@augmentd-labs/canvas-web 2.26.19 → 2.26.21
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/DocumentBodyEditor-CE2S2X6g.js +1 -0
- package/dist/assets/DocumentIcon-BS10SIP6.js +1 -0
- package/dist/assets/EditorOverlay-BUToR_av.js +1 -0
- package/dist/assets/FileForm-BxTixeDm.js +1 -0
- package/dist/assets/FiltersApplet-DNYAQP5F.js +1 -0
- package/dist/assets/HomeFab-CpTZdNyY.js +3 -0
- package/dist/assets/IdentityFields-C2MPM-Ab.js +1 -0
- package/dist/assets/LensApplet-CRa1j2WP.js +1 -0
- package/dist/assets/LinkToCard-BZwwE-Dv.js +1 -0
- package/dist/assets/LinkToSidePanel-eCy3nW4R.js +1 -0
- package/dist/assets/{LocationTab-BONJQfYM.js → LocationTab-DAtqAQ3l.js} +1 -1
- package/dist/assets/{MarkdownEditor-CkobBLtI.js → MarkdownEditor-7OqSDr7E.js} +1 -1
- package/dist/assets/MessageComposerDialog-DzLhkHyh.js +4 -0
- package/dist/assets/{NextShell-Byg6OtC2.js → NextShell-D9gvlKY2.js} +1 -1
- package/dist/assets/NotesApplet-CFK86JYj.js +1 -0
- package/dist/assets/ObjectPropertiesCard-C3jt40tM.css +1 -0
- package/dist/assets/ObjectPropertiesCard-DDcRLpsW.js +8 -0
- package/dist/assets/PathPickerField-cVs5sZuG.js +1 -0
- package/dist/assets/PickDocumentsCard-BlicxMqC.js +1 -0
- package/dist/assets/SketchApplet-D8mkYmK9.js +1 -0
- package/dist/assets/{SketchEditor-C9_lu3Ot.js → SketchEditor-zMrm1npg.js} +4 -4
- package/dist/assets/TerminalApplet-BO2HRp0z.js +20 -0
- package/dist/assets/TerminalApplet-BrP-ENHg.css +1 -0
- package/dist/assets/TextDocumentEditor-7V4aFL8i.js +1 -0
- package/dist/assets/TodosApplet-swdaBT-2.js +1 -0
- package/dist/assets/TodosWidget-BXF8fYer.js +1 -0
- package/dist/assets/UploadProgressList-B2xCVzFR.js +1 -0
- package/dist/assets/_agentId_-CHdTYJFu.js +0 -0
- package/dist/assets/_contextId_-m9zn5qav.js +1 -0
- package/dist/assets/_workspaceName_-D0z9E9Uy.js +1 -0
- package/dist/assets/about-pl0DXTEt.js +1 -0
- package/dist/assets/add-B30V-yHb.js +1 -0
- package/dist/assets/admin-Bhg9QBHL.js +5 -0
- package/dist/assets/agents-Bc7_wscP.js +1 -0
- package/dist/assets/agents-ClK3Y2x0.js +1 -0
- package/dist/assets/alert-dialog-DIA-tAP5.js +1 -0
- package/dist/assets/api-CA6WiiYM.js +1 -0
- package/dist/assets/api-tokens-O5iFESo0.js +1 -0
- package/dist/assets/appearance-DLo_2WH0.js +1 -0
- package/dist/assets/applet-target-DnTa2VAT.js +1 -0
- package/dist/assets/apps-DzFFo5D0.js +1 -0
- package/dist/assets/auth-Bx9fAZmz.js +1 -0
- package/dist/assets/auth-CUdpxbLV.js +1 -0
- package/dist/assets/backend-sync-progress-DU-e9TWi.css +1 -0
- package/dist/assets/backend-sync-progress-DWR42uQV.js +7 -0
- package/dist/assets/blobs-WiXP9QRi.js +1 -0
- package/dist/assets/button-Bv4zA1qr.js +1 -0
- package/dist/assets/chunk-62JRHF6Z-vspAGgtK.js +3 -0
- package/dist/assets/{chunk-K2UTITRG-zQFDOW3Q.js → chunk-K2UTITRG-BvHe9UPk.js} +3 -3
- package/dist/assets/code-editor-BOIngd5F.js +40 -0
- package/dist/assets/color-DFEH4BfK.js +1 -0
- package/dist/assets/content-app-view-BUi8HG1r.js +1 -0
- package/dist/assets/context-D_K4g9SQ.js +1 -0
- package/dist/assets/contexts-B6d6Axza.js +1 -0
- package/dist/assets/contexts-CgydYDn-2.js +1 -0
- package/dist/assets/date-time-picker-BZaA3M9_.js +1 -0
- package/dist/assets/desk-dI_FvLsK.js +1 -0
- package/dist/assets/devices-CAa1bRxk.js +1 -0
- package/dist/assets/devices-D3-_UWM0.js +1 -0
- package/dist/assets/document-BG_mODBn.js +1 -0
- package/dist/assets/document-list-BiogH4tf.js +2 -0
- package/dist/assets/document-list-DAYdk5vh.css +1 -0
- package/dist/assets/document-open-mode-DoImW-xs.js +1 -0
- package/dist/assets/embedding-Cjrxh6MN.js +1 -0
- package/dist/assets/embedding-m8SZH4oN.js +1 -0
- package/dist/assets/form-panel-Dz96K7Lv.js +1 -0
- package/dist/assets/geo-CZfs0E-x.js +1 -0
- package/dist/assets/home-C5IxNq_5.js +1 -0
- package/dist/assets/image-GAAHSSAO-CI-0hUck.js +1 -0
- package/dist/assets/index-D7EoeBID.css +2 -0
- package/dist/assets/index-DtZS4JJ4.js +16 -0
- package/dist/assets/inferd-config-editor-DagMmwW4.js +1 -0
- package/dist/assets/input-BOtCd4HP.js +1 -0
- package/dist/assets/key-bindings-DomR6ZNC.js +1 -0
- package/dist/assets/label-CNoJOoe0.js +1 -0
- package/dist/assets/last-path-BbXWC3b3.js +1 -0
- package/dist/assets/layer-style-Byl5LNFR.js +1 -0
- package/dist/assets/lazy-editor-Cbva8Pe2.js +2 -0
- package/dist/assets/logs-CdbfY8_H.js +1 -0
- package/dist/assets/{markdown-html-XoABNf32.js → markdown-html-CZMGihx6.js} +1 -1
- package/dist/assets/markdown-view-BBBZtNSR.js +2 -0
- package/dist/assets/note-save-status-DPz4VzL6.js +1 -0
- package/dist/assets/offline-BjMpUv3N.js +1 -0
- package/dist/assets/page-header-GtTr9Ff_.js +1 -0
- package/dist/assets/public-share-DT9Tgn_Y.js +1 -0
- package/dist/assets/query-debug-tVbB_8Z6.js +1 -0
- package/dist/assets/react-BHzhHVTZ.js +164 -0
- package/dist/assets/registry-BgnkvPjl.js +2 -0
- package/dist/assets/relation-events-CKio19hE.js +1 -0
- package/dist/assets/remotes-DR_iJClb.js +1 -0
- package/dist/assets/role-C5I0Plgn.js +1 -0
- package/dist/assets/roles-DERIgujv.js +2 -0
- package/dist/assets/roles-DswT1Lv0.js +2 -0
- package/dist/assets/settings-B4LC1yCH.js +1 -0
- package/dist/assets/settings-BXOyceZ3.js +1 -0
- package/dist/assets/settings-CUzf6xEQ.js +14 -0
- package/dist/assets/settings-DhoHM9AU.js +1 -0
- package/dist/assets/share-target-CpjVaYVl.js +1 -0
- package/dist/assets/shared-1dpCuibu.js +1 -0
- package/dist/assets/shared-B824Ibpc.js +1 -0
- package/dist/assets/sketch-lazy-Q58-vPF-.js +2 -0
- package/dist/assets/socket-CtH3EU9m.js +1 -0
- package/dist/assets/subtree-transfer-dialog-B7s4r78T.js +1 -0
- package/dist/assets/tags-YamdPoBK.js +1 -0
- package/dist/assets/text-documents-D_zDMyhB.js +2 -0
- package/dist/assets/{ui-BqHBdBU4.js → ui-BSqPn1LJ.js} +2 -2
- package/dist/assets/url-params-n7kU_WZ-.js +1 -0
- package/dist/assets/use-applet-docs-Cry2SFsG.js +1 -0
- package/dist/assets/use-applet-target-mkjQujx6.js +1 -0
- package/dist/assets/use-canvas-pins-C57Vbkrq.css +1 -0
- package/dist/assets/use-canvas-pins-CZBfEB5E.js +3 -0
- package/dist/assets/use-create-panel-DhSNIGtr.js +1 -0
- package/dist/assets/use-document-modal-PG8bQyIB.js +1 -0
- package/dist/assets/use-menu-BVkqNEIx.js +1 -0
- package/dist/assets/use-mobile-Db-vWu9Y.js +1 -0
- package/dist/assets/use-settings-back-Dk-DJEUO.js +1 -0
- package/dist/assets/use-sortable-data-DYIDDI8c.js +1 -0
- package/dist/assets/{use-theme-Bd8sb5Ox.js → use-theme-DaxpiICf.js} +1 -1
- package/dist/assets/use-toast-BlLDqSUO.js +1 -0
- package/dist/assets/use-toolbox-Ck_cLGgf.js +1 -0
- package/dist/assets/use-workspace-identity-BVpGHkZq.js +1 -0
- package/dist/assets/useAddTarget-CVRPElxz.js +1 -0
- package/dist/assets/useAgentModels-ndLotMWH.js +3 -0
- package/dist/assets/useDocumentThumbnail-C_rq2rXs.js +1 -0
- package/dist/assets/useEditNoteFields-Bigs9ZG8.js +1 -0
- package/dist/assets/useEscapeClose-DR_xKT_k.js +1 -0
- package/dist/assets/useSocketSubscription-ifW-vnlb.js +1 -0
- package/dist/assets/useToastHelpers-CRrpIIdY.js +1 -0
- package/dist/assets/users-C9N-O1QA.js +1 -0
- package/dist/assets/workspace-BydSRtST.js +1 -0
- package/dist/assets/workspace-CJ1PWQ29.js +1 -0
- package/dist/assets/workspace-access-C9nZlBBZ.js +1 -0
- package/dist/assets/workspace-area-menu-Ba_9bGKs.js +1 -0
- package/dist/assets/workspace-content-gate-D8bzGD9i.js +1 -0
- package/dist/assets/workspace-import-form-D5JA8gzx.js +1 -0
- package/dist/assets/workspaces-BBgdfAM_.js +1 -0
- package/dist/assets/workspaces-Dx5_N57M.js +1 -0
- package/dist/index.html +69 -14
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/EditorOverlay-B384ALjA.js +0 -1
- package/dist/assets/TextDocumentEditor-DBVWuJaR.js +0 -1
- package/dist/assets/alert-dialog-BC58hyW-.js +0 -1
- package/dist/assets/blobs-CtDkR2hC.js +0 -1
- package/dist/assets/code-editor-BQnKd3jw.js +0 -40
- package/dist/assets/document-list-BmUv3zzK.js +0 -19
- package/dist/assets/document-list-r-TfV16D.css +0 -1
- package/dist/assets/image-GAAHSSAO-BoD-NvEF.js +0 -1
- package/dist/assets/index-BhcdilCi.css +0 -2
- package/dist/assets/index-DRji5GQn.js +0 -61
- package/dist/assets/react-BzqgEMSQ.js +0 -164
- package/dist/assets/subtree-transfer-dialog-DRz8kLqY.js +0 -1
- package/dist/assets/text-documents-BvR9-zf4.js +0 -3
- package/dist/assets/useAddTarget-CgZfKokT.js +0 -1
- package/dist/assets/workspace-BSXnX2Me.js +0 -1
|
@@ -1,19 +0,0 @@
|
|
|
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-C9_lu3Ot.js","assets/react-BzqgEMSQ.js","assets/ui-BqHBdBU4.js","assets/utils-BxVxyehK.js","assets/alert-dialog-BC58hyW-.js","assets/utils-2pl1SbIp.js","assets/blobs-CtDkR2hC.js","assets/workspace-BSXnX2Me.js","assets/useAddTarget-CgZfKokT.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-B384ALjA.js","assets/SketchEditor-DtRVLazd.css","assets/TextDocumentEditor-DBVWuJaR.js","assets/text-documents-BvR9-zf4.js","assets/LocationTab-BONJQfYM.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/subtree-transfer-dialog-DRz8kLqY.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,An as l,Br as u,Bt as d,Cr as f,Ct as p,Dn as m,Dt as h,Er as g,Et as _,Ft as v,Gn as y,Gr as b,Gt as x,Hn as S,Hr as C,Ht as w,Ir as T,It as E,J as D,Jr as O,Jt as k,Kr as A,Kt as j,L as M,Ln as N,Lr as P,Lt as F,Mn as I,Mr as ee,Mt as L,Or as te,Pt as ne,Q as re,Qr as R,Qt as z,Rn as B,Rr as ie,Rt as ae,Sr as oe,Tr as se,Tt as ce,U as V,Un as le,Vn as H,Vr as ue,W as de,Wn as fe,Wr as pe,Wt as me,X as he,Xn as ge,Xr as _e,Xt as ve,Y as ye,Yn as be,Z as xe,_n as Se,ai as Ce,an as we,ci as Te,cr as Ee,ct as De,di as Oe,dn as ke,er as Ae,fi as U,fr as je,gn as Me,gr as Ne,gt as Pe,hn as Fe,hr as Ie,ii as Le,in as Re,ir as ze,li as Be,lr as Ve,mr as He,mt as Ue,ni as We,nr as Ge,nt as Ke,on as qe,or as Je,ot as Ye,qn as Xe,qr as Ze,rn as Qe,rr as $e,rt as et,sr as tt,st as nt,tr as rt,tt as it,ui as at,un as ot,ur as st,vi as ct,vr as lt,wt as ut,xr as dt,xt as ft,yn as pt,yr as mt,yt as ht,zr as gt,zt as _t}from"./ui-BqHBdBU4.js";import{t as W}from"./utils-2pl1SbIp.js";import{_ as vt,b as G,u as K,v as yt,x as q,y as bt}from"./alert-dialog-BC58hyW-.js";import{t as xt}from"./socket-hM4c-ZSl.js";import{l as St,s as Ct}from"./blobs-CtDkR2hC.js";import{A as wt,An as Tt,Bt as Et,Dn as Dt,Et as Ot,F as kt,Fn as At,Ft as jt,G as Mt,Hn as Nt,Ht as Pt,In as Ft,It,J as Lt,Jn as Rt,Kn as zt,Ln as Bt,Lt as Vt,Mn as Ht,Mt as Ut,P as Wt,Rt as Gt,Sn as Kt,Tn as qt,Ut as Jt,Wn as Yt,X as Xt,Xt as Zt,Y as Qt,Yn as $t,Yt as en,Z as tn,_n as nn,_t as rn,a as an,at as on,bn as sn,c as cn,d as ln,en as un,et as dn,ft as fn,g as pn,gn as mn,gt as hn,h as gn,hn as _n,jt as vn,k as yn,kn as bn,kt as xn,l as Sn,mn as Cn,q as wn,qn as Tn,r as En,rt as Dn,s as On,t as kn,tn as An,u as jn,v as Mn,xn as Nn,xt as Pn,yn as Fn,zn as In}from"./workspace-BSXnX2Me.js";import{a as Ln,c as Rn,d as zn,f as Bn,h as Vn,i as Hn,m as Un,n as Wn,o as Gn,p as Kn,r as qn,s as Jn,t as Yn,v as Xn,y as Zn}from"./text-documents-BvR9-zf4.js";import{A as Qn,C as $n,E as er,M as tr,R as nr,S as rr,k as ir,l as ar,o as or,v as sr,x as cr}from"./useAddTarget-CgZfKokT.js";import{t as lr}from"./sanitize-DrVcFY1Q.js";import{t as ur}from"./markdown-it-DRESbtwK.js";import{n as dr}from"./map-BxCwdK0d.js";import{t as fr}from"./search-COMZIxA7.js";var J=e(r(),1),pr=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,mr=/^[\\/]{2}/;function hr(e,t){return t+e.replace(/\\/g,`/`)}var gr=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(gr||{}),_r=`popstate`;function vr(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function yr(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return Cr(``,{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:wr(t)}return Er(t,n,null,e)}function Y(e,t){if(e===!1||e==null)throw Error(t)}function br(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function xr(){return Math.random().toString(36).substring(2,10)}function Sr(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 Cr(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?Tr(t):t,state:n,key:t&&t.key||r||xr(),mask:i}}function wr({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 Tr(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 Er(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=vr(e)?e:Cr(h.location,e,t);n&&n(r,e),l=u()+1;let d=Sr(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=vr(e)?e:Cr(h.location,e,t);n&&n(r,e),l=u();let i=Sr(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 Dr(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(_r,d),c=e,()=>{i.removeEventListener(_r,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 Dr(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Y(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:wr(t);return i=i.replace(/ $/,`%20`),!n&&mr.test(i)&&(i=r+i),new URL(i,r)}function Or(e,t,n=`/`){return kr(e,t,n,!1)}function kr(e,t,n,r,i){let a=Jr((typeof t==`string`?Tr(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Ar(e),s=null,c=qr(a);for(let e=0;s==null&&e<o.length;++e)s=Ur(o[e],c,r);return s}function Ar(e){let t=jr(e);return Nr(t),t}function jr(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;Y(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=ni([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Y(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),jr(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:Vr(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Kr(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 Mr(e.path))a(e,t,!0,n)}),t}function Mr(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=Mr(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 Nr(e){e.sort((e,t)=>e.score===t.score?Hr(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var Pr=/^:[\w-]+$/,Fr=3,Ir=2,Lr=1,Rr=10,zr=-2,Br=e=>e===`*`;function Vr(e,t){let n=e.split(`/`),r=n.length;return n.some(Br)&&(r+=zr),t&&(r+=Ir),n.filter(e=>!Br(e)).reduce((e,t)=>e+(Pr.test(t)?Fr:t===``?Lr:Rr),r)}function Hr(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 Ur(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?Gr(u,l,s.matcher,s.compiledParams):Wr(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=Wr({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:ni([a,d.pathname]),pathnameBase:ii(ni([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=ni([a,d.pathnameBase]))}return o}function Wr(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Kr(e.path,e.caseSensitive,e.end);return Gr(e,t,n,r)}function Gr(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 Kr(e,t=!1,n=!0){br(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 qr(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return br(!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 Jr(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 Yr(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?Tr(e):e,a;return n?(n=ti(n),a=n.startsWith(`/`)?Xr(n.substring(1),`/`):Xr(n,t)):a=t,{pathname:a,search:ai(r),hash:oi(i)}}function Xr(e,t){let n=ri(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Zr(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 Qr(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function $r(e){let t=Qr(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function ei(e,t,n,r=!1){let i;typeof e==`string`?i=Tr(e):(i={...e},Y(!i.pathname||!i.pathname.includes(`?`),Zr(`?`,`pathname`,`search`,i)),Y(!i.pathname||!i.pathname.includes(`#`),Zr(`#`,`pathname`,`hash`,i)),Y(!i.search||!i.search.includes(`#`),Zr(`#`,`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=Yr(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var ti=e=>e.replace(/[\\/]{2,}/g,`/`),ni=e=>ti(e.join(`/`)),ri=e=>e.replace(/\/+$/,``),ii=e=>ri(e).replace(/^\/*/,`/`),ai=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,oi=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,si=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 ci(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function li(e){return ni(e.map(e=>e.route.path).filter(Boolean))||`/`}var ui=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function di(e,t){let n=e;if(typeof n!=`string`||!pr.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(ui)try{let e=new URL(window.location.href),r=mr.test(n)?new URL(hr(n,e.protocol)):new URL(n),a=Jr(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{br(!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 fi=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(fi);var pi=[`GET`,...fi];new Set(pi);var mi=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function hi(e){try{return mi.includes(new URL(e).protocol)}catch{return!1}}var gi=J.createContext(null);gi.displayName=`DataRouter`;var _i=J.createContext(null);_i.displayName=`DataRouterState`;var vi=J.createContext(!1);function yi(){return J.useContext(vi)}var bi=J.createContext({isTransitioning:!1});bi.displayName=`ViewTransition`;var xi=J.createContext(new Map);xi.displayName=`Fetchers`;var Si=J.createContext(null);Si.displayName=`Await`;var Ci=J.createContext(null);Ci.displayName=`Navigation`;var wi=J.createContext(null);wi.displayName=`Location`;var Ti=J.createContext({outlet:null,matches:[],isDataRoute:!1});Ti.displayName=`Route`;var Ei=J.createContext(null);Ei.displayName=`RouteError`;var Di=`REACT_ROUTER_ERROR`,Oi=`REDIRECT`,ki=`ROUTE_ERROR_RESPONSE`;function Ai(e){if(e.startsWith(`${Di}:${Oi}:{`))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 ji(e){if(e.startsWith(`${Di}:${ki}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new si(t.status,t.statusText,t.data)}catch{}}function Mi(e,{relative:t}={}){Y(Ni(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=J.useContext(Ci),{hash:i,pathname:a,search:o}=Hi(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:ni([n,a])),r.createHref({pathname:s,search:o,hash:i})}function Ni(){return J.useContext(wi)!=null}function Pi(){return Y(Ni(),`useLocation() may be used only in the context of a <Router> component.`),J.useContext(wi).location}var Fi=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Ii(e){J.useContext(Ci).static||J.useLayoutEffect(e)}function Li(){let{isDataRoute:e}=J.useContext(Ti);return e?aa():Ri()}function Ri(){Y(Ni(),`useNavigate() may be used only in the context of a <Router> component.`);let e=J.useContext(gi),{basename:t,navigator:n}=J.useContext(Ci),{matches:r}=J.useContext(Ti),{pathname:i}=Pi(),a=JSON.stringify($r(r)),o=J.useRef(!1);return Ii(()=>{o.current=!0}),J.useCallback((r,s={})=>{if(br(o.current,Fi),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=ei(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:ni([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var zi=J.createContext(null);function Bi(e){let t=J.useContext(Ti).outlet;return J.useMemo(()=>t&&J.createElement(zi.Provider,{value:e},t),[t,e])}function Vi(){let{matches:e}=J.useContext(Ti);return e[e.length-1]?.params??{}}function Hi(e,{relative:t}={}){let{matches:n}=J.useContext(Ti),{pathname:r}=Pi(),i=JSON.stringify($r(n));return J.useMemo(()=>ei(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Ui(e,t){return Wi(e,t)}function Wi(e,t,n){Y(Ni(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=J.useContext(Ci),{matches:i}=J.useContext(Ti),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||``;sa(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=Pi(),d;if(t){let e=typeof t==`string`?Tr(t):t;Y(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):Or(e,{pathname:p});br(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),br(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=Zi(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:ni([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:ni([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?J.createElement(wi.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function Gi(){let e=ia(),t=ci(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=J.createElement(J.Fragment,null,J.createElement(`p`,null,`💿 Hey developer 👋`),J.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,J.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,J.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),J.createElement(J.Fragment,null,J.createElement(`h2`,null,`Unexpected Application Error!`),J.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?J.createElement(`pre`,{style:i},n):null,o)}var Ki=J.createElement(Gi,null),qi=class extends J.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=ji(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:J.createElement(Ti.Provider,{value:this.props.routeContext},J.createElement(Ei.Provider,{value:e,children:this.props.component}));return this.context?J.createElement(Yi,{error:e},t):t}};qi.contextType=vi;var Ji=new WeakMap;function Yi({children:e,error:t}){let{basename:n}=J.useContext(Ci);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Ai(t.digest);if(e){let r=Ji.get(t);if(r)throw r;let i=di(e.location,n),a=i.absoluteURL||i.to;if(hi(a))throw Error(`Invalid redirect location`);if(ui&&!Ji.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 Ji.set(t,n),n}}return J.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function Xi({routeContext:e,match:t,children:n}){let r=J.useContext(gi);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),J.createElement(Ti.Provider,{value:e},n)}function Zi(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);Y(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:li(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||Ki,o&&(s<0&&c===0?(sa(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?J.createElement(n.route.Component,null):n.route.element?n.route.element:e,J.createElement(Xi,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?J.createElement(qi,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Qi(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function $i(e){let t=J.useContext(gi);return Y(t,Qi(e)),t}function ea(e){let t=J.useContext(_i);return Y(t,Qi(e)),t}function ta(e){let t=J.useContext(Ti);return Y(t,Qi(e)),t}function na(e){let t=ta(e),n=t.matches[t.matches.length-1];return Y(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function ra(){return na(`useRouteId`)}function ia(){let e=J.useContext(Ei),t=ea(`useRouteError`),n=na(`useRouteError`);return e===void 0?t.errors?.[n]:e}function aa(){let{router:e}=$i(`useNavigate`),t=na(`useNavigate`),n=J.useRef(!1);return Ii(()=>{n.current=!0}),J.useCallback(async(r,i={})=>{br(n.current,Fi),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var oa={};function sa(e,t,n){!t&&!oa[e]&&(oa[e]=!0,br(!1,n))}J.memo(ca);function ca({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Wi(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function la({to:e,replace:t,state:n,relative:r}){Y(Ni(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=J.useContext(Ci);br(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=J.useContext(Ti),{pathname:o}=Pi(),s=Li(),c=ei(e,$r(a),o,r===`path`),l=JSON.stringify(c);return J.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function ua(e){return Bi(e.context)}function da(e){Y(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function fa({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Y(!Ni(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=J.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=Tr(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=J.useMemo(()=>{let e=Jr(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 br(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:J.createElement(Ci.Provider,{value:c},J.createElement(wi.Provider,{children:t,value:h}))}function pa({children:e,location:t}){return Ui(ma(e),t)}J.Component;function ma(e,t=[]){let n=[];return J.Children.forEach(e,(e,r)=>{if(!J.isValidElement(e))return;let i=[...t,r];if(e.type===J.Fragment){n.push.apply(n,ma(e.props.children,i));return}Y(e.type===da,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Y(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=ma(e.props.children,i)),n.push(a)}),n}var ha=`get`,ga=`application/x-www-form-urlencoded`;function _a(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function va(e){return _a(e)&&e.tagName.toLowerCase()===`button`}function ya(e){return _a(e)&&e.tagName.toLowerCase()===`form`}function ba(e){return _a(e)&&e.tagName.toLowerCase()===`input`}function xa(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Sa(e,t){return e.button===0&&(!t||t===`_self`)&&!xa(e)}function Ca(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 wa(e,t){let n=Ca(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Ta=null;function Ea(){if(Ta===null)try{new FormData(document.createElement(`form`),0),Ta=!1}catch{Ta=!0}return Ta}var Da=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Oa(e){return e!=null&&!Da.has(e)?(br(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${ga}"`),null):e}function ka(e,t){let n,r,i,a,o;if(ya(e)){let o=e.getAttribute(`action`);r=o?Jr(o,t):null,n=e.getAttribute(`method`)||ha,i=Oa(e.getAttribute(`enctype`))||ga,a=new FormData(e)}else if(va(e)||ba(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?Jr(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||ha,i=Oa(e.getAttribute(`formenctype`))||Oa(o.getAttribute(`enctype`))||ga,a=new FormData(o,e),!Ea()){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(_a(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=ha,r=null,i=ga,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 Aa(e,t){if(e===!1||e==null)throw Error(t)}function ja(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&&Jr(i.pathname,t)===`/`?`${ri(t)}/_root.${r}`:`${ri(i.pathname)}.${r}`,i}async function Ma(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 Na(e){return e!=null&&typeof e.page==`string`}function Pa(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 Fa(e,t,n){return Ba((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Ma(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Pa).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Ia(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 La(e,t,{includeHydrateFallback:n}={}){return Ra(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 Ra(e){return[...new Set(e)]}function za(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Ba(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!Na(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(za(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function Va(){let e=J.useContext(gi);return Aa(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function Ha(){let e=J.useContext(_i);return Aa(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Ua=J.createContext(void 0);Ua.displayName=`FrameworkContext`;function Wa(){let e=J.useContext(Ua);return Aa(e,`You must render this element inside a <HydratedRouter> element`),e}function Ga(e,t){let n=J.useContext(Ua),[r,i]=J.useState(!1),[a,o]=J.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=J.useRef(null);J.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),J.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:Ka(s,p),onBlur:Ka(c,m),onMouseEnter:Ka(l,p),onMouseLeave:Ka(u,m),onTouchStart:Ka(d,p)}]:[a,f,{}]:[!1,f,{}]}function Ka(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function qa({page:e,...t}){let n=yi(),{nonce:r}=Wa(),{router:i}=Va(),a=J.useMemo(()=>Or(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?J.createElement(Ya,{page:e,matches:a,...t}):J.createElement(Xa,{page:e,matches:a,...t})):null}function Ja(e){let{manifest:t,routeModules:n}=Wa(),[r,i]=J.useState([]);return J.useEffect(()=>{let r=!1;return Fa(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Ya({page:e,matches:t,...n}){let r=Pi(),{future:i}=Wa(),{basename:a}=Va(),o=J.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=ja(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return J.createElement(J.Fragment,null,o.map(e=>J.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function Xa({page:e,matches:t,...n}){let r=Pi(),{future:i,manifest:a,routeModules:o}=Wa(),{basename:s}=Va(),{loaderData:c,matches:l}=Ha(),u=J.useMemo(()=>Ia(e,t,l,a,r,`data`),[e,t,l,a,r]),d=J.useMemo(()=>Ia(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=J.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=ja(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=J.useMemo(()=>La(d,a),[d,a]),m=Ja(d);return J.createElement(J.Fragment,null,f.map(e=>J.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>J.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>J.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Za(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}J.Component;var Qa=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Qa&&(window.__reactRouterVersion=`7.18.2`)}catch{}function $a({basename:e,children:t,useTransitions:n,window:r}){let i=J.useRef();i.current??=yr({window:r,v5Compat:!0});let a=i.current,[o,s]=J.useState({action:a.action,location:a.location}),c=J.useCallback(e=>{n===!1?s(e):J.startTransition(()=>s(e))},[n]);return J.useLayoutEffect(()=>a.listen(c),[a,c]),J.createElement(fa,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var eo=J.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=J.useContext(Ci),v=typeof l==`string`&&pr.test(l),y=di(l,h);l=y.to;let b=Mi(l,{relative:r}),x=Pi(),S=null;if(o){let e=ei(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:ni([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=Ga(n,p),E=ao(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=J.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:Za(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?J.createElement(J.Fragment,null,k,J.createElement(qa,{page:b})):k});eo.displayName=`Link`;var to=J.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=Hi(a,{relative:c.relative}),d=Pi(),f=J.useContext(_i),{navigator:p,basename:m}=J.useContext(Ci),h=f!=null&&fo(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=Jr(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return J.createElement(eo,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});to.displayName=`NavLink`;var no=J.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=ha,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=J.useContext(Ci),g=lo(),_=uo(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&pr.test(s);return J.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?J.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});no.displayName=`Form`;function ro(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function io(e){let t=J.useContext(gi);return Y(t,ro(e)),t}function ao(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Li(),d=Pi(),f=Hi(e,{relative:o});return J.useCallback(p=>{if(Sa(p,t)){p.preventDefault();let t=n===void 0?wr(d)===wr(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?J.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function oo(e){br(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=J.useRef(Ca(e)),n=J.useRef(!1),r=Pi(),i=J.useMemo(()=>wa(r.search,n.current?null:t.current),[r.search]),a=Li();return[i,J.useCallback((e,t)=>{let r=Ca(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var so=0,co=()=>`__${String(++so)}__`;function lo(){let{router:e}=io(`useSubmit`),{basename:t}=J.useContext(Ci),n=ra(),r=e.fetch,i=e.navigate;return J.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=ka(e,t);if(a.navigate===!1){let e=a.fetcherKey||co();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 uo(e,{relative:t}={}){let{basename:n}=J.useContext(Ci),r=J.useContext(Ti);Y(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...Hi(e||`.`,{relative:t})},o=Pi();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:ni([n,a.pathname])),wr(a)}function fo(e,{relative:t}={}){let n=J.useContext(bi);Y(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=io(`useViewTransitionState`),i=Hi(e,{relative:t});if(!n.isTransitioning)return!1;let a=Jr(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Jr(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Wr(i.pathname,o)!=null||Wr(i.pathname,a)!=null}var po=e(o(),1),X=n(),mo=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(ct,{ref:n,className:W(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));mo.displayName=ct.displayName;function ho(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var go=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=bt,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||ho();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=xt(this.baseUrl,{transports:[`websocket`],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.5,timeout:1e4,forceNew:!0,extraHeaders:{Authorization:`Bearer ${t}`,"X-Connection-ID":this.connectionId},auth:{token:t}}),this.setupDefaultHandlers(),this.registerHandlers(),this.socket.connect())}cleanupSocket(){this.socket?.removeAllListeners(),this.socket?.disconnect(),this.socket=null,this.connected=!1,this.socketWrappers.clear()}setupDefaultHandlers(){this.socket&&(this.socket.on(`connect`,()=>{this.connected=!0;for(let e of this.desiredSubscriptions)this.socket?.emit(`subscribe`,{channel:e})}),this.socket.on(`disconnect`,()=>{this.connected=!1}),this.socket.on(`connect_error`,()=>{this.connected=!1}))}registerHandlers(){this.socket&&this.handlers.forEach((e,t)=>{e.forEach(e=>{this.attach(t,e)})})}attach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e);if(n||(n=new Map,this.socketWrappers.set(e,n)),n.has(t))return;let r=(...e)=>t(...e);n.set(t,r),this.socket.on(e,r)}detach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e),r=n?.get(t);r&&(this.socket.off(e,r),n?.delete(t),n&&n.size===0&&this.socketWrappers.delete(e))}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);let n=this.handlers.get(e);return n.has(t)?()=>this.off(e,t):(n.add(t),this.socket&&this.attach(e,t),()=>this.off(e,t))}off(e,t){let n=this.handlers.get(e);n&&n.has(t)&&(n.delete(t),n.size===0&&this.handlers.delete(e),this.detach(e,t))}request(e,t,n=1e4){return new Promise((r,i)=>{if(!this.socket||!this.connected){i(Error(`Socket not connected`));return}let a=!1,o=setTimeout(()=>{a||(a=!0,i(Error(`Socket request timed out: ${e}`)))},n);try{this.socket.emit(e,t??{},t=>{a||(a=!0,clearTimeout(o),t?.status===`error`?i(Error(t.message||`${e} failed`)):r(t?.payload??t))})}catch(e){a=!0,clearTimeout(o),i(e instanceof Error?e:Error(String(e)))}})}emit(e,...t){if(e===`subscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.add(e)}else if(e===`unsubscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.delete(e)}if(this.socket&&this.connected)try{this.socket.emit(e,...t)}catch(t){console.error(`Error emitting event ${e}:`,t),this.reconnect()}else this.connect()}disconnect(){this.cleanupSocket(),this.authToken=null,this.desiredSubscriptions.clear()}isConnected(){return this.connected}retryNow(){this.connected||(this.cleanupSocket(),this.connect())}reconnect(){this.connect()}};function _o({className:e=`h-5 w-5`,...t}){return(0,X.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,X.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,X.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}var vo=(0,J.createContext)(null),yo=()=>(0,J.useContext)(vo),bo=[{id:`square`,label:`Square (Lychee-like)`},{id:`flickr`,label:`Justified (Flickr-like)`},{id:`masonry`,label:`Masonry (500px-like)`},{id:`original`,label:`Original proportions`}],xo=`canvas:tileStyle`;function So(){try{let e=localStorage.getItem(xo);return bo.some(t=>t.id===e)?e:`masonry`}catch{return`masonry`}}var Co=So(),wo=new Set;function To(){return Co}function Eo(e){try{localStorage.setItem(xo,e)}catch{}Co=e;for(let e of wo)e()}function Do(e){wo.add(e);let t=t=>{(t.key===xo||t.key===null)&&(Co=So(),e())};return window.addEventListener(`storage`,t),()=>{wo.delete(e),window.removeEventListener(`storage`,t)}}function Oo(){return(0,J.useSyncExternalStore)(Do,To,()=>`masonry`)}var ko=`canvas:alwaysOnReader`;function Ao(){try{return localStorage.getItem(ko)!==`off`}catch{return!0}}var jo=Ao(),Mo=new Set;function No(){return jo}function Po(e){try{localStorage.setItem(ko,e?`on`:`off`)}catch{}jo=e;for(let e of Mo)e()}function Fo(e){Mo.add(e);let t=t=>{(t.key===ko||t.key===null)&&(jo=Ao(),e())};return window.addEventListener(`storage`,t),()=>{Mo.delete(e),window.removeEventListener(`storage`,t)}}function Io(){return(0,J.useSyncExternalStore)(Fo,No,()=>!0)}var Lo=`canvas:readerWidth`,Ro=320,zo=1600;function Bo(){try{let e=Number(sessionStorage.getItem(Lo));return Number.isFinite(e)&&e>=Ro&&e<=zo?e:null}catch{return null}}var Vo=Bo(),Ho=new Set;function Uo(e){return Ho.add(e),()=>{Ho.delete(e)}}function Wo(e){Vo=e===null?null:Math.round(Math.max(Ro,Math.min(zo,e)));try{Vo===null?sessionStorage.removeItem(Lo):sessionStorage.setItem(Lo,String(Vo))}catch{}Ho.forEach(e=>e())}function Go(){return(0,J.useSyncExternalStore)(Uo,()=>Vo,()=>null)}var Ko=`(max-width: 767px)`,qo=new Map;function Jo(e){let t=qo.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},qo.set(e,t)}return t}function Yo(){let e=Jo(Ko);return(0,J.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>!1)}function Xo(){return Zo(`(max-width: 1023px)`)}function Zo(e){let t=Jo(e);return(0,J.useSyncExternalStore)(t.subscribe,t.getSnapshot,()=>!1)}var Qo=1,$o=8,es=320,ts=28,ns=2.5,rs={scale:1,x:0,y:0};function is({src:e,alt:t,className:n=``,onZoomChange:r}){let i=(0,J.useRef)(null),a=(0,J.useRef)(null),[o,s]=(0,J.useState)(rs),c=(0,J.useRef)(new Map),l=(0,J.useRef)(null),u=(0,J.useRef)(null),d=(0,J.useRef)(!1),f=(0,J.useRef)(null),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(e);h!==e&&(g(e),s(rs)),(0,J.useEffect)(()=>{r?.(o.scale>1.001)},[o.scale,r]);let _=(0,J.useCallback)(e=>{let t=i.current,n=a.current;if(!t||!n)return e;let r=Math.min($o,Math.max(Qo,e.scale)),o=Math.max(0,(n.offsetWidth*r-t.clientWidth)/2),s=Math.max(0,(n.offsetHeight*r-t.clientHeight)/2);return{scale:r,x:Math.min(o,Math.max(-o,e.x)),y:Math.min(s,Math.max(-s,e.y))}},[]),v=(0,J.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let a=r.getBoundingClientRect(),o=t-a.left-a.width/2,c=n-a.top-a.height/2;s(t=>{let n=e/t.scale;return _({scale:e,x:o-(o-t.x)*n,y:c-(c-t.y)*n})})},[_]),y=(0,J.useCallback)(()=>{let e=i.current,t=a.current;if(!e||!t||!t.offsetWidth||!t.offsetHeight)return ns;let n=Math.max(e.clientWidth/t.offsetWidth,e.clientHeight/t.offsetHeight),r=Math.max(t.naturalWidth/t.offsetWidth,t.naturalHeight/t.offsetHeight)||$o;return Math.min($o,Math.max(ns,Math.min(Math.max(n,ns),r)))},[]),b=(0,J.useCallback)((e,t)=>{o.scale>1.001?s(rs):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<es&&Math.hypot(e.clientX-n.x,e.clientY-n.y)<ts){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<=Qo?s(rs):v(Math.min($o,t),e.clientX,e.clientY)},T=o.scale>1.001;return(0,X.jsx)(`div`,{ref:i,className:`relative flex h-full w-full items-center justify-center overflow-hidden`,style:{touchAction:`none`,cursor:T?`grab`:`zoom-in`},onPointerDown:x,onPointerMove:S,onPointerUp:C,onPointerCancel:e=>{c.current.delete(e.pointerId),l.current=null,u.current=null,d.current=!0,c.current.size===0&&m(!1)},onWheel:w,onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),!(f.current!==null&&e.timeStamp-f.current<es)&&b(e.clientX,e.clientY)},children:(0,X.jsx)(`img`,{ref:a,src:e,alt:t,draggable:!1,className:n,style:{transform:`translate3d(${o.x}px, ${o.y}px, 0) scale(${o.scale})`,transformOrigin:`center center`,transition:p?`none`:`transform var(--duration-normal) ease-out`,willChange:`transform`}})})}var as=(0,J.createContext)(null);function os(){return!/android|iphone|ipad|mobile/i.test(navigator.userAgent)&&navigator.pdfViewerEnabled!==!1}var ss=40,cs=1600;function ls({blob:e,filename:t}){let n=(0,J.useRef)(null),[r,i]=(0,J.useState)({error:null,pages:0,truncated:!1});return(0,J.useEffect)(()=>{let r=n.current;if(!r)return;let a=!1,o=null;return(async()=>{let n=await s(()=>import(`./pdf-Ciz5_WNq.js`),__vite__mapDeps([0,1])),c=(await s(async()=>{let{default:e}=await import(`./pdf.worker.min-C8Ts8bNu.js`);return{default:e}},[])).default;n.GlobalWorkerOptions.workerSrc=c;let l=await e.arrayBuffer();if(a)return;let u=n.getDocument({data:l});o=()=>{u.destroy()};let d=await u.promise;if(a)return;let f=Math.min(d.numPages,ss),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,cs*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>ss})}})().catch(e=>{a||i(t=>({...t,error:e instanceof Error?e.message:String(e)}))}),()=>{a=!0,o?.(),r.replaceChildren()}},[e,t]),(0,X.jsxs)(`div`,{className:`space-y-2`,children:[r.error&&(0,X.jsxs)(`p`,{className:`text-sm text-destructive`,children:[`Could not render PDF: `,r.error]}),!r.error&&r.pages===0&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering PDF…`}),(0,X.jsx)(`div`,{ref:n,className:`space-y-2`}),r.truncated&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,ss,` pages. Download the file for the full document.`]})]})}function us({blob:e,blobUrl:t,filename:n,className:r=``}){let i=(0,J.useMemo)(()=>e&&e.type!==`application/pdf`?URL.createObjectURL(e.slice(0,e.size,`application/pdf`)):null,[e]);return(0,J.useEffect)(()=>()=>{i&&URL.revokeObjectURL(i)},[i]),os()||!e?(0,X.jsx)(`div`,{className:`min-h-[300px] ${r}`,children:(0,X.jsx)(`iframe`,{src:i??t,className:`h-full min-h-[300px] w-full rounded border`,title:n})}):(0,X.jsx)(`div`,{className:`max-h-viewport-pane overflow-y-auto ${r}`,children:(0,X.jsx)(ls,{blob:e,filename:n})})}function ds(e,t,n=256,{enabled:r=!0,blobFallback:i=!0,version:a=null}={}){let{isPublic:o,fetchBlob:s,fetchThumbnail:c}=Xn(e),l=`${o?`pub`:`ws`}:${e}:${t}:${n}:${r}:${a??``}`,[u,d]=(0,J.useState)({blobUrl:null,error:null,loading:r}),[f,p]=(0,J.useState)(l);return l!==f&&(p(l),d({blobUrl:null,error:null,loading:r})),(0,J.useEffect)(()=>{if(!r)return;let e=!1,o=null;return c(t,n,a).catch(e=>{if(!i)throw e;return s(t)}).then(({blob:t})=>{e||(o=URL.createObjectURL(t),d({blobUrl:o,error:null,loading:!1}))}).catch(t=>{e||d({blobUrl:null,error:String(t instanceof Error?t.message:t),loading:!1})}),()=>{e=!0,o&&URL.revokeObjectURL(o)}},[l]),u}function fs({workspaceId:e,document:t}){let{download:n}=Xn(e),[r,i]=(0,J.useState)(!1),a=Bt(t)||`document-${t.id}`;return(0,X.jsxs)(`button`,{type:`button`,onClick:async()=>{i(!0);try{await n(t.id,a)}finally{i(!1)}},disabled:r,className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,X.jsx)(Ne,{className:`h-3.5 w-3.5`}),r?`Preparing…`:`Download`]})}var ps=1600;function ms({error:e,loading:t,children:n}){return e?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:e}):t?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading preview...`}):(0,X.jsx)(X.Fragment,{children:n})}function hs({workspaceId:e,document:t,className:n=``}){let r=(0,J.useContext)(as),i=Yo(),a=Zo(`(pointer: coarse)`),{blobUrl:o,error:s,loading:c}=ds(e,t.id,ps,{version:t.checksumArray?.[0]??null}),{fetchBlob:l}=Xn(e),u=Bt(t)||`document-${t.id}`,[d,f]=(0,J.useState)(!1);return(0,X.jsx)(ms,{error:s,loading:c,children:o&&(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[i||a?(0,X.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,X.jsx)(is,{src:o,alt:u,className:`max-h-full max-w-full object-contain`})}):(0,X.jsx)(`img`,{src:o,alt:u,draggable:!1,onDoubleClick:r?e=>{e.preventDefault(),e.stopPropagation(),r()}:void 0,title:r?`Double-click to maximize or restore`:void 0,className:`min-h-0 w-full flex-1 object-contain ${r?`cursor-zoom-in`:``}`}),(0,X.jsxs)(`button`,{type:`button`,onClick:async()=>{f(!0);try{let{blob:e}=await l(t.id),n=URL.createObjectURL(e),r=window.document.createElement(`a`);r.href=n,r.download=u,window.document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),3e4)}finally{f(!1)}},disabled:d,className:`inline-flex shrink-0 self-start items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,X.jsx)(Ne,{className:`h-3.5 w-3.5`}),d?`Preparing…`:`Download original`]})]})})}function gs({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Vn(e,t.id);return(0,X.jsx)(ms,{error:i,loading:a,children:r&&(0,X.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,X.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`,className:`w-full`}),(0,X.jsx)(fs,{workspaceId:e,document:t})]})})}function _s({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Vn(e,t.id),[o,s]=(0,J.useState)(!1);return(0,X.jsx)(ms,{error:i,loading:a,children:r&&(0,X.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,X.jsx)(`video`,{src:r,controls:!0,playsInline:!0,preload:`metadata`,onError:()=>s(!0),className:`max-h-viewport-pane w-full rounded border`}),o&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This video can’t be played inline in your browser. Download it to view.`}),(0,X.jsx)(fs,{workspaceId:e,document:t})]})})}function vs({workspaceId:e,document:t,className:n=``}){let{blobUrl:r,blob:i,error:a,loading:o}=Un(e,t.id,{typeHint:`application/pdf`}),s=Bt(t)||`document-${t.id}`;return(0,X.jsx)(ms,{error:a,loading:o,children:r&&(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[(0,X.jsx)(us,{blob:i,blobUrl:r,filename:s,className:`min-h-0 flex-1`}),(0,X.jsx)(`div`,{children:(0,X.jsx)(fs,{workspaceId:e,document:t})})]})})}var ys=(0,J.lazy)(()=>s(()=>import(`./markdown-html-XoABNf32.js`),__vite__mapDeps([2,3,4,5,6,7,8])));function bs({content:e,className:t=``,preview:n=!1}){return(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`div`,{className:`whitespace-pre-wrap break-words ${t}`,children:e}),children:(0,X.jsx)(ys,{content:e,className:t,preview:n})})}function xs({workspaceId:e,document:t,className:n=``}){let{text:r,error:i,loading:a}=Un(e,t.id,{mode:`text`,version:t.checksumArray?.[0]});return i?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):a||r==null?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,X.jsx)(`pre`,{className:`bg-muted p-3 rounded text-xs overflow-auto max-h-viewport-pane whitespace-pre-wrap ${n}`,children:r})}function Ss({workspaceId:e,document:t,className:n=``}){let r=t.schema===Yt,{text:i,error:a,loading:o}=Un(e,t.id,{mode:`text`,enabled:!r,version:t.checksumArray?.[0]});return r?(0,X.jsxs)(`div`,{className:`markdown-note space-y-3 ${n}`,children:[t.data?.title?(0,X.jsx)(`h3`,{className:`text-lg font-semibold`,children:String(t.data.title)}):null,(0,X.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent`,children:(0,X.jsx)(bs,{content:String(t.data?.content??``),className:`markdown-doc px-4 py-3`})})]}):a?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:a}):o||i==null?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,X.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent overflow-auto max-h-viewport-pane ${n}`,children:(0,X.jsx)(bs,{content:i,className:`markdown-doc px-4 py-3`})})}function Cs({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),r=$t(n);return r?(0,X.jsx)(`div`,{className:`aspect-video w-full ${t}`,children:(0,X.jsx)(`iframe`,{src:`https://www.youtube-nocookie.com/embed/${encodeURIComponent(r)}`,title:String(e.data?.title??e.data?.label??`YouTube video`),className:`h-full w-full rounded border`,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0})}):null}function ws({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),[r,i]=(0,J.useState)({blobUrl:null,blob:null,failed:!1,loading:!0}),[a,o]=(0,J.useState)(n);n!==a&&(o(n),i({blobUrl:null,blob:null,failed:!1,loading:!0})),(0,J.useEffect)(()=>{let e=!1,t=null,r=async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.blob();return new Blob([t],{type:`application/pdf`})},a=()=>{let e=localStorage.getItem(`authToken`);return fetch(`${yt}/proxy/pdf?url=${encodeURIComponent(n)}`,{headers:e?{Authorization:`Bearer ${e}`}:{}})};return fetch(n).then(r).catch(()=>a().then(r)).then(n=>{e||(t=URL.createObjectURL(n),i({blobUrl:t,blob:n,failed:!1,loading:!1}))}).catch(()=>{e||i({blobUrl:null,blob:null,failed:!0,loading:!1})}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[n]);let{blobUrl:s,blob:c,failed:l,loading:u}=r,d=(()=>{try{let e=decodeURIComponent(new URL(n).pathname.split(`/`).filter(Boolean).pop()??``)||`document`;return/\.pdf$/i.test(e)?e:`${e}.pdf`}catch{return`document.pdf`}})();return(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${t}`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3`,children:[(0,X.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs text-primary hover:underline`,children:[(0,X.jsx)(je,{className:`h-3 w-3`}),` `,n]}),c&&(0,X.jsxs)(`button`,{type:`button`,onClick:()=>{if(!c)return;let e=URL.createObjectURL(c),t=window.document.createElement(`a`);t.href=e,t.download=d,window.document.body.appendChild(t),t.click(),t.remove(),setTimeout(()=>URL.revokeObjectURL(e),3e4)},className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:[(0,X.jsx)(Ne,{className:`h-3.5 w-3.5`}),` Download`]})]}),u&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading PDF…`}),l&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Inline preview unavailable (direct fetch and server proxy both failed). Use the link above.`}),s&&(0,X.jsx)(us,{blob:c,blobUrl:s,filename:d,className:`min-h-[300px] flex-1`})]})}function Ts(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 Es(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function Ds({document:e,className:t=``}){let n=e.data||{},r=String(n.url??n.uri??``),i=String(n.title??n.label??``)||Es(r),a=typeof n.favIconUrl==`string`?n.favIconUrl:``,o=n.pinned===!0,s=typeof n.timestamp==`string`?n.timestamp:null,[c,l]=(0,J.useState)(!1);return(0,X.jsxs)(`div`,{className:`space-y-3 ${t}`,children:[(0,X.jsxs)(`a`,{href:r,target:`_blank`,rel:`noopener noreferrer`,className:`group flex items-start gap-3 rounded-lg border bg-card p-3 transition-colors hover:bg-accent/40`,children:[(0,X.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded bg-muted`,children:a&&!c?(0,X.jsx)(`img`,{src:a,alt:``,className:`h-5 w-5`,onError:()=>l(!0)}):(0,X.jsx)(H,{className:`h-4 w-4 text-muted-foreground`})}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,X.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:i}),o&&(0,X.jsx)(v,{className:`h-3 w-3 shrink-0 fill-warning text-warning`})]}),(0,X.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-muted-foreground`,children:Es(r)}),(0,X.jsx)(`div`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground/70`,children:r})]}),(0,X.jsx)(je,{className:`mt-1 h-4 w-4 shrink-0 text-muted-foreground reveal-on-hover`})]}),s&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Saved `,new Date(s).toLocaleString()]})]})}var Os={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4};function ks(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 As(){return new Promise((e,t)=>navigator.geolocation.getCurrentPosition(e,t,Os))}function js(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 Ms(){let e=typeof navigator<`u`&&`geolocation`in navigator&&typeof window<`u`&&window.isSecureContext,[t,n]=(0,J.useState)(e?`prompt`:`unsupported`),[r,i]=(0,J.useState)(!1),[a,o]=(0,J.useState)(!1),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(null),[d,f]=(0,J.useState)(null),[p,m]=(0,J.useState)(null),h=(0,J.useRef)(!1),g=(0,J.useRef)(null),_=(0,J.useRef)(null);(0,J.useEffect)(()=>{if(!e||!navigator.permissions?.query)return;let t=!1,r=null;return navigator.permissions.query({name:`geolocation`}).then(e=>{t||(r=e,n(e.state),e.onchange=()=>n(e.state))}).catch(()=>{}),()=>{t=!0,r&&(r.onchange=null)}},[e]);let v=(0,J.useCallback)(e=>{if(c(null),!e){_.current=null,f(null),m(null),h.current||i(!1);return}let t={lat:e.lat,lon:e.lon,source:`manual`};_.current=t,f(t),m(e.label??null),i(!0)},[]);return{supported:e,permission:t,enabled:r,busy:a,error:s,fix:l,setEnabled:(0,J.useCallback)(t=>{if(c(null),!t){h.current=!1,_.current=null,f(null),m(null),i(!1);return}_.current||e&&(h.current=!0,i(!0),o(!0),As().then(e=>{let t=ks(e);g.current=t,u(t),n(`granted`)}).catch(e=>{c(js(e)),e?.code===1&&(n(`denied`),h.current=!1,i(!1))}).finally(()=>o(!1)))},[e]),manual:d,manualLabel:p,setManual:v,capture:(0,J.useCallback)(async()=>{if(_.current)return _.current;if(!h.current||!e)return null;try{return ks(await As())}catch{return g.current}},[e])}}var Ns=`2.1`,Ps=[`pending`,`in-progress`,`completed`,`cancelled`],Fs={pending:`Pending`,"in-progress":`In progress`,completed:`Completed`,cancelled:`Cancelled`};function Is(e){return String(e).padStart(2,`0`)}function Ls(e){return`${e.getFullYear()}-${Is(e.getMonth()+1)}-${Is(e.getDate())}T${Is(e.getHours())}:${Is(e.getMinutes())}`}function Rs(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:Ls(t)}function zs(e){if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function Bs(){let e=new Date;return e.setHours(23,59,0,0),Ls(e)}function Vs(e){let t=zs(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 Hs(){let[e,t]=(0,J.useState)(``),[n,r]=(0,J.useState)(``),[i,a]=(0,J.useState)(`pending`),[o,s]=(0,J.useState)(``),[c,l]=(0,J.useState)(Bs()),[u,d]=(0,J.useState)([]),[f,p]=(0,J.useState)(``),[m,h]=(0,J.useState)(!1),g=Ms(),_=e.trim().length>0&&!m;async function v(t){h(!0);try{let r=await g.capture(),a=f.trim(),s={schema:zt,schemaVersion:Ns,data:Vs({title:e,description:n,status:i,priority:o,due:c}),...a?{comment:a}:{},metadata:{features:Kn(u),...r?{geo:r}:{}}};return await or(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 Us(e){return e.data||{}}var Ws={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 Gs(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 Ks(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 qs(e,t,n){let r=n===`completed`,i={...t.data||{},status:n,completed:r};r?i.completedAt=new Date().toISOString():delete i.completedAt,await qt(e,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:i}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}function Js({document:e,workspaceId:t,className:n=``}){let r=Us(e),i=Zn()!=null,[a,o]=(0,J.useState)(!1),{replicating:s,label:c}=bn(e),l=r.status===`completed`,u=r.status??`pending`,d=Gs(r);return(0,X.jsx)(`div`,{className:`space-y-3 ${n}`,children:(0,X.jsxs)(`div`,{className:`relative flex items-start gap-3 rounded-lg border bg-card p-3 transition-opacity ${s?`opacity-60`:``}`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(i||a)){o(!0);try{await qs(t,e,l?`pending`:`completed`)}catch{}finally{o(!1)}}},disabled:i||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${i?`cursor-default opacity-70`:``}`,children:a?(0,X.jsx)(ke,{className:`h-3 w-3 animate-spin`}):l&&(0,X.jsx)(C,{className:`h-3.5 w-3.5`})}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsx)(`div`,{className:`font-medium leading-tight ${l?`text-muted-foreground line-through`:``}`,children:r.title||`Todo ${e.id}`}),(0,X.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-2 text-xs`,children:[(0,X.jsx)(`span`,{className:`rounded-full px-2 py-0.5 ${Ws[u]}`,children:Fs[u]}),r.dueDate&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,X.jsx)(A,{className:`h-3 w-3`}),Ks(r.dueDate),d?` · overdue`:``]}),typeof r.priority==`number`&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,children:[(0,X.jsx)(Ae,{className:`h-3 w-3`}),`P`,r.priority]})]}),r.description&&(0,X.jsx)(bs,{content:String(r.description),className:`mt-2 text-sm text-muted-foreground`}),s&&(0,X.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground`,role:`status`,children:[(0,X.jsx)(ke,{className:`h-3 w-3 animate-spin`}),c]})]})]})})}function Ys(e,t){let{fetchBlob:n}=Xn(e),r=Zn(),i=t.checksumArray?.[0]||t.updatedAt||``,a=JSON.stringify([e,r,t.id,i]),o=typeof t.data?.body==`string`?t.data.body:null,s=typeof t.data?.bodyHtml==`string`?t.data.bodyHtml:null,c=o!==null||s!==null,[l,u]=(0,J.useState)(null);return(0,J.useEffect)(()=>{if(c)return;let e=new AbortController;return n(t.id,{format:`email`,version:i,signal:e.signal}).then(async({blob:t})=>{let n=JSON.parse(await t.text());if(typeof n.body!=`string`||n.bodyHtml!=null&&typeof n.bodyHtml!=`string`)throw Error(`Invalid email content response`);e.signal.aborted||u({key:a,body:n.body,bodyHtml:n.bodyHtml||null,error:null})}).catch(t=>{e.signal.aborted||u({key:a,body:``,bodyHtml:null,error:t instanceof Error?t.message:String(t)})}),()=>e.abort()},[a,c,n,t.id,i]),c?{body:o||``,bodyHtml:s,loading:!1,error:null}:l?.key===a?{...l,loading:!1}:{body:``,bodyHtml:null,loading:!0,error:null}}function Xs(e){return e?typeof e==`string`?e:e.name&&e.address?`${e.name} <${e.address}>`:e.address||e.name||``:``}function Zs(e){return e?(Array.isArray(e)?e:[e]).map(e=>Xs(e)).filter(Boolean).join(`, `):``}function Qs(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 $s(e,t,n){let r=0;lr.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=lr.sanitize(e,{FORBID_TAGS:[`script`,`iframe`,`object`,`embed`,`form`,`base`,`link`,`meta`],FORBID_ATTR:[`srcset`]}),i=`<!doctype html><html><head>
|
|
5
|
-
<meta charset="utf-8">
|
|
6
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
7
|
-
<meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; img-src data:${n?` https:`:``}; style-src 'unsafe-inline'`}">
|
|
8
|
-
<style>html{overflow:auto}body{margin:12px;font:14px/1.5 system-ui,sans-serif;color:#1a1a1a;background:#fff}@media(max-width:480px){body{margin:8px}}</style>
|
|
9
|
-
</head><body>${t}</body></html>`;return{url:URL.createObjectURL(new Blob([i],{type:`text/html;charset=utf-8`})),remoteCount:r}}finally{lr.removeHook(`afterSanitizeAttributes`)}}function ec(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 tc(e){return(0,X.jsx)(nc,{...e},`${e.workspaceId}:${e.document.id}`)}function nc({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=Xn(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],{body:s,bodyHtml:c,loading:u,error:d}=Ys(e,t),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(!1),[g,_]=(0,J.useState)(!1),[v,y]=(0,J.useState)(0),[b,x]=(0,J.useState)(null);(0,J.useEffect)(()=>{if(!c||m)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 ec(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}=$s(c,r,g);n.push(i),p(i),y(a)}).catch(t=>{e||x(String(t instanceof Error?t.message:t))}),()=>{e=!0,n.forEach(e=>URL.revokeObjectURL(e)),p(null)}},[e,t.id,c,m,g]);let S=typeof a.date==`string`?new Date(a.date).toLocaleString():null,C=o.filter(e=>!e.isInline||!e.contentId),w=async e=>{if(e.url)try{await i(t.id,e.filename||`attachment`,{url:e.url})}catch(e){x(e instanceof Error?e.message:String(e))}};return(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 min-w-0 flex-col gap-3 ${n}`,children:[(0,X.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-2 text-sm sm:p-3`,children:(0,X.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2 sm:gap-3`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 basis-64 space-y-1`,children:[(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,X.jsxs)(`details`,{className:`sm:hidden`,children:[(0,X.jsxs)(`summary`,{className:`cursor-pointer text-xs`,children:[(0,X.jsx)(`span`,{className:`inline-block max-w-[85%] truncate align-bottom`,children:typeof a.from==`object`&&a.from?a.from.name||a.from.address:String(a.from||`Unknown sender`)}),(0,X.jsx)(`span`,{className:`ml-2 text-muted-foreground`,children:`Details`})]}),(0,X.jsxs)(`div`,{className:`mt-2 space-y-1 break-words text-xs`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Xs(a.from)]}),Zs(a.to)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Zs(a.to)]}),Zs(a.cc)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Zs(a.cc)]}),S&&(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:S})]})]}),(0,X.jsxs)(`div`,{className:`hidden space-y-1 break-words sm:block`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Xs(a.from)]}),Zs(a.to)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Zs(a.to)]}),Zs(a.cc)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Zs(a.cc)]}),S&&(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:S})]})]}),c&&(0,X.jsxs)(`div`,{className:`flex max-w-full flex-wrap gap-2`,children:[(0,X.jsxs)(q,{size:`sm`,variant:`outline`,onClick:()=>h(!m),children:[m?(0,X.jsx)(se,{className:`mr-1.5 h-3.5 w-3.5`}):(0,X.jsx)(ze,{className:`mr-1.5 h-3.5 w-3.5`}),m?`HTML`:`Plain text`]}),!m&&v>0&&(0,X.jsxs)(q,{size:`sm`,variant:g?`secondary`:`outline`,onClick:()=>_(!g),title:`Remote images can reveal your IP/read status to the sender`,children:[g?(0,X.jsx)(I,{className:`mr-1.5 h-3.5 w-3.5`}):(0,X.jsx)(l,{className:`mr-1.5 h-3.5 w-3.5`}),g?`Hide remote images`:`Show remote images (${v})`]})]})]})}),(b||d)&&(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:b||d}),u?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading message…`}):d?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:String(a.bodyPreview||`Message content could not be loaded.`)}):!m&&c?f?(0,X.jsx)(`iframe`,{src:f,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,X.jsx)(`pre`,{className:`min-h-[12rem] flex-1 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-sm`,children:s||`(empty body)`}),C.length>0&&(0,X.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,X.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,C.length,`)`]}),C.map((e,t)=>(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,X.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,X.jsx)(ze,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,X.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:Qs(e.size)})]}),e.url&&(0,X.jsxs)(`button`,{onClick:()=>w(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,X.jsx)(Ne,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}function rc({attachment:e,workspaceId:t,document:n}){let{download:r}=Xn(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}=Un(t,n.id,{url:e.url,typeHint:i,enabled:!o&&!!e.url}),{src:u,error:d,loading:f}=Vn(t,n.id,{url:e.url,enabled:o&&!!e.url}),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(``),_=o?d:c;return(0,X.jsxs)(`div`,{className:`space-y-2 rounded border p-2`,children:[_&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:_}),(o?f:l)&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading attachment…`}),!o&&s&&i.startsWith(`image/`)&&(0,X.jsx)(`img`,{src:s,alt:a,className:`max-h-96 max-w-full rounded object-contain`}),o&&u&&(i.startsWith(`video/`)?(0,X.jsx)(`video`,{controls:!0,playsInline:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`max-h-96 w-full rounded`},u):(0,X.jsx)(`audio`,{controls:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`w-full`},u)),p&&(0,X.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:`This media could not be played in your browser. Download it to play in another app.`}),h&&(0,X.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:h}),e.url&&(0,X.jsxs)(`button`,{className:`text-sm text-primary underline`,onClick:()=>{r(n.id,a,{url:e.url}).catch(()=>g(`Attachment could not be downloaded.`))},children:[`Download `,a]})]})}function ic(e){let t=e.document.data,n=t.sender,r=t.channel,i=Array.isArray(t.attachments)?t.attachments:[],a=t.timestamp?new Date(String(t.timestamp)):null;return(0,X.jsxs)(`article`,{className:`space-y-4 p-3 ${e.className||``}`,children:[(0,X.jsxs)(`header`,{className:`space-y-1 border-b pb-3`,children:[(0,X.jsx)(`p`,{className:`font-medium`,children:n?.name||n?.displayName||n?.username||n?.id||`Unknown sender`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:[r?.name||r?.id,String(t.platform||``),a&&!Number.isNaN(a.getTime())?a.toLocaleString():``].filter(Boolean).join(` · `)})]}),(0,X.jsx)(`p`,{className:`whitespace-pre-wrap break-words text-sm`,children:String(t.text||`(No text)`)}),!!t.mediaError&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:String(t.mediaError)}),i.map((t,n)=>(0,X.jsx)(rc,{...e,attachment:t},t.url||n))]})}var ac={email:qe,phone:F,sms:z,chat:z,slack:z,matrix:z,web:H,url:H},oc={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},sc=e=>Array.isArray(e)?e:[];function cc(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 lc({title:e,count:t,children:n}){return t===0?null:(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,X.jsx)(`div`,{className:`space-y-1`,children:n})]})}function uc({icon:e,primary:t,children:n,title:r}){return(0,X.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 rounded-md border bg-card px-2.5 py-1.5 text-sm`,title:r,children:[(0,X.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,X.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,X.jsx)(Ke,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function dc({document:e,className:t}){let n=e.data??{},r=sc(n.identifiers),i=sc(n.channels),a=sc(n.organizations),o=sc(n.links),s=sc(n.tags),c=String(n.displayName||``).trim(),l=Rt(e.schema,Nt),u=String(n.primaryEmail||``).trim(),d=n.name&&typeof n.name==`object`?n.name:{},f=[d.prefix,d.given,d.middle,d.family,d.suffix].map(e=>String(e||``).trim()).filter(Boolean).join(` `),p=i.some(e=>e.kind===`email`&&e.value===u);return(0,X.jsxs)(`div`,{className:W(`space-y-4`,t),children:[(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:oc[l]||l}),f&&f!==c&&(0,X.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,X.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,X.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,X.jsx)(lc,{title:`Primary email`,count:1,children:(0,X.jsx)(uc,{icon:qe,primary:!0,children:(0,X.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,X.jsx)(lc,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=cc(n,r),a=ac[n]||z;return(0,X.jsxs)(uc,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,X.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,X.jsx)(lc,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,X.jsxs)(uc,{icon:rt,primary:e.primary,children:[(0,X.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,X.jsx)(lc,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,X.jsxs)(uc,{icon:Ze,children:[e.name,e.role&&(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,X.jsx)(lc,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,X.jsxs)(uc,{icon:Fe,children:[(0,X.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,X.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function fc({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,X.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,X.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function pc(e){let t=e.schema;if(t===`data/schema/note`)return Ss;if(t===`data/schema/drawing`)return hs;if(t===`data/schema/task`)return Js;if(t===`data/schema/message/email`)return tc;if(t===`data/schema/message`)return ic;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return dc;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return $t(t)?Cs:Ts(t)?ws:Ds}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(Tn(n,Bt(e))){case`image`:return hs;case`audio`:return gs;case`video`:return _s;case`pdf`:return vs;case`markdown`:return Ss;case`text`:return xs;default:return fc}}function mc(e){let t=`/workspaces/${encodeURIComponent(e.workspaceName)}`,n=e.path.replace(/^\/+/,``).split(`/`).map(encodeURIComponent).join(`/`);return e.treeName===`context`?`${t}/path/${n}`:`${t}/trees/${encodeURIComponent(e.treeName)}/path/${n}`}var hc=[];function gc(e){if(e.key!==`Escape`||e.isComposing||e.defaultPrevented)return;let t=hc[hc.length-1];t&&(e.preventDefault(),t())}function _c(e,t=!0){let n=(0,J.useRef)(e);(0,J.useEffect)(()=>{n.current=e});let r=t&&!!e;(0,J.useEffect)(()=>{if(!r)return;let e=()=>n.current?.();return hc.push(e),hc.length===1&&window.addEventListener(`keydown`,gc),()=>{let t=hc.indexOf(e);t>=0&&hc.splice(t,1),hc.length===0&&window.removeEventListener(`keydown`,gc)}},[r])}function vc({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,J.useRef)(null),[o,s]=(0,J.useState)({x:e,y:t});return _c(n),(0,J.useLayoutEffect)(()=>{let n=a.current;if(!n)return;let{width:r,height:i}=n.getBoundingClientRect();s({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})},[e,t]),(0,po.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,X.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:W(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r,`bg-popover text-popover-foreground`),children:i})]}),document.body)}var yc=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),bc={Delete:`Del`,Backspace:`⌫`,Enter:`↵`,ArrowUp:`↑`,ArrowDown:`↓`};function xc(e){let t=e.split(`+`),n=t.pop()||``,r=bc[n]||(n.length===1?n.toUpperCase():n);if(yc){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 Sc(e,t){let n=t.split(`+`),r=n.pop()||``;return(yc?e.metaKey:e.ctrlKey)!==n.includes(`Mod`)||e.shiftKey!==n.includes(`Shift`)||e.altKey!==n.includes(`Alt`)||yc&&e.ctrlKey!==n.includes(`Ctrl`)?!1:r.length===1?e.key.toLowerCase()===r.toLowerCase():e.key===r}function Cc(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 wc(e,t){if(e.defaultPrevented||e.nativeEvent.isComposing||Cc(e.target))return!1;let n=t.find(t=>t.shortcut&&!t.disabled&&Sc(e,t.shortcut));return n?(e.preventDefault(),e.stopPropagation(),n.run({shiftKey:e.shiftKey}),!0):!1}function Tc(e){return e.key===`ContextMenu`||e.key===`F10`&&e.shiftKey}function Ec(){return typeof window<`u`&&window.matchMedia(`(max-width: 767px)`).matches}function Dc(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 Oc(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 kc(e,t,n){t(),setTimeout(()=>{e.run({shiftKey:n})},0)}function Ac({anchor:e,items:t,onClose:n,label:r}){let i=(0,J.useRef)(null);return(0,J.useEffect)(()=>{let e=document.activeElement;return i.current?.querySelector(`[role="menuitem"]:not([aria-disabled="true"])`)?.focus(),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[]),(0,X.jsx)(vc,{x:e.x,y:e.y,onClose:n,className:`min-w-[200px] rounded-lg border bg-popover text-popover-foreground py-1 shadow-elevation-3`,children:(0,X.jsx)(`div`,{ref:i,role:`menu`,"aria-label":r,onKeyDown:e=>{let t=Array.from(i.current?.querySelectorAll(`[role="menuitem"]:not([aria-disabled="true"])`)??[]);if(t.length===0)return;let r=t.indexOf(document.activeElement),a=e=>t[(e+t.length)%t.length]?.focus();switch(e.key){case`ArrowDown`:e.preventDefault(),a(r+1);return;case`ArrowUp`:e.preventDefault(),a(r<0?-1:r-1);return;case`Home`:e.preventDefault(),a(0);return;case`End`:e.preventDefault(),a(-1);return;case`Tab`:e.preventDefault(),n();return}if(e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let n=e.key.toLowerCase(),i=[...t.slice(r+1),...t.slice(0,r+1)].find(e=>e.textContent?.trim().toLowerCase().startsWith(n));i&&(e.preventDefault(),i.focus())}},onContextMenu:e=>e.preventDefault(),children:Oc(t).map((e,t)=>(0,X.jsxs)(J.Fragment,{children:[t>0&&(0,X.jsx)(`div`,{role:`separator`,className:`my-1 h-px bg-border`}),e[0].groupLabel&&(0,X.jsx)(`div`,{className:`px-3 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let t=e.icon;return(0,X.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,"aria-disabled":e.disabled||void 0,title:e.hint,onClick:t=>{e.disabled||kc(e,n,t.shiftKey)},className:W(`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm outline-none`,e.disabled?`cursor-default opacity-50`:e.destructive?`text-destructive hover:bg-destructive hover:text-destructive-foreground focus:bg-destructive focus:text-destructive-foreground`:`hover:bg-muted focus:bg-muted`),children:[t?(0,X.jsx)(t,{className:`h-3.5 w-3.5 shrink-0`}):(0,X.jsx)(`span`,{className:`w-3.5 shrink-0`}),(0,X.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.shortcut&&(0,X.jsx)(`kbd`,{className:`ml-4 shrink-0 font-sans text-[11px] text-muted-foreground`,children:xc(e.shortcut)})]},e.id)})]},`${e[0].group??``}:${t}`))})})}function jc({items:e,onClose:t,header:n}){_c(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,po.createPortal)((0,X.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-popover text-popover-foreground animate-in slide-in-from-bottom-10 fade-in duration-normal`,onClick:t,onContextMenu:e=>e.preventDefault(),children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,X.jsx)(`div`,{className:`min-w-0 flex-1`,children:n}),(0,X.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,X.jsx)(M,{className:`h-5 w-5`})})]}),(0,X.jsx)(`div`,{className:`min-h-4 flex-1`}),(0,X.jsxs)(`div`,{className:`max-h-[75vh] shrink-0 space-y-2 overflow-y-auto px-4 pt-2`,style:{paddingBottom:`calc(var(--safe-bottom) + 1.25rem)`},onClick:e=>e.stopPropagation(),children:[Oc(e).map((e,n)=>(0,X.jsxs)(`div`,{className:W(`space-y-2`,n>0&&`pt-2`),children:[e[0].groupLabel&&(0,X.jsx)(`div`,{className:`px-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let n=e.icon;return(0,X.jsxs)(`button`,{type:`button`,disabled:e.disabled,onClick:n=>kc(e,t,n.shiftKey),className:W(r,e.destructive&&`border-destructive/30 text-destructive`,e.disabled&&`opacity-50`),children:[n&&(0,X.jsx)(n,{className:W(`h-5 w-5 shrink-0`,!e.destructive&&`text-muted-foreground`)}),e.label]},e.id)})]},`${e[0].group??``}:${n}`)),(0,X.jsx)(`button`,{type:`button`,onClick:t,className:`${r} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function Mc({anchor:e,items:t,onClose:n,label:r,header:i}){return t.length===0?null:Ec()?(0,X.jsx)(jc,{items:t,onClose:n,header:i??(r&&(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:r}))}):(0,X.jsx)(Ac,{anchor:e,items:t,onClose:n,label:r})}var Nc=null;function Pc(){return Nc||=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(()=>(Nc=null,[])),Nc}async function Fc(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 Ic=`ph:folder-fill`,Lc=`ph:squares-four-fill`,Rc=`ph:stack-fill`,zc=[`#ef4444`,`#f97316`,`#f59e0b`,`#eab308`,`#84cc16`,`#22c55e`,`#14b8a6`,`#06b6d4`,`#3b82f6`,`#6366f1`,`#8b5cf6`,`#a855f7`,`#ec4899`,`#f43f5e`,`#64748b`,`#78716c`],Bc={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`}},Vc={"workspace:home":{icon:`ph:house-fill`,color:`#3b82f6`},"workspace:data":{icon:`ph:database-fill`,color:`#14b8a6`}},Hc={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`}},Uc={icon:`ph:hard-drive-fill`,color:`#64748b`};function Wc(e){let t=e.config?.ui??{},n=e.address&&Vc[e.address]||e.driver&&Hc[e.driver]||Uc;return{icon:typeof t.icon==`string`?t.icon:n.icon??Uc.icon,color:typeof t.color==`string`?t.color:n.color??Uc.color}}function Gc(e){let t=e.metadata?.ui??{},n=Bc[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 Kc(e){let t=Bc[(e.split(`/`).filter(Boolean).pop()??``).trim().toLowerCase()];return t?{metadata:qc(void 0,t)}:null}function qc(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 Jc=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,Yc=()=>({h:Jc(0,360),s:Jc(42,98),l:Jc(40,90)}),Xc=(e,t,n)=>{t/=100,n/=100;let r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),a=n-r/2,o=0,s=0,c=0;0<=e&&e<60?(o=r,s=i):60<=e&&e<120?(o=i,s=r):120<=e&&e<180?(s=r,c=i):180<=e&&e<240?(s=i,c=r):240<=e&&e<300?(o=i,c=r):300<=e&&e<360&&(o=r,c=i),o=Math.round((o+a)*255),s=Math.round((s+a)*255),c=Math.round((c+a)*255);let l=e=>e.toString(16).padStart(2,`0`);return`#${l(o)}${l(s)}${l(c)}`},Zc=()=>{let{h:e,s:t,l:n}=Yc();return Xc(e,t,n)},Qc=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)},$c=(e,t=.82)=>{let n=Qc(e);return n===null||n>t},el=e=>e&&!$c(e)?e:void 0,tl=e=>{if(!e)return`text-muted-foreground/70`;let t=Qc(e);return t!==null&&t>.5?`text-black/45`:`text-white/80`},nl=e=>{let t=Qc(e);return t!==null&&(t+.05)/.05>=1.05/(t+.05)?`text-black`:`text-white`},rl=[{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 il(e,t){return{Icon:e,...rl[t-1]}}var al={tab:il(H,7),link:il(H,7),email:il(qe,3),note:il(it,3),task:il(Ye,5),message:il(z,6),identity:il(V,2),contact:il(V,2),device:il(k,10),application:il(me,11),dotfile:il(Pe,4),document:il(ze,9)},ol=[{test:/^image\//,spec:il(l,5)},{test:/^video\//,spec:il(Ge,11)},{test:/^audio\//,spec:il(x,10)},{test:/pdf$/,spec:il(ze,1)},{test:/zip|tar|gzip|7z|rar|compressed/,spec:il(Ve,12)},{test:/json|javascript|typescript|xml|html|css|x-sh|python/,spec:il(Ee,6)},{test:/^text\//,spec:il(ze,12)}],sl=il($e,6),cl=il($e,9);function ll(e){let t=(e.schema||``).split(`/`).pop()||``;if(t===`file`){let t=String(e.metadata?.contentType||``).toLowerCase();return ol.find(({test:e})=>e.test(t))?.spec||sl}return al[t]||cl}var ul={3.5:`h-3.5 w-3.5`,4:`h-4 w-4`,5:`h-5 w-5`,10:`h-10 w-10`};function dl(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 fl({document:e,size:t=4,chip:n=!1,className:r}){let i=ll(e),a=e.schema===`data/schema/tab`?dl(e.data):[],[o,s]=(0,J.useState)(0),c=a[o]??null,l=c?(0,X.jsx)(`img`,{src:c,alt:``,loading:`lazy`,onError:()=>s(e=>e+1),className:W(ul[t],`rounded-xs object-contain`,!n&&`shrink-0`,!n&&r)}):(0,X.jsx)(i.Icon,{className:W(ul[t],i.color,!n&&`shrink-0`,!n&&r)});return n?(0,X.jsx)(`span`,{className:W(`inline-flex shrink-0 items-center justify-center rounded-md`,t>=10?`p-3`:`p-1`,i.chip,r),children:l}):l}function pl({items:e,onNavigate:t,disabled:n,className:r,label:i=`Tree path`}){let a=(0,J.useRef)(null),o=e[e.length-1]?.path;return(0,J.useEffect)(()=>{let e=a.current;e&&(e.scrollLeft=e.scrollWidth)},[o]),(0,X.jsx)(`nav`,{"aria-label":i,className:W(`min-w-0 flex-1`,r),children:(0,X.jsx)(`ol`,{ref:a,className:`flex min-w-0 items-center gap-1 overflow-x-auto py-0.5 text-sm`,children:e.map((r,i)=>{let a=i===e.length-1,o=W(`block max-w-56 truncate rounded px-1.5 py-1`,a?`font-medium text-foreground`:`text-muted-foreground`);return(0,X.jsxs)(`li`,{className:`flex shrink-0 items-center gap-1`,children:[i>0&&(0,X.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/60`,children:`/`}),t&&!a?(0,X.jsx)(`button`,{type:`button`,title:r.path===`/`?`${r.label} (root)`:r.path,disabled:n,onClick:()=>t(r.path),className:W(o,`hover:bg-accent hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50`),children:r.label}):(0,X.jsx)(`span`,{title:r.path===`/`?r.label:r.path,"aria-current":a?`location`:void 0,className:o,children:r.label})]},r.path)})})})}function ml(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 hl={context:(0,X.jsx)(S,{className:`h-3.5 w-3.5`}),directory:(0,X.jsx)(y,{className:`h-3.5 w-3.5`}),backends:(0,X.jsx)(B,{className:`h-3.5 w-3.5`}),relations:(0,X.jsx)(Ue,{className:`h-3.5 w-3.5`})},gl={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function _l(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function vl(e,t){let n=(0,J.useRef)(null),r=(0,J.useRef)(!1),i=()=>{n.current&&=(clearTimeout(n.current),null)},a=e=>t=>{if(r.current){r.current=!1;return}t.detail>1||e()};return t?{guardClick:a,handlers:{onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),t({clientX:n.clientX,clientY:n.clientY,path:e})},onPointerDown:a=>{if(a.pointerType!==`touch`)return;let{clientX:o,clientY:s}=a;i(),n.current=setTimeout(()=>{r.current=!0,t({clientX:o,clientY:s,path:e})},500)},onPointerUp:i,onPointerLeave:i,onPointerMove:i}}:{handlers:{},guardClick:a}}function yl(e,t,n){let r=_l(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>yl(e,r,n))??!1}var bl=200;function xl({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,J.useState)(``);return(0,X.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 text-sm shadow-elevation-1`,children:[(0,X.jsx)(oe,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:n=>{n.key===`Enter`&&r.trim()&&e(r.trim()),n.key===`Escape`&&t()},onBlur:()=>{n||t()},placeholder:`New folder name…`,autoFocus:!0,disabled:n,className:`w-full flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),n&&(0,X.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function Sl({node:e,parentPath:t,query:n,selected:r,onToggle:a,onActivate:o,onRowMenu:s,createParent:c,onCreateConfirm:l,onCreateCancel:u,creating:d}){let f=_l(t,e.name),p=!!e.children?.length,[m,h]=(0,J.useState)(!1),{handlers:g,guardClick:_}=vl(f,s);if(n&&!yl(e,t,n))return null;let v=c===f,y=m||n.length>0||v,b=r.has(f),x=e.type===`canvas`,S=Gc(e);return(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`div`,{className:W(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,b?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:_(()=>a(f)),onDoubleClick:e=>{e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button,input,textarea,select,a,[contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),p?h(e=>!e):o?.(f))},title:f,...g,children:[(0,X.jsx)(`button`,{type:`button`,"aria-label":`${y?`Collapse`:`Expand`} ${e.label||e.name}`,"aria-expanded":p?y:void 0,disabled:!p,className:W(`shrink-0 text-muted-foreground hover:text-foreground`,!p&&`invisible`),onClick:e=>{e.stopPropagation(),e.detail<=1&&h(e=>!e)},children:y?(0,X.jsx)(ue,{className:`w-4 h-4`}):(0,X.jsx)(gt,{className:`w-4 h-4`})}),(0,X.jsx)(i,{icon:S.icon||(x?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:el(S.color),className:W(`shrink-0`,!el(S.color)&&(x?`text-primary`:`text-muted-foreground`))}),(0,X.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),y&&p||v?(0,X.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[v&&l&&u&&(0,X.jsx)(xl,{busy:d,onConfirm:e=>{h(!0),l(f,e)},onCancel:u}),y&&e.children?.map(e=>(0,X.jsx)(Sl,{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 Cl({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,X.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=el(e.color);return(0,X.jsxs)(`div`,{onClick:()=>n(e.name),className:`group relative flex cursor-pointer items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 shadow-elevation-1 transition-all hover:bg-accent/50 hover:shadow`,style:{borderRight:`6px solid ${t||`transparent`}`},children:[(0,X.jsx)(i,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:W(`shrink-0`,!t&&`text-muted-foreground`)}),(0,X.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,X.jsx)(gt,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function wl({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:a,excludeDocumentIds:o}){let[s,c]=(0,J.useState)(`folder`),[l,u]=(0,J.useState)(``),d=l.trim().toLowerCase(),[f,p]=(0,J.useState)(`/`),[m,h]=(0,J.useState)(null),[g,_]=(0,J.useState)(!1),[v,y]=(0,J.useState)([]),[b,x]=(0,J.useState)(!1),[S,C]=(0,J.useState)(``),[w,T]=(0,J.useState)(``),[E,D]=(0,J.useState)(t),O=n?t:E,k=e=>{p(`/`),c(`folder`),C(``),T(``),a?.(`/`),n?n(e):D(e)},[A,j]=(0,J.useState)(O);O!==A&&(j(O),p(`/`),c(`folder`)),(0,J.useEffect)(()=>{let e=setTimeout(()=>T(S.trim()),300);return()=>clearTimeout(e)},[S]),(0,J.useEffect)(()=>{let t=!1;async function n(){_(!0);try{let n=await wn(e,O);t||h(n)}catch{t||h(null)}finally{t||_(!1)}}return n(),()=>{t=!0}},[e,O]),(0,J.useEffect)(()=>{if(s!==`documents`)return;let t=!1,n=O===`directory`?`directory`:kn,r=O===`context`?`context`:`directory`;async function i(){x(!0);try{let i=w?await on(e,f,[],{treeName:n,treeType:r,q:w,limit:bl}):await Lt(e,f,n,{limit:bl});t||y(i.payload||[])}catch{t||y([])}finally{t||x(!1)}}return i(),()=>{t=!0}},[e,O,f,s,w]);let N=e=>{p(e),a?.(e)},P=o?.size?v.filter(e=>!o.has(e.id)):v;return s===`folder`?(0,X.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,X.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,X.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>k(e),className:W(`flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors`,O===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Browse the ${gl[e].toLowerCase()}`,children:[hl[e],(0,X.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,X.jsxs)(`button`,{type:`button`,onClick:()=>c(`documents`),className:`inline-flex items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90`,children:[`Next `,(0,X.jsx)(gt,{className:`h-3.5 w-3.5`})]})]}),(0,X.jsx)(pl,{items:ml(f,e),onNavigate:N,label:`Folder path`}),(0,X.jsxs)(`div`,{className:`relative`,children:[(0,X.jsx)(ht,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,X.jsx)(`input`,{type:`text`,placeholder:`Filter folders…`,value:l,onChange:e=>u(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})]}),(0,X.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:g?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:W(`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:()=>N(`/`),onDoubleClick:()=>{N(`/`),c(`documents`)},title:`/`,children:[(0,X.jsx)(ue,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,X.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:m?.children?.length?m.children.map(e=>(0,X.jsx)(Sl,{node:e,parentPath:`/`,query:d,selected:new Set([f]),onToggle:N,onActivate:e=>{N(e),c(`documents`)}},e.id||e.name)):(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,X.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,X.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsxs)(`button`,{type:`button`,onClick:()=>c(`folder`),className:`inline-flex min-w-0 items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Back to folders`,children:[(0,X.jsx)(gt,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,X.jsx)(`span`,{children:`Folders`})]}),(0,X.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,X.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,X.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground`,children:[`[`,O,`]`]}),(0,X.jsx)(pl,{items:ml(f,e),onNavigate:N,label:`Document folder path`})]}),(0,X.jsxs)(`div`,{className:`relative`,children:[(0,X.jsx)(ht,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,X.jsx)(`input`,{type:`text`,placeholder:`Search documents in this folder…`,value:S,onChange:e=>C(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-7 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),S&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>C(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear document search`,children:(0,X.jsx)(M,{className:`h-3.5 w-3.5`})})]})]}),(0,X.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:b?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):P.length===0?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:w?`No documents match “${w}” here.`:`No documents in this folder.`}):P.map(e=>{let t=At(e),n=r.has(e.id);return(0,X.jsxs)(`div`,{onClick:()=>i(e.id),className:W(`flex min-h-9 items-center gap-2 rounded-md px-3 py-1.5 cursor-pointer transition-all select-none text-sm`,n?`bg-primary/[0.08] hover:bg-primary/[0.12]`:`hover:bg-primary/[0.04]`),children:[(0,X.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,X.jsx)(fl,{document:e,size:3.5}),(0,X.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function Tl({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[y,b]=(0,J.useState)(r?`tree`:`workspace`),[x,S]=(0,J.useState)([]),[C,w]=(0,J.useState)(!r),[T,E]=(0,J.useState)(r??null),D=u&&l.includes(u)?u:l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`,[O,k]=(0,J.useState)(D),A=g?.length?g:[...En],[j,N]=(0,J.useState)(A[0]??`references`),[P,F]=(0,J.useState)(`out`),[I,ee]=(0,J.useState)(new Set),[L,te]=(0,J.useState)(null),[ne,re]=(0,J.useState)(`context`),[R,z]=(0,J.useState)(!1),B=O===`pins`?ne:O;(0,J.useEffect)(()=>{if(!T)return;let e=!1;return xn(T).then(t=>{e||te(t)}).catch(()=>{e||z(!0)}),()=>{e=!0}},[T]);let ie=O===`relations`,[ae,oe]=(0,J.useState)(null),[se,ce]=(0,J.useState)(!1),[V,le]=(0,J.useState)(new Set),[H,de]=(0,J.useState)(``),fe=H.trim().toLowerCase(),{showErrorToast:pe}=Ct(),[me,he]=(0,J.useState)(null),[ge,_e]=(0,J.useState)(null),[ve,ye]=(0,J.useState)(!1);_c(e,!o&&!ve);let xe=vl(`/`,e=>he(e)),Se=e=>!o&&(O===`backends`?p?.canCreate(e)===!0:O!==`pins`&&O!==`relations`),Ce=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!T||ve||!Se(e))){ye(!0);try{let t=`${e===`/`?``:e}/${n}`,r=O===`context`?kn:O;O===`backends`?await p.create(e,n):await hn(T,t,!0,r),rn(T,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:T,treeName:r,cacheInvalidated:!0}}));let i=await wn(T,O);oe(i),le(e=>a?new Set([...e,t]):new Set([t])),de(``),_e(null)}catch(e){pe(e instanceof Error?e.message:`Failed to create folder`)}finally{ye(!1)}}},[we,Te]=(0,J.useState)(r);r!==we&&(Te(r),r||w(!0)),(0,J.useEffect)(()=>{r||jt().then(e=>S(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>S([])).finally(()=>w(!1))},[r,i]),(0,J.useEffect)(()=>{if(!T||O===`relations`||O===`pins`)return;let e=!1,t=0;async function n(n=!1){let r=++t;n||ce(!0);try{let n=await wn(T,O);!e&&r===t&&oe(n)}catch{!e&&r===t&&!n&&oe(null)}finally{!e&&r===t&&ce(!1)}}let r=e=>{let t=e.detail;t?.workspaceName&&t.workspaceName!==T||t?.treeName&&t.treeName!==O||(t?.cacheInvalidated||rn(T,O),n(!0))};return window.addEventListener(`workspace:tree:refresh`,r),n(),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,r)}},[T,O]);let Ee=e=>{e!==T&&(te(null),z(!1)),k(D),E(e),le(new Set),ee(new Set),b(`tree`)},De=e=>{ee(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Oe=e=>{if(!a){le(new Set([e]));return}le(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},ke=ie?I.size>0&&!!m:V.size>0,Ae=async()=>{if(!(!T||o||!ke)){if(ie){await m?.({predicate:j,direction:P,targetIds:Array.from(I)},{workspaceName:h??T});return}await t(Array.from(V),{workspaceName:T,treeName:B===`context`?kn:B,treeType:B===`context`?`context`:`directory`})}},U=n??1;return o&&s?(0,X.jsx)(`div`,{className:W(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:s}):(0,X.jsxs)(`div`,{className:W(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(Me,{className:`h-4 w-4`}),d??(y===`workspace`?`Link to…`:ie?`Relate ${U} document${U===1?``:`s`} to…`:`Link ${U} document${U===1?``:`s`} to…`)]}),(0,X.jsx)(`button`,{type:`button`,onClick:e,disabled:o||ve,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,X.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-normal`,style:{transform:y===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,X.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,X.jsx)(Cl,{workspaces:x,loading:C,onPick:Ee})}),(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,X.jsx)(`button`,{type:`button`,disabled:ve,onClick:()=>b(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,X.jsx)(gt,{className:`h-4 w-4 rotate-180`})}),(l.includes(`context`)||l.includes(`directory`))&&(0,X.jsxs)(`button`,{type:`button`,disabled:ve,onClick:()=>{k(`pins`),le(new Set),_e(null)},className:W(`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2 text-xs`,O===`pins`?`border-primary`:`border-transparent text-muted-foreground`),children:[(0,X.jsx)(v,{className:`h-3.5 w-3.5`}),`Pins`]}),l.map(e=>(0,X.jsxs)(`button`,{type:`button`,disabled:ve,onClick:()=>{k(e),le(new Set),_e(null)},className:W(`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:[hl[e],gl[e]]},e))]}),!ie&&(0,X.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,X.jsxs)(`div`,{className:`relative`,children:[(0,X.jsx)(ht,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,X.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:H,onChange:e=>de(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`})]})}),ie&&(0,X.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,X.jsx)(`select`,{id:`relation-predicate`,value:j,onChange:e=>N(e.target.value),className:`min-w-0 flex-1 rounded-md border border-input bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,children:A.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))})]}),(0,X.jsx)(`div`,{className:`flex items-center gap-1`,children:[{dir:`out`,label:`This → picked`,hint:`the ${U===1?`document`:`documents`} you started from ${j} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${j} the ${U===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,X.jsx)(`button`,{type:`button`,title:n,onClick:()=>F(e),className:W(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,P===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!ie&&a&&(0,X.jsxs)(`div`,{className:`flex h-10 shrink-0 items-center gap-1.5 overflow-x-auto border-b bg-primary/[0.04] px-3`,children:[!V.size&&(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Selected folders appear here`}),Array.from(V).map(e=>(0,X.jsxs)(`span`,{className:`inline-flex max-w-full shrink-0 items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground`,children:[(0,X.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>Oe(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,X.jsx)(M,{className:`h-3 w-3`})})]},e))]}),ie&&(h??T)&&(0,X.jsx)(wl,{workspaceName:h??T,treeTab:`context`,selectedDocIds:I,onToggleDoc:De,excludeDocumentIds:_}),O===`pins`&&(0,X.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!L&&!R&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),R&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!R&&L?.length===0&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),L?.filter(e=>e.resolvable!==!1&&l.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(fe)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,X.jsxs)(`button`,{type:`button`,"aria-pressed":ne===t&&V.has(e.path),className:W(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,ne===t&&V.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{ne===t?Oe(e.path):(re(t),le(new Set([e.path])))},children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(v,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,X.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,X.jsx)(`div`,{className:W(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(ie||O===`pins`)&&`hidden`),children:se?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:W(`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`,V.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:xe.guardClick(()=>Oe(`/`)),title:`/`,...Se(`/`)?xe.handlers:{},children:[(0,X.jsx)(ue,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,X.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[ge===`/`&&(0,X.jsx)(xl,{busy:ve,onConfirm:e=>Ce(`/`,e),onCancel:()=>_e(null)}),ae?.children?.length?ae.children.map(e=>(0,X.jsx)(Sl,{node:e,parentPath:`/`,query:fe,selected:V,onToggle:Oe,onRowMenu:e=>{Se(e.path)&&he(e)},createParent:ge,onCreateConfirm:Ce,onCreateCancel:()=>_e(null),creating:ve},e.id||e.name)):ge===`/`?null:(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),y===`tree`&&(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:ie?`${I.size} document${I.size===1?``:`s`} selected`:`${V.size} path${V.size===1?``:`s`} selected`}),(0,X.jsx)(q,{size:`sm`,onClick:Ae,disabled:!ke||o||ve,children:o?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(_o,{className:`mr-1.5 h-3.5 w-3.5`}),ie?`Relating…`:`Linking…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Me,{className:`mr-1 h-3.5 w-3.5`}),ie?`Relate`:f??`Link`]})})]}),me&&(0,X.jsx)(Ac,{anchor:{x:me.clientX,y:me.clientY},onClose:()=>he(null),items:[{id:`new-folder`,label:`New folder in ${me.path}`,icon:be,run:()=>_e(me.path)}]})]})}var El=`workspace:relations:refresh`;function Dl(){window.dispatchEvent(new CustomEvent(El))}function Ol({title:e,icon:t,onClose:n,onSave:r,navigateAfterSave:i=!1,canSave:a=!1,saving:o=!1,saveProgress:s,successMessage:c=`Saved`,lockedWorkspaceName:l,fillParent:u=!1,fullWidthContent:d=!1,relationSubjectId:f,frame:p,children:m,maximized:h,onMaximizedChange:g}){let _=Li(),[v,y]=(0,J.useState)(`portrait`),[b,x]=(0,J.useState)(!1),S=h??b,C=e=>{x(e),g?.(e)},[w,T]=(0,J.useState)(!1),[E,D]=(0,J.useState)(!1),[O,k]=(0,J.useState)(!1),A=o||O;_c(()=>T(!1),w&&!A),_c(()=>C(!1),S&&!w);let j=(0,J.useRef)(null),N=Yo(),{showSuccessToast:P,showErrorToast:F}=Ct(),I=N&&!u&&!S,[ee,L]=(0,J.useState)(!1),te=!u&&!S&&!p&&!ee;(0,J.useEffect)(()=>{w&&j.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[w]);let ne=async(e,t)=>{if(!(!r||A)){k(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>Pt(t.workspaceName,e,a,t.treeName,t.treeType))),P(c),n?.(),i&&_(mc({...t,path:e[0]}),{replace:!0})}catch(e){F(e instanceof Error?e.message:`Failed to save`)}finally{k(!1)}}},re=async e=>{if(!(!f||!l||e.targetIds.length===0)){D(!0);try{await Mn(l,f,e.predicate,e.targetIds,e.direction),P(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Dl(),T(!1)}catch(e){F(e instanceof Error?e.message:`Failed to create relations`)}finally{D(!1)}}},R=S?w?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:I?void 0:v===`portrait`?{aspectRatio:`0.707 / 1`,height:`calc(var(--viewport-h) * 0.85)`,width:`auto`,maxWidth:`min(90vw, 100%)`,flexShrink:0}:{aspectRatio:`1 / 0.707`,width:`min(90vw, 900px)`,maxWidth:`100%`,height:`auto`,maxHeight:`calc(var(--viewport-h) * 0.85)`,flexShrink:0},z=!!(f&&l),B=r&&w&&(0,X.jsx)(Tl,{onClose:()=>T(!1),onConfirm:ne,fixedWorkspaceName:l,saving:A||E,savingContent:s,tabs:z?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:z?re:void 0,relationWorkspaceName:l,relationExcludeIds:z?new Set([f]):void 0,sizeClassName:p?`h-full max-h-full w-full min-w-0 rounded-none border-0 shadow-none`:u?`h-full max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`:void 0}),ie=(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>y(e=>e===`portrait`?`landscape`:`portrait`),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground max-md:hidden touch-target`,"aria-label":`Toggle orientation`,title:`Toggle orientation`,children:(0,X.jsx)(ut,{className:`h-4 w-4`})}),r&&(typeof m==`function`?(0,X.jsx)(`button`,{type:`button`,onClick:()=>T(!0),disabled:!a||A,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":A?`Saving…`:`Add relations / Link to…`,title:`Add relations / Link to…`,children:(0,X.jsx)(Me,{className:`h-4 w-4`})}):(0,X.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>T(!0),disabled:!a||A,children:A?`Saving…`:`Save / Link to…`})),(0,X.jsx)(`button`,{type:`button`,onClick:()=>p&&!S?p.onToggleExpanded():C(!S),className:W(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`,!S&&!p&&`max-md:hidden`),"aria-label":p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,title:p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,children:S||p?.expanded?(0,X.jsx)(ve,{className:`h-4 w-4`}):(0,X.jsx)(Qe,{className:`h-4 w-4`})}),n&&(0,X.jsx)(`button`,{type:`button`,onClick:n,disabled:A,className:W(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`),"aria-label":`Close`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),ae=(0,X.jsxs)(`div`,{style:{...p&&!S?{width:`100%`,height:`100%`,minWidth:0}:R,"--document-reading-width":S&&!d?`48rem`:`100%`},onAnimationEnd:e=>{te&&e.target===e.currentTarget&&L(!0)},className:W(`flex flex-col overflow-hidden`,p&&!S?`strip-document-card`:`rounded-(--card-radius) border bg-card shadow-elevation-4 transition-[width,height]`,u&&!S&&!p&&`w-full`,I&&`fixed inset-2 z-40 shadow-elevation-5`,te&&`animate-card-in`),children:[typeof m!=`function`&&(0,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,X.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,X.jsx)(`span`,{className:`truncate`,children:e})]}),ie]}),(0,X.jsx)(as.Provider,{value:()=>C(!S),children:(0,X.jsx)(`div`,{className:W(`min-h-0 flex-1 overflow-y-auto`,S&&!d&&typeof m!=`function`&&`mx-auto w-full max-w-3xl`),children:p&&B?B:typeof m==`function`?m(ie):m})})]});return S?(0,po.createPortal)((0,X.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[ae,B&&(0,X.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:B})]}),document.body):(0,X.jsxs)(X.Fragment,{children:[ae,!p&&B&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!A&&T(!1),"aria-hidden":!0}),(0,X.jsx)(`div`,{ref:j,className:`relative shrink-0 md:z-panel md:ml-2 md:pr-2 max-md:fixed max-md:bottom-2 max-md:left-2 max-md:right-2 max-md:top-2 max-md:z-card-overlay max-md:animate-fade-in`,children:B})]})]})}function kl({onSearch:e,onDraftChange:t,inputRef:n,label:r=`Search documents`,clearOnSubmit:i=!0,showSubmitButton:a=!0}){return(0,X.jsxs)(`form`,{className:`canvas-search-input`,role:`search`,onSubmit:n=>{n.preventDefault();let r=n.currentTarget.elements.namedItem(`query`),a=r.value.trim();a&&(e(a),i&&(r.value=``,t?.(``)))},children:[(0,X.jsx)(`input`,{ref:n,name:`query`,type:`search`,"aria-label":r,placeholder:r,autoComplete:`off`,enterKeyHint:`search`,onChange:e=>t?.(e.target.value),onKeyDown:e=>{e.key===`Enter`&&e.nativeEvent.isComposing&&e.preventDefault()}}),a&&(0,X.jsx)(`button`,{type:`submit`,className:`canvas-nav-button`,"aria-label":`Run search`,title:`Run search`,children:(0,X.jsx)(ht,{size:17})})]})}function Al({queries:e,onRemoveQuery:t,scope:n=`path`,onScopeChange:r}){return(0,X.jsxs)(`div`,{className:`canvas-search-options`,children:[r&&(0,X.jsxs)(`div`,{className:`canvas-search-scopes`,"aria-label":`Search scope`,children:[(0,X.jsx)(`span`,{children:`Search in`}),(0,X.jsx)(`button`,{type:`button`,"aria-pressed":n===`path`,onClick:()=>r(`path`),children:`This path`}),(0,X.jsx)(`button`,{type:`button`,"aria-pressed":n===`workspace`,onClick:()=>r(`workspace`),children:`Workspace`})]}),e.length>0&&(0,X.jsxs)(`div`,{className:`canvas-search-queries`,"aria-label":`Active searches`,children:[e.map((e,n)=>(0,X.jsxs)(`span`,{className:`canvas-search-query`,children:[(0,X.jsx)(ht,{size:12,"aria-hidden":`true`}),(0,X.jsx)(`span`,{title:e,children:e}),t&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>t(n),"aria-label":`Remove search: ${e}`,children:(0,X.jsx)(M,{size:14})})]},`${e}-${n}`)),t&&e.length>1&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>t(-1),className:`canvas-search-clear`,children:`Clear all`})]})]})}function jl({children:e,accentColor:t}){return(0,X.jsxs)(`div`,{className:`canvas-navigation-tabs`,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,className:`canvas-tab-divider`,style:t?{backgroundColor:t}:void 0}),e]})}function Ml({workspace:e,workspaceIcon:t,tree:n,path:r,document:a,section:o,onBack:s,onBrowseWorkspaces:c,onBrowseTree:l,onNavigatePath:u,onDocument:d,onSection:f,onFilter:p,filtersActive:m,filtersOpen:h,onAdd:g,search:_,onDraftChange:v,tabs:y,accentColor:b,actions:x}){let[S,C]=(0,J.useState)(!1),[w,T]=(0,J.useState)(!1),E=(0,J.useRef)(null),D=(0,J.useRef)(null),O=(0,J.useRef)(null),k=(0,J.useRef)(!1),A=JSON.stringify([e,n,r,a]),[j,N]=(0,J.useState)(A);j!==A&&(N(A),C(!1)),(0,J.useEffect)(()=>{S?D.current?.focus():(E.current&&(E.current.scrollLeft=E.current.scrollWidth,T(E.current.scrollLeft>1)),k.current&&=(O.current?.focus(),!1))},[S,A,o]);let P=()=>{k.current=!0,C(!1),v?.(``)},F=S?P:s??l,I=ml(r,e).slice(1),ee=(e,t,n,r,i=!1)=>n?(0,X.jsx)(`button`,{type:`button`,className:t,onClick:n,title:r,"aria-current":i?`location`:void 0,children:e}):(0,X.jsx)(`span`,{className:`canvas-address-label ${t}`,title:r,"aria-current":i?`location`:void 0,children:e});return(0,X.jsxs)(`header`,{className:`canvas-navigation${y?` has-tabs`:``}`,style:b?{borderTopColor:b}:void 0,children:[y&&(0,X.jsx)(jl,{accentColor:b,children:y}),(0,X.jsxs)(`div`,{className:`canvas-address-row`,children:[(0,X.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,"aria-label":S?`Back to address`:`Back to previous view`,title:S?`Back to address`:`Back to previous view`,disabled:!S&&!s&&!l,onClick:F,children:(0,X.jsx)(at,{size:19})}),(0,X.jsxs)(`div`,{className:`canvas-address-field`,onDoubleClick:e=>{_&&!e.target.closest(`button`)&&C(!0)},onKeyDown:e=>{e.key===`Escape`&&S&&(e.preventDefault(),e.stopPropagation(),P())},children:[S&&_?(0,X.jsx)(kl,{inputRef:D,onSearch:_.onSearch,onDraftChange:v,clearOnSubmit:!_.localOnly,showSubmitButton:!1,label:_.queries.length?`Refine search…`:`Search documents…`}):(0,X.jsxs)(X.Fragment,{children:[ee((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(i,{icon:t||`ph:stack-fill`,className:`h-4 w-4 shrink-0`,"aria-hidden":`true`}),(0,X.jsx)(`span`,{className:`truncate`,children:e})]}),`canvas-address-workspace`,c,`Browse workspaces`),(0,X.jsxs)(`div`,{ref:E,className:`canvas-address-crumbs${w?` is-scrolled`:``}`,onScroll:e=>T(e.currentTarget.scrollLeft>1),role:`navigation`,"aria-label":`Canvas address`,tabIndex:0,onKeyDown:e=>{e.key===`Enter`&&e.target===e.currentTarget&&_&&C(!0)},children:[n&&ee(`[${n}]`,`canvas-address-tree`,l,`Browse tree: ${n}`),ee(`:/`,`canvas-address-root`,u?()=>u(`/`):void 0,`Go to tree root`),I.map((e,t)=>(0,X.jsxs)(`span`,{className:`canvas-address-segment`,children:[t>0&&(0,X.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),ee(e.label,``,u?()=>u(e.path):void 0,e.path,!a&&t===I.length-1)]},e.path)),a&&(0,X.jsxs)(`span`,{className:`canvas-address-segment`,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,children:I.length?`/`:``}),ee(a,``,d,a)]}),o&&ee(`#${o}`,`canvas-address-section`,f,o,!0)]})]}),_&&(0,X.jsxs)(`button`,{ref:O,type:`button`,className:`canvas-nav-button canvas-address-search`,onClick:()=>{S?D.current?.form?.requestSubmit():C(!0)},"aria-label":S?`Run search`:`Search this canvas`,"aria-expanded":S,title:S?`Run search`:`Search this canvas`,children:[(0,X.jsx)(ht,{size:17}),_.queries.length>0&&(0,X.jsx)(`span`,{className:`canvas-nav-dot`})]})]}),p&&(0,X.jsxs)(`button`,{type:`button`,className:`canvas-nav-button canvas-filter-button`,onClick:p,"aria-label":m?`Filters active`:`Filters`,"aria-expanded":!!h,"data-active":!!m,title:m?`Filters active`:`Filters`,children:[(0,X.jsx)(De,{size:19}),m&&(0,X.jsx)(`span`,{className:`canvas-nav-dot`})]}),g&&(0,X.jsx)(`button`,{type:`button`,className:`canvas-nav-button canvas-add-button`,onClick:g,"aria-label":`Add here`,title:`Add here`,children:(0,X.jsx)(L,{size:21})}),x]}),S&&_&&(0,X.jsxs)(`div`,{className:`canvas-search-dropdown`,children:[(0,X.jsxs)(`div`,{className:`canvas-search-heading`,children:[(0,X.jsx)(`span`,{children:_.localOnly?`Filter documents on this page`:v?`Type to filter this page · Enter to search all results`:`Search text or an exact ID, e.g. @id:123`}),(0,X.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,onClick:P,"aria-label":`Close search`,children:(0,X.jsx)(M,{size:16})})]}),(0,X.jsx)(Al,{..._})]}),!S&&_&&_.queries.length>0&&(0,X.jsx)(`div`,{className:`px-3 pb-2`,children:(0,X.jsx)(Al,{queries:_.queries,onRemoveQuery:_.onRemoveQuery})})]})}function Nl({tabs:e,active:t,onChange:n,className:r=``,iconOnly:i=!1}){return(0,X.jsx)(`div`,{className:`flex gap-1 border-b overflow-x-auto ${r}`,children:e.map(e=>{let r=e.icon;return(0,X.jsxs)(`button`,{onClick:()=>n(e.id),title:e.label,className:`${i&&r?`px-3`:`px-4`} py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap inline-flex items-center gap-1.5 ${t===e.id?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[r&&(0,X.jsx)(r,{className:`h-3.5 w-3.5`}),(!i||!r)&&e.label]},e.id)})})}function Pl({workspaceId:e,document:t,className:n}){let r=pc(t);return r?(0,X.jsx)(r,{workspaceId:e,document:t,className:n}):(0,X.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var Fl=e=>`${vt.workspaces}/${encodeURIComponent(e)}/messages`,Il=e=>K.get(`${Fl(e)}/accounts`),Ll=(e,t)=>K.get(`${Fl(e)}/reply-target/${t}`),Rl=(e,t)=>K.post(`${Fl(e)}/send`,t),zl=(e,t)=>K.get(`${Fl(e)}/whatsapp/${encodeURIComponent(t)}/connection`),Bl=(e,t)=>K.get(`${Fl(e)}/outbox/${encodeURIComponent(t)}`),Vl=(e,t)=>K.delete(`${Fl(e)}/whatsapp/${encodeURIComponent(t)}/connection`),Hl=(e,t)=>K.get(`${Fl(e)}/thread/${t}`),Ul=new ur({html:!1});function Wl(e){let t=e=>{let n=[];return e.map(e=>{if(e.children)return t(e.children);switch(e.type){case`strong_open`:case`strong_close`:return`*`;case`em_open`:case`em_close`:return`_`;case`s_open`:case`s_close`:return`~`;case`code_inline`:return`\`${e.content}\``;case`fence`:case`code_block`:return`\`\`\`\n${e.content}\`\`\`\n`;case`text`:return e.content;case`softbreak`:case`hardbreak`:return`
|
|
10
|
-
`;case`paragraph_close`:case`heading_close`:return`
|
|
11
|
-
|
|
12
|
-
`;case`list_item_open`:return`- `;case`link_open`:return n.push(String(e.attrGet(`href`)||``)),``;case`link_close`:return` (${n.pop()||``})`;case`image`:return e.content;default:return``}}).join(``)};return t(Ul.parse(e,{})).trim()}function Gl(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 Kl={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function ql({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${Gl(e)}:smtp-test:${i?.address}`:Gl(e,t,s),l=()=>({requestId:crypto.randomUUID(),text:a?`This is a test email sent from Canvas to check the SMTP configuration.`:``,replyToDocumentId:t,...i,...a?{subject:`Canvas SMTP test`}:{},...s?{forward:!0}:t?{replyAll:n===`replyAll`,quote:!0}:{}}),[u,d]=(0,J.useState)(()=>{try{let e=localStorage.getItem(c);if(e){let r=JSON.parse(e),i=r.draft||r;if(s||!t||r.attempted)return i;let a=n===`replyAll`;return{...i,replyAll:a,...!!i.replyAll===a?{}:{to:void 0,cc:void 0}}}}catch{}return l()}),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)([]),[g,_]=(0,J.useState)(navigator.onLine);(0,J.useEffect)(()=>{let e=()=>_(navigator.onLine);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]);let v=(0,J.useRef)(!1),[y,b]=(0,J.useState)(!1),[x,S]=(0,J.useState)(!1),[C,w]=(0,J.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,J.useState)(``),[D,O]=(0,J.useState)(null);(0,J.useEffect)(()=>{let n=!0;return Promise.all([Il(e),t?Ll(e,t):Promise.resolve(null)]).then(([e,r])=>{n&&(p(r),h(e.filter(e=>e.canSend&&(!r||e.driver===r.driver&&e.address===r.address))),t&&!r&&E(`This message has no supported reply account.`),r&&d(e=>{let t=e.replyAll?r.allRecipients:r.recipients;return{...e,driver:r.driver,address:r.address,...!s&&t&&!C?{to:e.to?.some(e=>e.trim())?e.to:t.to,cc:e.cc?.some(e=>e.trim())?e.cc:t.cc}:{}}}))}).catch(e=>{n&&E(e.message)}),()=>{n=!1}},[e,t,s,C]),(0,J.useEffect)(()=>{try{D?.status===`accepted`?localStorage.removeItem(c):localStorage.setItem(c,JSON.stringify({draft:u,attempted:C}))}catch{}},[c,u,C,D]);let k=m.find(e=>e.driver===u.driver&&e.address===u.address),A=k?.driver===`imap`,j=k?.driver===`whatsapp`,M=!!u.images?.length,N=!!u.text.trim(),P=e=>d(t=>({...t,...e})),F=async()=>{S(!0),E(``),w(!0);let t=A?N?u:{...u,html:void 0}:{...u,text:j?Wl(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await Bl(e,u.requestId).catch(n=>{if(n.statusCode===404)return Rl(e,t);throw n}):await Rl(e,t);if(O(n),n.status===`accepted`){try{localStorage.removeItem(c)}catch{}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}}))}}catch(e){let t=e;E(t.message),!C&&t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==409&&w(!1)}finally{S(!1)}},I=async e=>{if(L||v.current)return;let t=e.filter(e=>[`image/png`,`image/jpeg`,`image/webp`,`image/gif`].includes(e.type));if(t.length){if((u.images?.length||0)+t.length>(j?1:8)){E(j?`One picture per WhatsApp reply.`:`Up to 8 pictures per email.`);return}if((u.images||[]).reduce((e,t)=>e+t.base64.length*3/4,0)+t.reduce((e,t)=>e+t.size,0)>8388608){E(`Pictures must total at most 8 MB.`);return}v.current=!0,b(!0);try{let e=await Promise.all(t.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>n(Error(`Could not read picture`)),r.onload=()=>t({name:e.name,mimeType:e.type,base64:String(r.result).split(`,`)[1]}),r.readAsDataURL(e)})));d(t=>({...t,images:[...t.images||[],...e]})),E(``)}catch(e){E(e instanceof Error?e.message:`Could not read picture`)}finally{v.current=!1,b(!1)}}},ee=u.replyAll?f?.allRecipients:f?.recipients,L=x||C||y,te=a?`Send test email`:t?s?Kl.forward:Kl[u.replyAll?`replyAll`:`reply`]:`New message`,ne=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,X.jsxs)(`section`,{onPasteCapture:e=>{if(!(A||j))return;let t=Array.from(e.clipboardData.files);t.some(e=>e.type.startsWith(`image/`))&&(e.preventDefault(),e.stopPropagation(),I(t))},className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${te} to message`:`New message`,children:[(0,X.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,X.jsx)(`strong`,{className:`text-sm`,children:te}),(0,X.jsx)(q,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,X.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:k?`${k.driver}:${k.address}`:``,disabled:L||!!t||!!i,onChange:e=>{let t=m.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&P({driver:t.driver,address:t.address,to:[],cc:[],bcc:[],subject:void 0,target:void 0,images:void 0,replyAll:!1})},children:[(0,X.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,X.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses the saved SMTP settings. Enter a recipient you control, then click Send. This sends a real email; provider acceptance does not guarantee inbox delivery.`}),!m.length&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Enable sending in the account’s workspace settings. Your draft stays on this device.`}),A?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,X.jsx)(G,{"aria-label":`To`,disabled:L,value:u.to?.join(`, `)||``,onChange:e=>P({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&ee&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,ee.to.join(`, `),ee.cc.length?` · Cc: ${ee.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,X.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,X.jsx)(G,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:L,value:u[e]?.join(`, `)||``,onChange:t=>P({[e]:[t.target.value]})})]},e)),(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,X.jsx)(G,{"aria-label":`Subject`,disabled:L,value:u.subject||``,placeholder:ne,onChange:e=>P({subject:e.target.value||void 0})})]}),t&&!s&&(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,X.jsxs)(`label`,{className:`flex gap-2`,children:[(0,X.jsx)(`input`,{type:`checkbox`,disabled:L,checked:u.replyAll||!1,onChange:e=>{let t=e.target.checked?f?.allRecipients:f?.recipients;P({replyAll:e.target.checked,...t?{to:t.to,cc:t.cc}:{}})}}),`Reply all`]}),(0,X.jsxs)(`label`,{className:`flex gap-2`,children:[(0,X.jsx)(`input`,{type:`checkbox`,disabled:L,checked:u.quote||!1,onChange:e=>P({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,X.jsx)(zn,{format:`html`,editable:!L,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>P({html:e,text:t.slice(0,32e3)})})]}):(0,X.jsxs)(X.Fragment,{children:[!t&&(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,X.jsx)(G,{"aria-label":`Conversation`,disabled:L,value:u.target||``,onChange:e=>P({target:e.target.value})})]}),j?(0,X.jsx)(zn,{format:`markdown`,editable:!L,value:u.text,placeholder:`Write a message…`,onChange:e=>P({text:e.slice(0,32e3)})}):(0,X.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:L,value:u.text,onChange:e=>P({text:e.target.value}),placeholder:`Write a message…`})]}),(A||j)&&(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,X.jsx)(`input`,{"aria-label":`Attach pictures`,className:`block`,type:`file`,accept:`image/png,image/jpeg,image/webp,image/gif`,multiple:!j,disabled:L,onChange:e=>{I(Array.from(e.target.files||[])),e.target.value=``}})]}),u.images?.map((e,t)=>(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,X.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,X.jsx)(q,{size:`sm`,variant:`ghost`,disabled:L,onClick:()=>P({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),j&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,X.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[D.status===`accepted`?`Accepted by the provider.`:D.message,` `,D.warnings?.join(` `),` `,D.rejected?.length?`Not accepted for: ${D.rejected.join(`, `)}`:``]}),D?.status!==`accepted`&&(0,X.jsx)(q,{size:`sm`,disabled:x||y||!C&&(!k||!N&&!M&&!(A&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void F(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,X.jsx)(q,{size:`sm`,variant:`ghost`,disabled:x,onClick:()=>{window.confirm(C?`This message may already have been sent. Discard this draft only after checking the conversation.`:`Discard this draft?`)&&(d({...l(),driver:u.driver,address:u.address}),w(!1),O(null),E(``))},children:`Discard draft`}),C&&D?.status!==`accepted`&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Do not start another send until you have checked the conversation. The same request will not be delivered twice by Canvas.`})]})}function Jl(e){let t=(0,J.useRef)(null),n=(0,J.useRef)(e.onClose);return(0,J.useEffect)(()=>{n.current=e.onClose}),(0,J.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,X.jsx)(`dialog`,{ref:t,"aria-label":e.replyToDocumentId?`${e.mode===`forward`?`Forward`:e.mode===`replyAll`?`Reply all`:`Reply`} message`:`Send test email`,className:`m-auto w-[calc(100%-2rem)] max-w-3xl max-h-[90dvh] overflow-y-auto rounded-(--panel-radius) border bg-card p-0 text-foreground shadow-elevation-4 backdrop:bg-black/40`,onKeyDown:e=>e.stopPropagation(),onCancel:e=>{e.preventDefault(),e.stopPropagation(),n.current()},children:(0,X.jsx)(ql,{...e})})}function Yl({workspaceId:e,documentId:t}){let[n,r]=(0,J.useState)(null),[i,a]=(0,J.useState)(``),[o,s]=(0,J.useState)({}),[c,l]=(0,J.useState)(null),u=(0,J.useCallback)(async()=>{try{let n=await Hl(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,J.useEffect)(()=>{let n=!0;Hl(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(El,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(El,i)}},[e,t,u]),i?(0,X.jsxs)(`div`,{className:`p-3`,children:[(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,X.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,X.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,X.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,X.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,X.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No linked replies have been indexed. Other messages in this conversation are separate from this reply thread.`}),n.truncated&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Showing up to 200 linked messages.`}),n.documents.map(r=>{let i=At(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?[At(t).title]:[]}),p=o[Number(r.id)]??Number(r.id)===t;return(0,X.jsxs)(`details`,{open:p,onToggle:e=>{let t=e.currentTarget.open;s(e=>e[Number(r.id)]===t?e:{...e,[Number(r.id)]:t})},className:`rounded-lg border bg-card`,children:[(0,X.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,X.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,X.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,X.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,X.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,X.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,X.jsx)(Pl,{workspaceId:e,document:r})]},r.id)}),c&&(0,X.jsx)(Jl,{workspaceId:e,replyToDocumentId:Number(c.document.id),mode:c.mode,originalSubject:typeof c.document.data.subject==`string`?c.document.data.subject:void 0,onClose:()=>l(null)},`${c.document.id}:${c.mode}`)]})}function Xl(e,t){return e.slice(0,3).map(e=>{let n=t.get(e.id),r=e.reason===`not-found`?`Source missing from the storage index. Resync the source backend and retry.`:e.reason===`not found`?`Document no longer exists in this workspace. Refresh the list and select it again.`:e.reason;return`${n?`${n} (ID ${e.id})`:`Document ${e.id}`}: ${r}`}).join(`
|
|
13
|
-
`)+(e.length>3?`\n…and ${e.length-3} more failed file${e.length===4?``:`s`}.`:``)}var Zl=`h-full w-[380px] max-w-[90vw] max-md:w-full`;function Ql({onClose:e,children:t}){return(0,po.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-stretch justify-end bg-scrim animate-fade-in`,onClick:e,children:(0,X.jsx)(`div`,{className:`h-full p-2 max-md:w-full max-md:p-1`,onClick:e=>e.stopPropagation(),children:t})}),window.document.body)}var $l=[{mode:`copy`,label:`Copy to`,icon:(0,X.jsx)(f,{className:`h-3.5 w-3.5`})},{mode:`move`,label:`Move to`,icon:(0,X.jsx)(Te,{className:`h-3.5 w-3.5`})},{mode:`delete`,label:`Delete from`,icon:(0,X.jsx)(he,{className:`h-3.5 w-3.5`})}],eu=[{value:`rename`,label:`Rename mine (file-1.ext)`},{value:`overwrite`,label:`Overwrite the existing file`},{value:`error`,label:`Skip the document`}],tu=`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 nu(e){return e.driver===`cacache`?lt:e.config?.remote===!0?g:B}function ru({workspaceId:e,documentCount:t,initialMode:n=`copy`,defaultFilename:r=``,onConfirm:i,onClose:a,saving:o=!1,sizeClassName:s,deleteFrom:c,progress:l,stopping:u=!1,onStop:d}){let{showErrorToast:p}=Ct(),[m,h]=(0,J.useState)(!1);_c(a,!o&&!m);let[g,_]=(0,J.useState)(n),[v,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(null),[C,w]=(0,J.useState)(()=>new Set(n===`delete`&&c?[c.backend]:[])),[T,E]=(0,J.useState)(!1),[O,k]=(0,J.useState)(``),[A,j]=(0,J.useState)(r),[N,P]=(0,J.useState)(`rename`);(0,J.useEffect)(()=>{let t=!1;return Pn(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));w(e=>new Set([...e].filter(e=>n.has(e))))}).catch(e=>{t||S(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let F=g===`move`,I=e=>e.enabled===!1?`disabled`:e.config?.readOnly===!0?`read-only`:e.config?.supported===!1?`unsupported`:null,ee=(0,J.useMemo)(()=>(v||[]).filter(e=>!I(e)).map(e=>e.address),[v,g]),L=e=>{_(e),w(t=>{let n=(v||[]).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)})},te=e=>{w(t=>{if(F)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})},ne=(0,J.useMemo)(()=>(v||[]).filter(e=>C.has(e.address)&&Sn(e)),[v,C]),re=g!==`delete`&&ne.length>0,R=e=>{let t=cn(e,v||[]),n=t&&v?.find(e=>e.address===t.address);return!!n&&!I(n)&&g!==`delete`&&!o},z=async(t,n)=>{let r=cn(t,v||[]);if(!r||!R(t))throw Error(`Choose a writable file backend folder`);await an(e,r.driver,r.address,[[r.key,n].filter(Boolean).join(`/`)])},ie=e=>{h(!1);let t=ln(e[0]||``,v||[]),n=t?(v||[]).find(e=>e.address===t.address):null;if(!t||!n){p(`Pick a folder inside a storage backend`);return}if(I(n)){p(`${n.address} is ${I(n)}`);return}if(!Sn(n)){p(`${n.address} does not keep folders — objects are stored by content`);return}k(t.key),w(e=>F?new Set([t.address]):new Set([...e,t.address]))},ae=async()=>{C.size===0||o||await i([...C],g,{keepDocument:T,folder:re?O.trim():``,filename:re&&t===1?A.trim():``,onConflict:N})},oe=t,se=oe===1?``:`s`,ce=g===`delete`?`Delete ${oe} document${se} from…`:`${g===`move`?`Move`:`Copy`} ${oe} document${se} to…`,V=g===`delete`?`Delete from`:g===`move`?`Move to`:`Copy to`,le=C.size===0?V.split(` `)[0]:`${V} ${C.size} backend${C.size===1?``:`s`}`;return(0,X.jsxs)(`div`,{className:W(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,s||`max-h-viewport-card w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(B,{className:`h-4 w-4`}),ce]}),(0,X.jsx)(`button`,{type:`button`,onClick:a,disabled:o,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),(0,X.jsx)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:$l.map(({mode:e,label:t,icon:n})=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>L(e),disabled:o,className:W(`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`,g===e?e===`delete`?`border-destructive text-destructive`:`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[n,t]},e))}),(0,X.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:[x&&(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-destructive`,children:x}),!v&&!x&&(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading backends…`}),v?.length===0&&(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`No storage backends configured.`}),v?.map(e=>{let t=nu(e),n=I(e),r=C.has(e.address),i=e.config?.remote===!0;return(0,X.jsxs)(`div`,{onClick:()=>!n&&!o&&te(e.address),className:W(`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?g===`delete`?`bg-destructive/[0.08] hover:bg-destructive/[0.12] before:bg-destructive`:`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:n?``:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),title:e.address,children:[(0,X.jsx)(`input`,{type:F?`radio`:`checkbox`,checked:r,disabled:!!n||o,onChange:()=>te(e.address),onClick:e=>e.stopPropagation(),className:`h-4 w-4 shrink-0 accent-primary`,"aria-label":e.address}),(0,X.jsx)(t,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,X.jsx)(`span`,{className:`block truncate font-medium`,children:e.config?.label||e.address}),(0,X.jsxs)(`span`,{className:`block truncate font-mono text-[10px] text-muted-foreground`,children:[e.driver,` · `,e.address]})]}),i&&(0,X.jsx)(`span`,{className:`shrink-0 rounded bg-info-subtle px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,title:`Network mount${e.config?.transport?` (${e.config.transport})`:``} — transfers cross the network`,children:e.config?.transport||`remote`}),n&&(0,X.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:n})]},`${e.driver}/${e.address}`)}),g===`delete`&&(0,X.jsxs)(`label`,{className:`mt-3 flex cursor-pointer items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs`,children:[(0,X.jsx)(`input`,{type:`checkbox`,checked:T,onChange:e=>E(e.target.checked),disabled:o,className:`mt-0.5 h-3.5 w-3.5 accent-destructive`}),(0,X.jsxs)(`span`,{children:[`Keep the index entry when its `,(0,X.jsx)(`strong`,{children:`last`}),` copy is deleted.`,(0,X.jsx)(`span`,{className:`block text-muted-foreground`,children:`Otherwise the document moves to workspace Trash once no locations remain.`})]})]}),re&&(0,X.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-md border px-3 py-2`,children:[(0,X.jsxs)(`p`,{className:`text-xs font-medium`,children:[`Destination on `,ne.map(e=>e.config?.label||e.address).join(`, `)]}),(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`label`,{htmlFor:`backend-transfer-folder`,className:`text-[11px] text-muted-foreground`,children:`Folder (relative to the backend root)`}),(0,X.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,X.jsx)(G,{id:`backend-transfer-folder`,value:O,onChange:e=>k(e.target.value),placeholder:`/`,disabled:o,className:`h-9 font-mono text-xs`}),(0,X.jsx)(q,{type:`button`,variant:`outline`,size:`icon`,className:`h-9 w-9 shrink-0`,onClick:()=>h(!0),disabled:o,"aria-label":`Browse backend folders`,title:`Browse…`,children:(0,X.jsx)(y,{className:`h-4 w-4`})})]})]}),t===1?(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`label`,{htmlFor:`backend-transfer-filename`,className:`text-[11px] text-muted-foreground`,children:`File name`}),(0,X.jsx)(G,{id:`backend-transfer-filename`,value:A,onChange:e=>j(e.target.value),placeholder:r||`keeps the document's own name`,disabled:o,className:`h-9 font-mono text-xs`})]}):(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Each document keeps its own file name and extension.`}),(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`label`,{htmlFor:`backend-transfer-conflict`,className:`text-[11px] text-muted-foreground`,children:`If a different file already has that name`}),(0,X.jsx)(`select`,{id:`backend-transfer-conflict`,className:tu,value:N,onChange:e=>P(e.target.value),disabled:o,children:eu.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),g===`move`&&ee.length>0&&(0,X.jsx)(`p`,{className:`px-1 pt-2 text-[11px] text-muted-foreground`,children:`The source copy is released only once the destination write is durable.`})]}),o&&l&&(0,X.jsxs)(`div`,{role:`status`,className:`flex items-center justify-between gap-2 border-t px-4 py-2 text-xs`,children:[(0,X.jsxs)(`span`,{children:[u?`Stopping after current file`:`Processing`,` · `,l.completed,`/`,l.total]}),d&&(0,X.jsx)(q,{size:`sm`,variant:`outline`,onClick:d,disabled:u,children:`Stop`})]}),(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-t px-4 py-3`,children:[(0,X.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[C.size,` backend`,C.size===1?``:`s`,` selected`]}),(0,X.jsx)(q,{size:`sm`,variant:g===`delete`?`destructive`:`default`,onClick:ae,disabled:C.size===0||o,children:o?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(_o,{className:`mr-1.5 h-3.5 w-3.5`}),`Working…`]}):(0,X.jsxs)(X.Fragment,{children:[g===`delete`?(0,X.jsx)(he,{className:`mr-1 h-3.5 w-3.5`}):g===`move`?(0,X.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}):(0,X.jsx)(f,{className:`mr-1 h-3.5 w-3.5`}),le]})})]}),g===`delete`&&(0,X.jsxs)(`div`,{className:`flex items-start gap-2 border-t bg-destructive/5 px-4 py-2 text-[11px] text-muted-foreground`,children:[(0,X.jsx)(D,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,X.jsx)(`span`,{children:c&&C.has(c.backend)?`Deletes selected files in ${c.backend}/${c.folder}. Copies in other folders are kept.${C.size>1?` Other selected backends are also targeted.`:` Copies on other backends are kept.`}`:`Deletes the file data from the selected backends. Copies on other backends are untouched.`})]}),m&&(0,X.jsx)(Ql,{onClose:()=>h(!1),children:(0,X.jsx)(Tl,{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:R,create:z},onConfirm:ie,onClose:()=>h(!1)})})]})}function iu({tags:e,onChange:t,placeholder:n=`Add tag, press Enter`,suggestions:r=[]}){let[i,a]=(0,J.useState)(``),[o,s]=(0,J.useState)(!1),c=i.trim().toLowerCase(),l=(c?r.filter(t=>t.toLowerCase().includes(c)&&!e.includes(t)):o?r.filter(t=>!e.includes(t)):[]).slice(0,8),u=()=>{let n=i.trim();n&&!e.includes(n)&&t([...e,n]),a(``)};return(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-2 py-1.5 focus-within:ring-1 focus-within:ring-ring`,children:[e.map(n=>(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs`,children:[n,(0,X.jsx)(`button`,{type:`button`,onClick:()=>t(e.filter(e=>e!==n)),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${n}`,children:(0,X.jsx)(M,{className:`h-3 w-3`})})]},n)),(0,X.jsxs)(`div`,{className:`relative flex-1 min-w-[8ch]`,children:[(0,X.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:n=>{n.key===`Enter`||n.key===`,`?(n.preventDefault(),u()):n.key===`Backspace`&&!i&&e.length&&t(e.slice(0,-1))},onFocus:()=>s(!0),onBlur:()=>{setTimeout(u,150),s(!1)},placeholder:e.length?``:n,className:`w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),l.length>0&&(0,X.jsx)(`div`,{className:`absolute left-0 top-full z-50 mt-1 max-h-48 w-56 overflow-auto rounded-md border bg-popover p-1 text-sm shadow-elevation-2`,children:l.map(n=>(0,X.jsx)(`button`,{type:`button`,onMouseDown:r=>{r.preventDefault(),e.includes(n)||t([...e,n]),a(``)},className:`block w-full rounded px-2 py-1 text-left hover:bg-accent`,children:n},n))})]})]})}var au=e(dr(),1),ou=`#8b5cf6`,su=`https://nominatim.openstreetmap.org`,cu=700,lu=e=>Math.round(e*1e6)/1e6;function uu(){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:${ou};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 au.default.divIcon({html:e,className:`canvas-map-pick`,iconSize:[28,28],iconAnchor:[14,28]})}function du({initial:e,onPick:t,onClose:n}){let r=(0,J.useRef)(null),i=(0,J.useRef)(null),a=(0,J.useRef)(null),o=(0,J.useRef)(null);(0,J.useEffect)(()=>()=>o.current?.abort(),[]);let[s,c]=(0,J.useState)(e?{lat:e.lat,lon:e.lon}:null),[l,u]=(0,J.useState)(``),[d,f]=(0,J.useState)([]),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(null),[_,v]=(0,J.useState)(!1),[y,b]=(0,J.useState)(!1),[x,S]=(0,J.useState)(!1);(0,J.useEffect)(()=>{let e=requestAnimationFrame(()=>S(!0));return()=>cancelAnimationFrame(e)},[]),_c(n);let w=(0,J.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let o=au.default.latLng(e,t);a.current?a.current.setLatLng(o):(a.current=au.default.marker(o,{icon:uu(),draggable:!0,autoPan:!0}).addTo(r),a.current.on(`dragend`,()=>{let e=a.current.getLatLng();c({lat:lu(e.lat),lon:lu(e.lng)})})),c({lat:lu(e),lon:lu(t),...n?{label:n}:{}})},[]);(0,J.useEffect)(()=>{let t=r.current;if(!t||i.current)return;let n=au.default.map(t,{center:e?[e.lat,e.lon]:[20,0],zoom:e?13:2,worldCopyJump:!0,zoomControl:!0});au.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,J.useEffect)(()=>{if(!s||s.label)return;let{lat:e,lon:t}=s,n=new AbortController,r=setTimeout(()=>{v(!0),fetch(`${su}/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))},cu);return()=>{clearTimeout(r),n.abort()}},[s]);let T=(0,J.useCallback)(async()=>{let e=l.trim();if(e.length<2)return;o.current?.abort();let t=new AbortController;o.current=t;let n=!1,r=window.setTimeout(()=>{n=!0,t.abort()},12e3);m(!0),f([]),g(null);try{let n=await fetch(`${su}/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]),E=(0,J.useCallback)(()=>{if(!navigator.geolocation){g(`This browser has no geolocation`);return}b(!0),g(null),navigator.geolocation.getCurrentPosition(e=>{b(!1),i.current?.setView([e.coords.latitude,e.coords.longitude],16),w(e.coords.latitude,e.coords.longitude)},()=>{b(!1),g(`Could not read your location. Search or click the map instead`)},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})},[w]),D=(0,J.useCallback)(e=>{let t=i.current,n=Number(e.lat),r=Number(e.lon);if(!t||!Number.isFinite(n)||!Number.isFinite(r))return;let a=e.boundingbox?.map(Number);a&&a.length===4&&a.every(Number.isFinite)?t.fitBounds(au.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,po.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:W(`fixed inset-0 z-[60] bg-scrim transition-opacity duration-normal`,x?`opacity-100`:`opacity-0`),onClick:n}),(0,X.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Pick a location on the map`,className:W(`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`,x?`translate-x-0`:`translate-x-full`),children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(we,{className:`h-4 w-4 text-info`}),`Custom geotag`]}),(0,X.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close map`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),(0,X.jsxs)(`div`,{className:`relative z-10 shrink-0 border-b px-3 py-2`,children:[(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsxs)(`div`,{className:`relative flex-1`,children:[(0,X.jsx)(ht,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,X.jsx)(`input`,{value:l,autoFocus:!0,onChange:e=>{o.current?.abort(),o.current=null,m(!1),f([]),u(e.target.value),g(null)},"aria-label":`Search for a place or address`,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),T())},placeholder:`Search a place, e.g. Slavkovský štít`,spellCheck:!1,className:`h-8 w-full rounded-md border border-input bg-transparent pl-7 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,X.jsx)(`button`,{type:`button`,onClick:E,disabled:y,title:`Use my current location`,"aria-label":`Use my current location`,className:`inline-flex h-8 w-8 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50`,children:y?(0,X.jsx)(ke,{className:`h-3.5 w-3.5 animate-spin`}):(0,X.jsx)(ot,{className:`h-3.5 w-3.5`})}),(0,X.jsxs)(`button`,{type:`button`,onClick:T,disabled:p||l.trim().length<2,className:`inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs text-primary-foreground disabled:opacity-50`,children:[p?(0,X.jsx)(ke,{className:`h-3.5 w-3.5 animate-spin`}):(0,X.jsx)(ht,{className:`h-3.5 w-3.5`}),`Search`]})]}),h&&(0,X.jsx)(`p`,{role:`status`,className:`mt-1 text-xs text-warning`,children:h}),d.length>0&&(0,X.jsx)(`div`,{className:`absolute inset-x-3 top-full z-10 mt-1 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-elevation-4`,children:d.map(e=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>D(e),className:`block w-full border-b border-border/60 px-3 py-2 text-left text-xs last:border-0 hover:bg-muted`,children:e.display_name},`${e.lat},${e.lon},${e.display_name}`))})]}),(0,X.jsxs)(`div`,{className:`relative isolate z-0 min-h-0 flex-1`,children:[(0,X.jsx)(`div`,{ref:r,className:`h-full w-full`}),!s&&(0,X.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-3 z-[1000] flex justify-center`,children:(0,X.jsx)(`span`,{className:`rounded-full bg-background/90 px-3 py-1 text-xs text-muted-foreground shadow-elevation-2`,children:`Click the map to drop a pin, or drag it to fine-tune`})})]}),(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2`,children:[(0,X.jsx)(`div`,{className:`min-w-0 text-xs`,children:s?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5 tabular-nums text-foreground`,children:[(0,X.jsx)(mt,{className:`h-3 w-3 shrink-0 text-muted-foreground`}),s.lat.toFixed(5),`, `,s.lon.toFixed(5),_&&(0,X.jsx)(ke,{className:`h-3 w-3 animate-spin text-muted-foreground`})]}),s.label&&(0,X.jsx)(`div`,{className:`truncate text-muted-foreground`,children:s.label})]}):(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`No point selected`})}),(0,X.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:`Cancel`}),(0,X.jsxs)(`button`,{type:`button`,disabled:!s,onClick:()=>{s&&(t(s),n())},className:`inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-50`,children:[(0,X.jsx)(C,{className:`h-3.5 w-3.5`}),`Use this point`]})]})]})]})]}),document.body)}var fu={exif:`from the photo's EXIF`,device:`from the device at capture`,manual:`placed by hand`};function pu(e){let t=`${e.lat.toFixed(5)}, ${e.lon.toFixed(5)}`,n=e.source?fu[e.source]:null;return[t,e.accuracy==null?null:`±${e.accuracy} m`,n].filter(Boolean).join(` · `)}function mu({value:e,onChange:t,idPrefix:n=`edit-geo`}){let[r,i]=(0,J.useState)(!1);return(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${n}-action`,children:`Location`}),(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,X.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 text-xs`,children:[(0,X.jsx)(we,{className:e?`h-4 w-4 shrink-0 text-info`:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:e?`truncate tabular-nums`:`truncate text-muted-foreground`,children:e?pu(e):`No location on this document`})]}),(0,X.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,X.jsxs)(`button`,{id:`${n}-action`,type:`button`,onClick:()=>i(!0),className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,X.jsx)(Re,{className:`h-3.5 w-3.5`}),e?`Move pin`:`Set on map`]}),e&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>t(null),"aria-label":`Remove location`,title:`Remove location`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,X.jsx)(he,{className:`h-3.5 w-3.5`})})]})]}),r&&(0,X.jsx)(du,{initial:e,onPick:e=>t({lat:e.lat,lon:e.lon,source:`manual`}),onClose:()=>i(!1)})]})}var hu=15,gu=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function _u(e){return String(e).padStart(2,`0`)}function vu(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 yu(e){return`${e.getFullYear()}-${_u(e.getMonth()+1)}-${_u(e.getDate())}`}function bu(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function xu(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/hu)*hu),`${_u(e.getHours())}:${_u(e.getMinutes())}`}function Su(){let e=[];for(let t=0;t<1440;t+=hu)e.push(`${_u(Math.floor(t/60))}:${_u(t%60)}`);return e}var Cu=Su();function wu(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 Tu(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 Eu(e){let t=vu(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 Du({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,J.useState)(!1),u=(0,J.useRef)(null),d=vu(e),f=d?Eu(e):``;return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:W(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,X.jsx)(A,{className:W(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,X.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,X.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,X.jsx)(M,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,X.jsx)(Ou,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Ou({anchorRef:e,value:t,onChange:n,onClose:r}){let i=vu(t),a=i?.date??yu(new Date),o=i?.time??null,[s,c]=(0,J.useState)(()=>{let e=bu(a);return new Date(e.getFullYear(),e.getMonth(),1)}),l=(0,J.useRef)(null),d=(0,J.useRef)(null),[f,p]=(0,J.useState)(null);(0,J.useLayoutEffect)(()=>{let t=l.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));p({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,J.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let m=(0,J.useMemo)(()=>!o||Cu.includes(o)?Cu:[...Cu,o].sort(),[o]);(0,J.useEffect)(()=>{let e=d.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let h=(e,t)=>n(`${e}T${t}`),g=e=>{let t=o??xu();h(yu(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??xu();h(yu(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},y=yu(new Date),b=wu(s);return(0,po.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,X.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:f?.x??-9999,top:f?.y??-9999,visibility:f?`visible`:`hidden`},children:[(0,X.jsxs)(`div`,{className:`w-[236px]`,children:[(0,X.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,X.jsx)(u,{className:`h-4 w-4`})}),(0,X.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,X.jsx)(gt,{className:`h-4 w-4`})})]}),(0,X.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:gu.map(e=>(0,X.jsx)(`span`,{children:e},e))}),(0,X.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:b.map(e=>{let t=yu(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,X.jsx)(`button`,{type:`button`,onClick:()=>g(e),"aria-pressed":r,className:W(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===y&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,X.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,X.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,X.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&h(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,X.jsx)(`div`,{ref:d,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:m.map(e=>{let t=e===o;return(0,X.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>_(e),"aria-pressed":t,className:W(`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:Tu(e)},e)})})]})]})]}),document.body)}var ku={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Au=`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`,ju=`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 Mu({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${u}-title`,children:`Title`}),(0,X.jsx)(G,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${u}-desc`,children:`Description`}),(0,X.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:ju})]}),(0,X.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${u}-due`,children:`Due`}),(0,X.jsx)(Du,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${u}-priority`,children:`Priority`}),(0,X.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Au,children:[(0,X.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,X.jsx)(`option`,{value:e,children:ku[e]},e))]})]})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${u}-status`,children:`Status`}),(0,X.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Au,children:Ps.map(e=>(0,X.jsx)(`option`,{value:e,children:Fs[e]},e))})]})]})}var Nu=`3.0`,Pu=[`person`,`organization`,`service`,`bot`],Fu={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Iu=[`email`,`phone`,`sms`,`chat`,`web`],Lu=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function Ru(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 zu(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Rt(String(e?.schema||``),Nt);return{displayName:String(t.displayName||``),type:Pu.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 Bu(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await Mn(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function Vu(e){let[t,n]=(0,J.useState)(e?.displayName??``),[r,i]=(0,J.useState)(e?.type??`person`),[a,o]=(0,J.useState)(e?.primaryEmail??``),[s,c]=(0,J.useState)(e?.given??``),[l,u]=(0,J.useState)(e?.family??``),[d,f]=(0,J.useState)(e?.channels??[]),[p,m]=(0,J.useState)(e?.identifiers??[]),[h,g]=(0,J.useState)(e?.organizations??[]),[_,v]=(0,J.useState)([]),[y,b]=(0,J.useState)(``),[x,S]=(0,J.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${Nt}/${C.type}`,schemaVersion:Nu,data:Ru(C),...t?{comment:t}:{},metadata:{features:Kn(_)}},r=await or(e,[n]);return await Bu(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 Hu=`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 Uu({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,X.jsx)(mo,{children:e}),(0,X.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,X.jsx)(L,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,X.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,X.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,X.jsx)(he,{className:`h-3.5 w-3.5`})})]},i))})]})}function Wu(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 Gu(e){let[t,n]=(0,J.useState)([]);return(0,J.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Ot(e,`organization`);t||n(r.map(e=>({id:e.id,name:At(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function Ku({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=Gu(t);return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,X.jsx)(G,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${e}-type`,children:`Type`}),(0,X.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:W(Hu,`w-full`),children:Pu.map(e=>(0,X.jsx)(`option`,{value:e,children:Fu[e]},e))})]}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${e}-email`,children:`Primary email`}),(0,X.jsx)(G,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${e}-given`,children:`Given name`}),(0,X.jsx)(G,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`${e}-family`,children:`Family name`}),(0,X.jsx)(G,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,X.jsx)(Uu,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:W(Hu,`w-24`),children:[Iu.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e)),!Iu.includes(e.kind)&&(0,X.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,X.jsx)(G,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>p(Wu(f,f.indexOf(e))),className:W(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,X.jsx)(Ke,{className:W(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,X.jsx)(Uu,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:W(Hu,`w-24`),children:[Lu.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e)),!Lu.includes(e.type)&&(0,X.jsx)(`option`,{value:e.type,children:e.type})]}),(0,X.jsx)(G,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,X.jsx)(Uu,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,X.jsxs)(X.Fragment,{children:[y.length>0?(0,X.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:W(Hu,`min-w-0 flex-1`),children:[(0,X.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,X.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,X.jsx)(G,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,X.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,X.jsx)(Me,{className:`h-3.5 w-3.5`})}),(0,X.jsx)(G,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function qu(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 Ju(e){return qu(e.schema)||Hn(e)}function Yu(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function Xu(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await tn(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 Mn(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await Zt(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function Zu({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Ct(),a=qu(e.schema),o=e.schema===`data/schema/file`,[s,c]=(0,J.useState)(()=>Bt(e)),l=!o||!!s.trim()&&!/[\\/]/.test(s)&&!Array.from(s).some(e=>e.charCodeAt(0)<32)&&s!==`.`&&s!==`..`,u=e.schema===Yt,d=Hn(e),f=qn(e)??`markdown`,p=d&&Ln(e),m=e.schema===zt,h=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:g,titleKey:_}=Yu(e.schema),[v,y]=(0,J.useState)(g?String(e.data?.[g]??``):``),[b,x]=(0,J.useState)(String(e.data?.[_]??``)),[S,C]=(0,J.useState)(String(e.data?.content??``)),[w,T]=(0,J.useState)(String(e.data?.description??``)),[E,D]=(0,J.useState)(e.data?.status??`pending`),[O,k]=(0,J.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[A,j]=(0,J.useState)(e.data?.dueDate?Rs(String(e.data.dueDate)):Bs()),M=Vu(zu(e)),[N,P]=(0,J.useState)(String(e.comment??``)),F=e.metadata?.geo??null,[I,ee]=(0,J.useState)(F),L=e.features??e.metadata?.features,[te,ne]=(0,J.useState)(Bn(L).length?Bn(L):e.data?.tags??[]),re=Rn(e,t,u),{title:R,content:z,comment:B,tags:ie,geo:ae,setTitle:oe,setContent:se,setComment:ce,setTags:V,setGeo:le}=u?re:{title:b,content:S,comment:N,tags:te,geo:I,setTitle:x,setContent:C,setComment:P,setTags:ne,setGeo:ee},H=JSON.stringify(ae??null)!==JSON.stringify(F??null),ue=Un(t,e.id,{mode:`text`,enabled:d&&!p,maxTextLength:Wn,version:e.checksumArray?.[0]??null}),[de,fe]=(0,J.useState)(null),pe=`${e.id}:${e.checksumArray?.[0]??``}`;d&&ue.text!=null&&de!==pe&&(fe(pe),se(ue.text));let[me,he]=(0,J.useState)([]),[ge,_e]=(0,J.useState)(!1),{replicating:ve,mirror:ye}=bn(e);(0,J.useEffect)(()=>{let e=!1;return vn(t).then(t=>{e||he(t)}).catch(()=>{}),()=>{e=!0}},[t]);let be=!g||(()=>{try{return new URL(v.trim()),!0}catch{return!1}})(),xe=!ge&&l&&(d?!p&&ue.text!=null&&!ue.loading:a?h?M.displayName.trim().length>0&&M.emailValid:m?R.trim().length>0:u?re.canSave:be:!0),Se=async()=>{_e(!0);let c=[...(L||[]).filter(e=>!e.startsWith(`tag/`)),...Kn(ie)];try{if(u){await re.save(),n();return}if(d){let i=await Yn(t,e,z,{comment:B.trim(),metadata:{features:c,...o?{filename:s.trim()}:{},...H?{geo:ae}:{}}});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:B.trim(),metadata:{features:c,...o?{filename:s.trim()}:{}}};if(h){let{type:t,...n}=e.data??{};i.schema=`${Nt}/${M.values.type}`,i.data={...n,...Ru(M.values)}}else if(m)i.data={...e.data,...Vs({title:R,description:w,status:E,priority:O,due:A})};else if(a){let t=ie.map(e=>e.trim()).filter(Boolean),n;u?n={...R.trim()?{title:R.trim()}:{},content:z}:(n={...e.data},g&&(n[g]=v.trim()),R.trim()?n[_]=R.trim():delete n[_],n.tags=t),i.data=n}H&&(i.metadata={...i.metadata??{},geo:ae}),await qt(t,i),h&&(await Xu(t,e.id,M.values.organizations),Dl()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{_e(!1)}};return(0,X.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[o&&(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)(mo,{htmlFor:`file-name`,children:`File name`}),(0,X.jsx)(G,{id:`file-name`,value:s,onChange:e=>c(e.target.value)}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Changes the object’s name; storage locations stay the same.`})]}),a&&g&&(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`edit-url`,children:`URL`}),(0,X.jsx)(G,{id:`edit-url`,value:v,onChange:e=>y(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),v.trim()&&!be&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&h&&(0,X.jsx)(Ku,{idPrefix:`edit-identity`,workspaceName:t,...M,emailValid:M.emailValid}),a&&m&&(0,X.jsx)(Mu,{idPrefix:`edit-todo`,title:R,setTitle:oe,description:w,setDescription:T,status:E,setStatus:D,priority:O,setPriority:k,due:A,setDue:j}),a&&!m&&!h&&(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`edit-title`,children:`Title`}),(0,X.jsx)(G,{id:`edit-title`,value:R,onChange:e=>oe(e.target.value),placeholder:u?`Optional; defaults to today's date`:`Optional display title`})]}),(u||d)&&(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{children:`Body`}),p?(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):d&&ue.error?(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:ue.error}):d&&ue.text==null?(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,X.jsx)(Gn,{kind:u?`markdown`:f,value:z,onChange:se,placeholder:u?`Write your note…`:void 0})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{children:`Tags`}),(0,X.jsx)(iu,{tags:ie,onChange:V,suggestions:me})]}),(0,X.jsx)(mu,{value:ae,onChange:le}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(mo,{htmlFor:`edit-comment`,children:`Comment`}),(0,X.jsx)(`textarea`,{id:`edit-comment`,value:B,onChange:e=>ce(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`})]}),u&&(0,X.jsx)(Jn,{...re,onRetry:re.save}),(0,X.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,X.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>n(),disabled:ge,children:u?`Close`:`Cancel`}),(0,X.jsx)(q,{size:`sm`,onClick:Se,disabled:!xe,children:ge?ve?`Replicating to ${ye.label}…`:`Saving…`:`Save changes`})]})]})}var Qu=(0,J.createContext)(null),$u={open:()=>{},close:()=>{}};function ed(){return(0,J.useContext)(Qu)??$u}var td=(0,J.createContext)(null),nd={entry:null,open:()=>{},close:()=>{}};function rd(){return(0,J.useContext)(td)??nd}var id=`main`,ad=(0,J.createContext)(null);function od(){return(0,J.useContext)(ad)}var sd=50;function cd({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=ed(),o=rd(),s=od(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?At(l).title:``,[d,f]=(0,J.useState)(!1),{showErrorToast:p}=Ct(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await Dn(t,c):l;s?o.open(n,t):a(n,t)}catch(e){p(e instanceof Error?e.message:`Failed to open document`)}finally{f(!1)}}},h=!e.meta||e.meta.src===`doc`;return(0,X.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,X.jsx)(Te,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,X.jsx)(at,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,X.jsx)(fl,{document:l,size:3.5}):null,l?(0,X.jsx)(`button`,{type:`button`,onClick:()=>void m(),disabled:d,className:`min-w-0 flex-1 truncate text-left hover:underline`,title:u,children:u}):(0,X.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,X.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!h&&(0,X.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),h&&(0,X.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,X.jsx)(he,{className:`h-3.5 w-3.5`})})]})}function ld({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Ct(),[i,a]=(0,J.useState)(null),[o,s]=(0,J.useState)(null),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(!1),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(0),[g,_]=(0,J.useState)(1),v=(0,J.useRef)(0),y=(0,J.useCallback)(()=>{v.current++},[]),b=(0,J.useCallback)(async()=>{let n=++v.current;try{let r=await tn(t,e.id,{offset:m*sd,limit:sd,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)/sd)-1);if(_(i+1),m>i){h(i);return}a(r),s(null)}catch(e){if(n!==v.current)return;s(e instanceof Error?e.message:String(e))}},[t,e.id,m]),x=`${t}:${e.id}`,[S,C]=(0,J.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,J.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(El,e),()=>{y(),window.removeEventListener(El,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 Zt(t,e.id,i.p,o,a),n(`Relation removed`),Dl()}catch(e){r(e instanceof Error?e.message:`Failed to remove relation`)}finally{p(null)}},T=[{dir:`out`,title:`Points at`,hint:`this document as the subject`,entries:i?.outgoing??[]},{dir:`in`,title:`Pointed at by`,hint:`this document as the object`,entries:i?.incoming??[]}],E=e=>{a(null),h(e)};return(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,X.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,X.jsx)(L,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,X.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,X.jsxs)(`div`,{className:`mb-2`,children:[(0,X.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,X.jsx)(cd,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,X.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,X.jsx)(q,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,X.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,X.jsx)(q,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,X.jsx)(Ql,{onClose:()=>{u||l(!1)},children:(0,X.jsx)(Tl,{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 Mn(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),Dl()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var ud=(0,J.lazy)(()=>s(()=>import(`./SketchEditor-C9_lu3Ot.js`),__vite__mapDeps([9,3,4,10,1,11,12,13,14,15,16,17,18,19,20,21,22,23,24]))),dd=(0,J.lazy)(()=>s(()=>import(`./TextDocumentEditor-DBVWuJaR.js`),__vite__mapDeps([25,3,4,11,10,13,12,14,15,16,26,1,23]))),fd={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},pd={reply:_,replyAll:h,forward:le};function md({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Zn()!=null,{showErrorToast:a,showSuccessToast:o}=Ct(),[s,c]=(0,J.useState)(!1),l=e.data?.url||e.data?.uri,u=e.schema!==`data/schema/file`&&typeof l==`string`&&/^https?:\/\//i.test(l),[f,p]=(0,J.useState)(!1),m=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[h,g]=(0,J.useState)(null),_=e.schema===`data/schema/message/email`,v=!i&&(_||[`slack`,`whatsapp`].includes(String(e.data?.platform))),y=_?[`reply`,`replyAll`,`forward`]:[`reply`],b=e=>g(t=>t===e?null:e),x=!i,[S,C]=(0,J.useState)(n&&!i),w=e.schema===In,[T,E]=(0,J.useState)(!1),D=e.schema===`data/schema/note`||Hn(e),[k,A]=(0,J.useState)(!1),j=`${t}:${e.id}:${n}:${i}`,[M,N]=(0,J.useState)(j);j!==M&&(N(j),C(n&&!i),g(null),p(!1),E(!1),A(!1));let P=t=>{if(!x||!Ju(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 S&&x?(0,X.jsx)(Zu,{document:e,workspaceId:t,onClose:e=>{C(!1),r?.(e)}}):(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[x&&(0,X.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[m&&(0,X.jsx)(q,{size:`sm`,variant:f?`secondary`:`outline`,onClick:()=>p(!f),children:f?`Show message`:`View thread`}),v&&y.map(e=>{let t=pd[e];return(0,X.jsxs)(q,{size:`sm`,variant:h===e?`secondary`:`outline`,onClick:()=>b(e),children:[(0,X.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),fd[e]]},e)}),u&&(0,X.jsxs)(q,{variant:`outline`,size:`sm`,disabled:s,onClick:async()=>{c(!0);try{await kt(t,e.id),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),r?.(),o(`File saved to workspace; the original link is preserved`)}catch(e){a(e instanceof Error?e.message:String(e))}finally{c(!1)}},children:[(0,X.jsx)(Ne,{className:`mr-1 h-3 w-3`}),s?`Downloading…`:`Download to workspace`]}),e.schema===`data/schema/file`&&(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>Wt(t,e.id,Bt(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,X.jsx)(Ne,{className:`mr-1 h-3 w-3`}),` Download`]}),w&&(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>E(!0),children:[(0,X.jsx)(O,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),D&&(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>A(!0),children:[(0,X.jsx)(d,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>C(!0),children:[(0,X.jsx)(ae,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),T&&x&&(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,X.jsx)(ud,{doc:e,workspaceName:t,onSaved:()=>{E(!1),r?.()},onClose:()=>E(!1),onDetails:()=>{E(!1),C(!0)}})}),k&&x&&(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,X.jsx)(dd,{doc:e,workspaceName:t,onSaved:e=>{A(!1),r?.(e)},onClose:()=>A(!1),onDetails:()=>{A(!1),C(!0)}})}),(0,X.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,onMouseDownCapture:e=>{e.button===0&&e.detail>1&&P(e)&&e.preventDefault()},onDoubleClickCapture:e=>{P(e)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.ownerDocument.getSelection()?.removeAllRanges(),C(!0))},children:[f&&!i?(0,X.jsx)(Yl,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,X.jsx)(Pl,{workspaceId:t,document:e}),h&&v&&(0,X.jsx)(Jl,{workspaceId:t,replyToDocumentId:Number(e.id),mode:h,originalSubject:_&&typeof e.data?.subject==`string`?e.data.subject:void 0,onClose:()=>g(null)},`${e.id}:${h}`)]}),e.comment?.trim()&&(0,X.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,X.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,X.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var hd=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,gd=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function _d({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,X.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,X.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,gd(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`,hd(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,X.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function vd({document:e}){let t=e.metadata;return(0,X.jsxs)(`div`,{className:`space-y-6`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,X.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,X.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,X.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:hd(e.createdAt)})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:hd(e.updatedAt)})]})]})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,X.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,X.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,X.jsx)(_d,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,X.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=Sd(e.url);return(0,X.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,X.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),e.status&&e.status!==`available`&&(0,X.jsx)(`span`,{className:`shrink-0 rounded border px-1 text-xs`,title:e.statusChangedAt,children:e.status===`deleted`?`Deleted`:`Not found`}),r&&(0,X.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,X.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,X.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,X.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,X.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,X.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,X.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,X.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,X.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,X.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function yd({document:e}){let{showSuccessToast:t,showErrorToast:n}=Ct(),r=JSON.stringify(e,null,2);return(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)(`div`,{className:`flex justify-end`,children:(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,X.jsx)(f,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,X.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function bd({document:e,workspaceId:t}){let[n,r]=(0,J.useState)(null),[i,a]=(0,J.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,J.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,J.useEffect)(()=>{let n=!1;return Xt(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,X.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,X.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,X.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,X.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,X.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,X.jsx)(ld,{document:e,workspaceId:t})]}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function xd(e){return e===`stored`?lt:e===`workspace-file`?B:e===`imap`?qe:e===`readonly`?H:tt}function Sd(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 Cd({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Ct(),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(null),[d,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(null),[g,_]=(0,J.useState)(!1),v=`${t}:${e.id}`,[y,b]=(0,J.useState)(v);v!==y&&(b(v),o(null),c(null),p(null));let x=()=>{Qt(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,J.useEffect)(()=>{let n=!1;return Qt(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)=>{u(a),p(null);try{let i=await yn(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{u(null)}},C=async(a,o,s)=>{_(!0);try{let i=await Fn(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(Xl(i.failed,new Map([[e.id,Bt(e)||`Document ${e.id}`]]))||`Transfer failed`);let l=c.transfers?.flatMap(e=>e.state===`unchanged`?[]:[e.backend])??[],u=a.join(`, `);o===`delete`?r(`Deleted from ${u}`):l.length===0?r(`Nothing to do — already on ${u}`):r(`${o===`move`?`Moved to`:`Copied to`} ${l.join(`, `)}${c.transfers?.some(e=>e.state===`pending`)?` (pending sync)`:``}`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),h(null),n?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{_(!1)}},w=e=>{if((a?.length??0)<=1){p(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&S(e.url)};if(s)return(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let T=a.length===0,E=Bt(e);return(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,X.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,X.jsx)(lt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,X.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,X.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),T?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>h(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,X.jsx)(f,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>h(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,X.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=xd(n.kind),{backend:a,key:o}=Sd(n.url),s=l===n.url;return(0,X.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,X.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,X.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,X.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,X.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,X.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,X.jsx)(`button`,{onClick:()=>Wt(t,e.id,E||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,X.jsx)(Ne,{className:`h-3.5 w-3.5`})}),(0,X.jsx)(`button`,{onClick:()=>w(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,X.jsx)(he,{className:`h-3.5 w-3.5`})})]})]}),d===n.url&&(0,X.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,X.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,X.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,X.jsx)(q,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!1),children:`Also remove index entry`}),(0,X.jsx)(q,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!0),children:`Keep index entry (no bytes)`}),(0,X.jsx)(q,{variant:`ghost`,size:`sm`,onClick:()=>p(null),children:`Cancel`})]})]})]},n.url)}),m&&(0,po.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,X.jsx)(ru,{workspaceId:t,documentCount:1,initialMode:m,defaultFilename:E,saving:g,onConfirm:C,onClose:()=>{g||h(null)}})}),window.document.body)]})}function wd(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 Td(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 Ed(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&&Td(e,t,n.points)}function Dd(e,t,n=!1){let r=wd(e);return r?Ed(r.lat,r.lon,t):n}var Od=(0,J.lazy)(()=>s(()=>import(`./LocationTab-BONJQfYM.js`),__vite__mapDeps([27,3,4,28,29]))),kd=[{id:`view`,label:`View`,icon:st},{id:`location`,label:`Location`,icon:we},{id:`metadata`,label:`Metadata`,icon:m},{id:`json`,label:`JSON`,icon:_e},{id:`synapses`,label:`Synapses`,icon:Ue},{id:`backends`,label:`Backends`,icon:lt}];function Ad({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=Zn()!=null,d=wd(e),f=kd.filter(e=>(e.id!==`location`||d!==null)&&(!u||![`synapses`,`backends`].includes(e.id))),[p,m]=(0,J.useState)(n),h=`${e.id}:${n}`,[g,_]=(0,J.useState)(h);h!==g&&(_(h),m(n));let v=f.some(e=>e.id===p)?p:`view`,y=e=>{m(e),l?.(e)},b=o&&!!c&&!s,x=(0,X.jsx)(`div`,{className:W(b&&`document-detail-header shrink-0 border-b-[3px] bg-muted`),children:(0,X.jsxs)(`div`,{className:W(`flex min-w-0 items-center`,b&&`mx-auto h-[calc(3rem-4px)] w-full max-w-[var(--document-reading-width,100%)] gap-1 pl-2 pr-2 sm:pl-4`),children:[(0,X.jsx)(Nl,{tabs:f,active:v,onChange:y,className:W(`min-w-0 flex-1 px-1`,b&&`h-full border-b-0 px-0 max-sm:gap-0 max-sm:[&>button]:px-2.5`),iconOnly:o}),c]})});return(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[s?(0,X.jsx)(Ml,{...s,tabs:x,section:v,onDocument:()=>y(`view`),onSection:()=>y(`view`),onBack:v===`view`?s.onBack:()=>y(`view`)}):x,(0,X.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,X.jsxs)(`div`,{className:`mx-auto h-full w-full max-w-[var(--document-reading-width,100%)] p-4`,children:[v===`view`&&(0,X.jsx)(md,{document:e,workspaceId:t,initialEdit:r&&!u,onChanged:i}),v===`location`&&d&&(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,X.jsx)(Od,{lat:d.lat,lon:d.lon})}),v===`metadata`&&(0,X.jsx)(vd,{document:e,workspaceId:t}),v===`json`&&(0,X.jsx)(yd,{document:e,workspaceId:t}),v===`synapses`&&!u&&(0,X.jsx)(bd,{document:e,workspaceId:t}),v===`backends`&&!u&&(0,X.jsx)(Cd,{document:e,workspaceId:t,onChanged:i})]})})]})}function jd(e,t){let[n,r]=(0,J.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,J.useState)(a);a!==o&&(s(a),r(null));let c=(0,J.useRef)(a),l=(0,J.useRef)(0);(0,J.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,J.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}Dn(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}function Md(e){return e.schema===`data/schema/note`?it:e.schema===`data/schema/tab`?Fe:e.schema===`data/schema/file`?$e:e.schema===`data/schema/message/email`?qe:tt}function Nd({entry:e,onClose:t,frame:n}={}){let r=rd(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=jd(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,X.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,X.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between border-b-[3px] bg-muted pl-4 pr-2`,children:[(0,X.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,X.jsx)(`button`,{type:`button`,onClick:a,className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent`,"aria-label":`Close`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),(0,X.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,X.jsx)(`button`,{type:`button`,className:`ml-2 underline`,onClick:r.retry,children:`Retry`})]})]}):null;let{workspaceId:c}=i,l=t=>{s(t),t&&t.id!==i.document.id&&!e&&r.replace?.(t,c)};return(0,X.jsx)(Ol,{title:At(o).title,icon:Md(o),onClose:r.alwaysOn?void 0:a,onSave:async e=>(await Pt(c,e.path,[o.id],e.treeName,e.treeType),[o.id]),canSave:!0,successMessage:`Linked`,lockedWorkspaceName:c,relationSubjectId:o.id,frame:n,fillParent:!0,fullWidthContent:pc(o)===hs,maximized:e?void 0:r.location?.maximized,onMaximizedChange:e?void 0:e=>r.update?.({maximized:e}),children:t=>(0,X.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,X.jsx)(Ad,{document:o,workspaceId:c,onChanged:l,compact:!0,tabActions:t,initialTab:e?void 0:r.location?.section,onTabChange:e?void 0:e=>r.update?.({section:e})},`${c}:${o.id}`)})})}var Pd=320,Fd=1600;function Id({edge:e}){let t=Go(),n=(0,J.useRef)(null),r=e===`left`?-1:1;return(0,X.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":Pd,"aria-valuemax":Fd,"aria-valuenow":t??420,tabIndex:0,title:`Drag to resize; arrow keys adjust width; double-click to reset`,className:`absolute inset-y-0 ${e===`left`?`left-0`:`right-0`} z-20 hidden w-2 touch-none cursor-col-resize select-none hover:bg-primary/20 focus-visible:bg-primary/20 focus-visible:outline-none md:block`,onPointerDown:t=>{if(t.button!==0)return;t.preventDefault(),t.stopPropagation();let r=t.currentTarget.closest(`[data-reader-pane]`),i=e===`left`?(r.parentElement?.clientWidth??window.innerWidth)-248:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(Pd,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&Wo(Math.min(n.current.max,n.current.width+r*(e.clientX-n.current.x)))},onPointerUp:e=>{n.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{n.current=null},onLostPointerCapture:()=>{n.current=null},onDoubleClick:()=>Wo(null),onKeyDown:e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`&&e.key!==`Home`)return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.closest(`[data-reader-pane]`);e.key===`Home`?Wo(null):Wo(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function Ld(e){let t=yo(),n=Io(),r=Yo(),i=rd();return!e.enabled||!e.workspaceId||!n||r||t?.width!==void 0&&t.width<720||i.location?e.children:(0,X.jsx)(Rd,{...e,workspaceId:e.workspaceId},e.scope)}function Rd({workspaceId:e,scope:t,documents:n,loading:r,children:i}){let a=Go(),o=`canvas:readerSelection:${t}`,[s,c]=(0,J.useState)(()=>{try{return Number(sessionStorage.getItem(o))||null}catch{return null}}),l=r?null:n.find(e=>e.id===s)??n[0]??null,u=(0,J.useCallback)((t,n)=>{if(n===e){c(t.id);try{sessionStorage.setItem(o,String(t.id))}catch{}}},[e,o]),d=(0,J.useMemo)(()=>({entry:l?{document:l,workspaceId:e}:null,alwaysOn:!0,open:u,preview:u,replace:u,close:()=>{}}),[l,e,u]);return(0,X.jsx)(td.Provider,{value:d,children:(0,X.jsxs)(`div`,{"data-always-reader":!0,className:`flex h-full min-h-0 min-w-0 flex-1 gap-shell`,children:[(0,X.jsx)(`div`,{className:`min-h-0 min-w-0 flex-1 overflow-auto`,children:i}),(0,X.jsxs)(`aside`,{"data-reader-pane":!0,"aria-label":`Document reading pane`,style:{width:a?`${a}px`:`50vw`,maxWidth:`calc(100% - 240px)`},className:`relative flex min-h-0 min-w-0 shrink-0 overflow-hidden border-l bg-card`,children:[(0,X.jsx)(Id,{edge:`left`}),l?(0,X.jsx)(Nd,{},`${e}:${l.id}`):(0,X.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground`,role:`status`,children:r?`Loading documents…`:`No documents in this list`})]})]})})}async function zd(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 Bd(e){return`/workspaces/${e}/hooks`}async function Vd(e){return await K.get(Bd(e))||[]}async function Hd(e,t){return(await K.get(`${Bd(e)}/${t}`))?.content??``}async function Ud(e,t,n){await K.put(`${Bd(e)}/${t}`,{content:n})}async function Wd(e,t){await K.delete(`${Bd(e)}/${t}`)}var Gd=[`example-`,`disabled-`,`_`];function Kd(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function qd(e){return Gd.find(t=>e.startsWith(t))??null}function Jd(e){return qd(Kd(e).base)===null}function Yd(e){return Kd(e).base.startsWith(`example-`)}function Xd(e){let{dir:t,base:n}=Kd(e),r=qd(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function Zd(e,t,n){if(Jd(t)===n)return t;let r=Xd(t);return await Ud(e,r,await Hd(e,t)),await Wd(e,t),r}function Qd(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 $d(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function ef(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function tf(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 nf(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 rf(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var af=`rules.json`;async function of(e){try{let t=await Hd(e,af),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function sf(e,t){await Ud(e,af,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
14
|
-
`)}async function cf(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 K.get(`${Bd(e)}/pending${r?`?${r}`:``}`)||[]}async function lf(e,t){return await K.post(`${Bd(e)}/pending/decisions`,t)}async function uf(e,t){return await K.get(`${Bd(e)}/runs/${encodeURIComponent(t)}`)}async function df(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 K.get(`${Bd(e)}/runs${r?`?${r}`:``}`)||[]}var ff=1e4,pf=`canvas.hooks.backfillLimit`;function mf(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?500:Math.min(t,ff)}function hf(){try{let e=localStorage.getItem(pf);return e?mf(e):500}catch{return 500}}function gf(e){let t=mf(e);try{localStorage.setItem(pf,String(t))}catch{}return t}function _f(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 vf(e,t){return await K.post(`${Bd(e)}/backfill`,t)}function yf(e,t){return K.post(`${Bd(e)}/backfill/jobs`,t)}function bf(e,t){return K.get(`${Bd(e)}/backfill/jobs/${t}`)}function xf(e,t){return K.delete(`${Bd(e)}/backfill/jobs/${t}`)}function Sf(e){return K.get(`${Bd(e)}/backfill/jobs`)}async function Cf(e,t){return await K.post(`${Bd(e)}/run`,t)}async function wf(e,t){return await K.post(`${Bd(e)}/runs/${t}/replay`,{})}async function Tf(e){return await K.get(`${Bd(e)}/meta`)}async function Ef(e,t){return await K.post(`${Bd(e)}/generate`,t)}async function Df(e,t){let n=await Hd(e,af),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 Ud(e,af,JSON.stringify(o,null,2)+`
|
|
15
|
-
`)}var Of=Df;function kf(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 Af(){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 jf(){let[e]=(0,J.useState)(Af);return(0,J.useEffect)(()=>e.cancel,[e]),{onPointerDown:t=>{if(e.reset(),t.pointerType!==`touch`||!t.isPrimary)return;let n=t.target;if(!t.currentTarget.contains(n)||n.closest(`button, input, textarea, select, a, [contenteditable="true"], [role="dialog"]`))return;let{clientX:r,clientY:i}=t;e.start(r,i,()=>{n.dispatchEvent(new window.MouseEvent(`contextmenu`,{bubbles:!0,cancelable:!0,clientX:r,clientY:i}))})},onPointerMove:t=>e.move(t.clientX,t.clientY),onPointerUp:e.cancel,onPointerCancel:e.cancel,onPointerLeave:e.cancel,onDragStartCapture:t=>{e.cancel(),e.consumeClick()&&t.preventDefault()},onContextMenuCapture:t=>{t.isTrusted&&e.contextMenu()&&(t.preventDefault(),t.stopPropagation())},onClickCapture:t=>{e.consumeClick()&&(t.preventDefault(),t.stopPropagation())}}}function Mf(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 Nf(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 Pf=e=>typeof e==`string`?e:``,Ff=e=>e&&typeof e==`object`?e:{},If=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);function Lf(e){let t=e.data||{},n=e.schema===`data/schema/message/email`,r=!n&&e.schema.startsWith(`data/schema/message`),i=Pf(t.platform),a=Pf(Ff(t.channel).id)||Pf(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=Pf(Ff(t.from).address)||Pf(t.from);e&&s(`sender`,`Mail from ${e}`,{from:{equals:e}}),t.subject&&s(`subject`,`Subject matches regex`,{subject:{regex:If(t.subject)}})}else if(r){let e=Pf(Ff(t.sender).id)||Pf(Ff(t.sender).username)||Pf(Ff(t.sender).name)||Pf(t.sender),n=Pf(Ff(t.sender).name)||Pf(Ff(t.sender).username)||e;e&&s(`sender`,`Messages from ${n}`,{...c,sender:{equals:e}})}let l=Pf(t.body)||Pf(t.text)||Pf(t.content)||Pf(t.bodyHtml)||Pf(t.bodyPreview);if((n||r||l)&&s(`body`,n?`Email body matches regex`:`Text matches regex`,{...c,body:{regex:If(l.slice(0,160))}}),r){let n=Pf(t.threadId)||([`slack`,`teams`].includes(i)?Pf(Ff(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:If(t.url)}}),s(`schema`,`All items of this type`,{}),o}function Rf({label:e,onClose:t,children:n}){return _c(t),(0,po.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-dialog flex items-center justify-center bg-scrim p-4`,onClick:t,children:(0,X.jsx)(`section`,{"data-dialog-surface":!0,role:`dialog`,"aria-modal":`true`,"aria-label":e,className:`h-[86dvh] max-h-full min-h-0 w-full max-w-3xl overflow-y-auto rounded-(--panel-radius) border bg-popover text-popover-foreground shadow-elevation-4`,onClick:e=>e.stopPropagation(),children:n})}),window.document.body)}function zf(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}`}}var Bf=`Applying rules to existing documents…`,Vf=new Map;function Hf(e){return`${e.ruleIds.length>1?`Rule ${e.ruleIndex+1}/${e.ruleIds.length}: `:``}${e.processed}${e.total===null?``:` / ${e.total}`} documents · ${e.applied} applied`}function Uf(e,t){let n=`${t.checked} checked, ${t.applied} applied${t.skipped?`, ${t.skipped} already there`:``}`;t.status===`cancelled`?e.done({title:`Cancelled`,description:n}):t.status===`failed`?e.fail({title:`Stopped before finishing`,description:`${n}: ${t.error}. The rule stays enabled; rerun it from Rules to finish.`,variant:`destructive`}):t.failed?e.done({title:`Finished with errors`,description:`${n}, ${t.failed} failed. Details in the rule’s run log.`,variant:`destructive`}):e.done({title:`Rule applied`,description:n})}function Wf(e,t,n){let r=Vf.get(n.id);if(r)return r;let i=new Promise(r=>{let i={channel:`workspace:${t}`},a=e({title:Bf,description:Hf(n),action:{label:`Cancel`,onClick:()=>{a.update({title:`Cancelling…`,description:Hf(n)}),xf(t,n.id).catch(()=>a.update({title:Bf,description:`Could not cancel. Try again.`}))}}}),o=()=>{u?.(),go.off(`job.progress`,c),go.off(`job.finished`,c),r()},s=e=>{if(e.status===`running`)return a.update({title:Bf,description:Hf(e)});Uf(a,e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),o()},c=e=>{let t=e?.job;t?.id===n.id&&s(t)},l=()=>{go.emit(`subscribe`,i),bf(t,n.id).then(s,()=>{})},u=go.on(`connect`,l);go.on(`job.progress`,c),go.on(`job.finished`,c),l()});return Vf.set(n.id,i),i.finally(()=>Vf.delete(n.id)),i}async function Gf(e,t,n){let r;try{r=await yf(t,{ruleIds:n,limit:hf()})}catch(t){e({title:Bf}).fail({title:`Could not start`,description:`${t instanceof Error?t.message:String(t)}. The rule stays enabled; rerun it from Rules.`,variant:`destructive`});return}return Wf(e,t,r)}async function Kf(e,t){let n=await Sf(t).catch(()=>[]);for(let r of n)r.status===`running`&&Wf(e,t,r)}function qf(e){return`/workspaces/${e}/scripts`}async function Jf(e){return await K.get(qf(e))||[]}async function Yf(e,t){return(await K.get(`${qf(e)}/${t}`))?.content??``}async function Xf(e,t,n){await K.put(`${qf(e)}/${t}`,{content:n})}async function Zf(e,t){await K.delete(`${qf(e)}/${t}`)}function Qf({value:e,onChange:t,onPickTarget:n,fixedWorkspaceName:r,format:i=`url`,tabs:a=[`context`,`directory`],pickerTitle:o=`Pick a path…`,placeholder:s,id:c,disabled:l,className:u,inputClassName:d,presentation:f=`input`}){let[p,m]=(0,J.useState)(!1),h=e.match(/^(.*?):\/\//)?.[0]||``,g=h?e.slice(h.length):e;return(0,X.jsxs)(`div`,{className:W(`flex gap-2`,u),children:[f===`breadcrumbs`?(0,X.jsx)(pl,{items:ml(g,h.replace(`://`,``)||r||`Workspace`),onNavigate:e=>t(h?`${h}${e.replace(/^\/+/,``)}`:e),disabled:l,className:W(`rounded border px-1`,d)}):(0,X.jsx)(G,{id:c,value:e,onChange:e=>t(e.target.value),placeholder:s,disabled:l,className:W(`font-mono`,d)}),(0,X.jsx)(q,{type:`button`,variant:`outline`,size:`icon`,onClick:()=>m(!0),disabled:l,"aria-label":`Browse tree paths`,title:`Browse…`,className:`shrink-0`,children:(0,X.jsx)(y,{className:`h-4 w-4`})}),p&&(0,X.jsx)(Ql,{onClose:()=>m(!1),children:(0,X.jsx)(Tl,{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 $f=[{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`}],ep=[{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.`}],tp=[{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`}],np=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),rp=e=>np.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),ip=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:qe,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:qe,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:qe,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:B,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:Ne,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:Xe,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:Xe,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`tag`,label:`add tags`,icon:re,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`},{key:`unstore`,label:`delete the file from a storage backend`,icon:ye,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`notify`,label:`Send me a notification`,icon:We,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:R,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`},{key:`script`,label:`run a script`,icon:xe,tone:`text-slate-600 dark:text-slate-300 bg-slate-500/10`},{key:`delete`,label:`delete it from Canvas`,icon:he,tone:`text-destructive bg-destructive/10`},{key:`destroy`,label:`delete it everywhere`,icon:he,tone:`text-destructive bg-destructive/10`}],ap=e=>ip.find(t=>t.key===e)||ip[1],op=`{{title}}{{ext}}`,sp=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,cp=[{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.`}],lp=[{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}),up={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[Z(`link`)]},dp=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function fp(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var pp=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),mp=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:qe,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:()=>({...up,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:qe,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:()=>({...up,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:B,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})=>({...up,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:l,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})=>({...up,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:Xe,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:()=>({...up,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:qe,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:()=>({...up,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:Ne,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})=>({...up,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:R,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:()=>({...up,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:nt,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...up})}];function hp(e){let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field));if(t.length!==1||t[0].field!==`eventPathExact`)return null;let n=dp(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function gp(e){if(hp(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>dp(e.value));return t.length>0&&t.every(e=>/^(dir|directory|backends):\//.test(e))}function _p(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=hp(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`?sp:e.b||`<filename>`].filter(Boolean).join(`/`)}}function vp(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=np.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:dp(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${tp.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${tp.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[rp(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=pp(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:pp(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:pp(r),...s,...i?{tags:pp(i)}:{}}),n.kind===`unlink`&&r&&o.push({action:`unlink`,paths:pp(r),...s}),n.kind===`tag`&&r&&o.push({action:`tag`,tags:pp(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&&!gp(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`?op:n.storeName===`dated`?sp: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&&hp(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=pp(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:pp(i)}:{},...n.dlTags.trim()?{tags:pp(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||fp(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 yp(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`&&ep.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(np.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||hp(y)===null)||t.recursive===!0&&hp(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===op||e===sp?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===op?`title`:e===sp?`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(!cp.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 bp=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function xp(e,t=$f){let n=e.when,r=$d(e).map(e=>ep.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${bp(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 Sp(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 Cp(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===op?`, named by title`:e.key===sp?`, 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=cp.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=Sp(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=Sp(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function wp(e){return(e.then||[]).map(Cp).join(` · `)||`(no actions)`}function Tp(e){return ef(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function Ep(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 Dp(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 Op(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function kp(e){if(e.kind===`document`&&e.rule)return{...yp(e.rule)||up,id:null};if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...up,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{...up,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:gp(r)}]}}return{...up,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 Ap=`h-10 w-full rounded-md border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`,Q=`h-10 text-sm`;function $({label:e,hint:t,children:n,className:r}){return(0,X.jsxs)(`label`,{className:W(`flex min-w-0 flex-col gap-1.5`,r),children:[(0,X.jsx)(`span`,{className:`text-sm font-medium`,children:e}),n,t&&(0,X.jsx)(`span`,{className:`text-xs leading-relaxed text-muted-foreground`,children:t})]})}function jp({checked:e,onChange:t,label:n,hint:r,disabled:i}){return(0,X.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:i,onClick:()=>t(!e),className:W(`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40 disabled:cursor-not-allowed disabled:opacity-50`,e&&`border-primary/40 bg-primary/5`),children:[(0,X.jsx)(`span`,{className:W(`mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5 transition-colors`,e?`bg-primary`:`bg-muted-foreground/30`),children:(0,X.jsx)(`span`,{className:W(`h-4 w-4 rounded-full bg-background shadow transition-transform`,e&&`translate-x-4`)})}),(0,X.jsxs)(`span`,{className:`min-w-0`,children:[(0,X.jsx)(`span`,{className:`block text-sm font-medium`,children:n}),r&&(0,X.jsx)(`span`,{className:`block text-xs leading-relaxed text-muted-foreground`,children:r})]})]})}function Mp({value:e,options:t,onChange:n}){return(0,X.jsx)(`div`,{className:`inline-flex h-10 rounded-md border bg-background p-1`,children:t.map(t=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>n(t.value),className:W(`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 Np({active:e,onClick:t,children:n,title:r}){return(0,X.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:W(`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 Pp({step:e,title:t,hint:n}){return(0,X.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,X.jsx)(`span`,{className:`mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary`,children:e}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`text-base font-semibold leading-7`,children:t}),n&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]})]})}function Fp({icon:e,tone:t,size:n=`md`}){return(0,X.jsx)(`span`,{className:W(`inline-flex shrink-0 items-center justify-center rounded-xl`,n===`lg`?`h-12 w-12`:`h-10 w-10`,t),children:(0,X.jsx)(e,{className:n===`lg`?`h-6 w-6`:`h-5 w-5`})})}function Ip({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:i,onPrefillConsumed:a,createOnly:o=!1,onCreated:s,onCancel:c}){let{showToast:l,showProgress:u}=St(),[d,f]=(0,J.useState)([]),[m,h]=(0,J.useState)({}),g=e=>{df(e,{limit:500}).then(e=>h(Ep(e))).catch(()=>h({}))},[_,v]=(0,J.useState)(!0),[b,x]=(0,J.useState)(null),[S,C]=(0,J.useState)(!1),[w,T]=(0,J.useState)(!1),[E,D]=(0,J.useState)([]),[O,k]=(0,J.useState)([]),[A,j]=(0,J.useState)([]),[N,P]=(0,J.useState)(``),F=(0,J.useRef)(null),[I,te]=(0,J.useState)(e);e!==I&&(te(e),v(!0)),(0,J.useEffect)(()=>{of(e).then(e=>f(e)).finally(()=>v(!1)),g(e)},[e]);let[ne,re]=(0,J.useState)(null);i!==ne&&(re(i),i&&(x(kp(i)),C(!1))),(0,J.useEffect)(()=>{i&&a?.()},[i,a]),(0,J.useEffect)(()=>{Jf(e).then(e=>D(e.map(e=>e.path))).catch(()=>D([]))},[e]),(0,J.useEffect)(()=>{let t=!1;return Il(e).then(e=>{t||(j([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),P(``))}).catch(()=>{t||(j([]),P(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,J.useEffect)(()=>{Pn(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);k(t);let n=Op(t);n&&x(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(()=>k([]))},[e]);let[R,z]=(0,J.useState)($f);(0,J.useEffect)(()=>{Tf(e).then(e=>{e.schemas?.length&&z([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let B=async(t,n)=>{T(!0);try{return await sf(e,t),f(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{T(!1)}},ie=async()=>{if(!b||_||w)return;let t;try{t=vp(b,O)}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)}`,T(!0);try{await Df(e,t),l({title:`Rule created`,description:`The rule will run for matching new items.`}),s?.()}catch(e){l({title:`Could not create rule`,description:e instanceof Error?e.message:`Failed to save rule`,variant:`destructive`})}finally{T(!1)}return}!b.id&&d.some(e=>e.id===t.id)&&(t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`);let n=b.id?d.map(e=>e.id===b.id?{...t,enabled:e.enabled!==!1}:e):[...d,t];await B(n,b.id?`Rule updated`:`Rule created`)&&(x(null),s?.())},oe=e=>B(d.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),se=e=>{confirm(`Delete rule "${e}"?`)&&B(d.filter(t=>t.id!==e),`Rule deleted`)},[ce,V]=(0,J.useState)(null),le=async t=>{V(t);try{let n=await vf(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 the first ${n.processed} of ${n.total??n.processed} existing documents. Run its actions on all of them now?`))return;await Gf(u,e,[t])}catch(e){l({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{V(null),g(e)}},H=(e,t)=>x(n=>n&&{...n,[e]:t}),de=e=>{x(e.build({backend:Op(O)})),C(!1),requestAnimationFrame(()=>F.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},fe=e=>{let n=yp(e);n?(x(n),C(!1),requestAnimationFrame(()=>F.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[pe,me]=(0,J.useState)(null),ge=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,ve=(e,t)=>{if(!pe||!b||!e.length){me(null);return}if(pe.target===`storeFolder`){let t=tf(e[0]);H(`actions`,b.actions.map((e,n)=>n===pe.index?{...e,storeFolder:t?.rel||``,...t?.backend&&O.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(pe.target===`condition`){let n=e.map(e=>ge(e,t)),r=t.treeType===`context`&&b.actions.some(e=>e.kind===`store`);H(`conditions`,b.conditions.map((e,t)=>t===pe.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>ge(e,t));H(`actions`,b.actions.map((e,t)=>t===pe.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}me(null)},ye=(e,t,n=`Browse…`)=>(0,X.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>me({target:e,index:t}),children:[(0,X.jsx)(y,{className:`h-4 w-4 sm:mr-1.5`}),(0,X.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),be=gp(b?.conditions||[]),xe=!!b?.conditions.some(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&e.value.trim()),Se=e=>`${e.address}${e.address===`workspace:data`?` — managed blob store (default)`:e.address===`workspace:home`?` — workspace home folder`:e.driver?` — ${e.driver}`:``}`,Ce=(e,t,n,r=`workspace:home`)=>O.length?(0,X.jsxs)(`select`,{className:Ap,value:e,onChange:e=>t(e.target.value),children:[(0,X.jsx)(`option`,{value:``,children:n}),O.map(e=>(0,X.jsx)(`option`,{value:e.address,children:Se(e)},e.address)),e&&!O.some(t=>t.address===e)&&(0,X.jsx)(`option`,{value:e,children:e})]}):(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),we=d.filter(Tp),Ee=d.filter(e=>!Tp(e)),De=({rule:e})=>{let t=e.enabled!==!1,r=yp(e)!==null,i=m[e.id],a=ap(e.then?.[0]?.action||`link`),o=ef(e);return(0,X.jsxs)(`div`,{className:W(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,X.jsx)(Fp,{icon:a.icon,tone:a.tone}),(0,X.jsxs)(`div`,{className:`rule-card-content min-w-0 space-y-1.5`,children:[(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,X.jsx)(`h3`,{className:`text-base font-semibold leading-6`,children:e.description||e.id}),e.approval===!0&&(0,X.jsx)(`span`,{className:`rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning`,children:`needs approval`}),e.cascade===!0&&(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:`incl. automation-created`}),!r&&(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,title:`This rule uses matchers the builder cannot show; edit it as JSON.`,children:`JSON only`})]}),(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:xp(e,R)}),(0,X.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,X.jsx)(Te,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{children:wp(e)})]}),o.length>0&&(0,X.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:o.join(` | `),children:o.join(` | `)}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?(0,X.jsxs)(`button`,{type:`button`,className:W(`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,` `,Dp(i.last.ts)]}):`not run yet`})]}),(0,X.jsxs)(`div`,{className:`rule-card-actions`,children:[(0,X.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t,disabled:w,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>oe(e.id),className:W(`mr-1 inline-flex h-6 w-11 items-center rounded-full p-0.5 transition-colors`,t?`bg-primary`:`bg-muted-foreground/30`),children:(0,X.jsx)(`span`,{className:W(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,X.jsxs)(q,{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:ce!==null||e.when.eventPathExact!==void 0,onClick:()=>le(e.id),children:[ce===e.id?(0,X.jsx)(ke,{className:`h-4 w-4 animate-spin`}):(0,X.jsx)(ee,{className:`h-4 w-4`}),(0,X.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Apply`})]}),(0,X.jsxs)(q,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>fe(e),children:[r?(0,X.jsx)(ae,{className:`h-4 w-4`}):(0,X.jsx)(_e,{className:`h-4 w-4`}),(0,X.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,X.jsx)(q,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>se(e.id),children:(0,X.jsx)(he,{className:`h-4 w-4`})})]})]})},Oe=(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,X.jsx)(`h3`,{className:`text-base font-semibold`,children:`What should happen automatically?`}),S&&(0,X.jsxs)(q,{size:`sm`,variant:`ghost`,onClick:()=>C(!1),children:[(0,X.jsx)(M,{className:`mr-1 h-4 w-4`}),` Close`]})]}),(0,X.jsx)(`div`,{className:`grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,17rem),1fr))] gap-3`,children:mp.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>de(e),className:`flex min-w-0 items-start gap-3 rounded-xl border bg-card p-4 text-left transition-colors hover:border-primary/50 hover:bg-accent/40`,children:[(0,X.jsx)(Fp,{icon:e.icon,tone:e.tone,size:`lg`}),(0,X.jsxs)(`span`,{className:`min-w-0`,children:[(0,X.jsx)(`span`,{className:`block text-base font-semibold leading-6`,children:e.title}),(0,X.jsx)(`span`,{className:`mt-1 block break-words text-sm leading-relaxed text-muted-foreground`,children:e.blurb})]})]},e.id))})]});return(0,X.jsxs)(`div`,{className:`rule-builder min-w-0 space-y-5`,children:[!o&&(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-[1_1_20rem]`,children:[(0,X.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Rules`}),(0,X.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Rules run automatically as items arrive or get filed — no code needed. Stored in`,` `,(0,X.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` in the workspace git.`]})]}),(0,X.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[t&&(0,X.jsxs)(q,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,X.jsx)(_e,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,X.jsxs)(q,{onClick:()=>{x(null),C(!0)},disabled:S,children:[(0,X.jsx)(L,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),S&&!b&&Oe,b&&(0,X.jsxs)(`div`,{ref:F,className:`scroll-mt-4 space-y-6 rounded-xl border bg-card p-4 sm:p-6`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,X.jsx)(`h3`,{className:`text-lg font-semibold`,children:b.id?`Edit rule`:`New rule`}),(0,X.jsxs)(q,{variant:`ghost`,size:`sm`,onClick:()=>x(null),children:[(0,X.jsx)(M,{className:`mr-1 h-4 w-4`}),` Cancel`]})]}),(0,X.jsx)($,{label:`Name`,hint:`Shown in the list and the run log.`,children:(0,X.jsx)(G,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:b.description,onChange:e=>H(`description`,e.target.value)})}),(0,X.jsxs)(`section`,{className:`space-y-4`,children:[(0,X.jsx)(Pp,{step:1,title:`When…`,hint:`What the rule reacts to. All conditions must match; repeat a condition for either/or.`}),(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-[minmax(0,220px)_1fr]`,children:[(0,X.jsx)($,{label:`Item`,children:(0,X.jsxs)(`select`,{className:Ap,value:b.schema,onChange:e=>H(`schema`,e.target.value),children:[R.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value)),b.schema&&!R.some(e=>e.value===b.schema)&&(0,X.jsx)(`option`,{value:b.schema,children:b.schema.replace(/^data\/schema\//,``)})]})}),(0,X.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,X.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Event `,(0,X.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(any of)`})]}),(0,X.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:ep.map(e=>{let t=b.events.includes(e.value);return(0,X.jsx)(Np,{active:t,title:e.hint,onClick:()=>{let n=t?b.events.filter(t=>t!==e.value):[...b.events,e.value];n.length&&H(`events`,n)},children:e.label},e.value)})})]})]}),b.conditions.length>0&&(0,X.jsx)(`div`,{className:`space-y-2`,children:b.conditions.map((e,t)=>{let n=tp.find(t=>t.key===e.field);return(0,X.jsxs)(`div`,{className:`grid grid-cols-[2.25rem_1fr_auto] items-center gap-2 sm:grid-cols-[2.25rem_minmax(0,240px)_1fr_auto]`,children:[(0,X.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,title:`Same condition again = either may match (OR); different conditions must all match (AND)`,children:b.conditions.slice(0,t).some(t=>rp(t.field)===rp(e.field))?`or`:`and`}),(0,X.jsx)(`select`,{className:Ap,value:e.field,onChange:e=>H(`conditions`,b.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:tp.map(e=>(0,X.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,X.jsxs)(`div`,{className:`order-4 col-span-3 flex gap-2 sm:order-3 sm:col-span-1`,children:[(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>H(`conditions`,b.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&ye(`condition`,t,`Browse the workspace trees`)]}),(0,X.jsx)(q,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>H(`conditions`,b.conditions.filter((e,n)=>n!==t)),children:(0,X.jsx)(M,{className:`h-4 w-4`})})]},t)})}),(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,X.jsxs)(q,{size:`sm`,variant:`outline`,onClick:()=>H(`conditions`,[...b.conditions,{field:b.schema===`email`?`from`:`path`,value:``}]),children:[(0,X.jsx)(L,{className:`mr-1 h-4 w-4`}),` Add condition`]}),(0,X.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Contains matches literal text. Regex is case-insensitive: enter the pattern without /…/ delimiters; | stays part of the expression. For other filters, separate alternatives with `,(0,X.jsx)(`span`,{className:`font-mono`,children:`|`}),`, e.g. `,(0,X.jsx)(`span`,{className:`font-mono`,children:`image/* | video/*`}),`.`]})]})]}),(0,X.jsxs)(`section`,{className:`space-y-4`,children:[(0,X.jsx)(Pp,{step:2,title:`Then…`,hint:`Actions run in order. The item keeps its id, tags and folders unless an action says otherwise.`}),b.actions.map((t,n)=>{let r=e=>H(`actions`,b.actions.map((t,r)=>r===n?{...t,...e}:t)),i=O.find(e=>e.address===t.a),a=i?.capabilities?.paths===!0,o=be&&a,s=ap(t.kind),c=n=>(0,X.jsxs)(`div`,{className:`space-y-3 rounded-lg border border-dashed p-3`,children:[(0,X.jsxs)(`p`,{className:`text-sm font-medium`,children:[`What to do with the `,n]}),(0,X.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Save as a note at`,hint:`Context path by default, dir:/path for the directory tree.`,children:(0,X.jsx)(Qf,{inputClassName:Q,placeholder:`/notes/summaries (optional)`,value:t.notePath,onChange:e=>r({notePath:e}),fixedWorkspaceName:e,pickerTitle:`Save note under…`,onPickTarget:(e,t)=>r({notePath:t.treeType===`directory`?`dir:${e}`:e})})}),t.notePath.trim()&&(0,X.jsx)($,{label:`Note title`,children:(0,X.jsx)(G,{className:Q,placeholder:`Summary: {{doc.data.subject}}`,value:t.noteTitle,onChange:e=>r({noteTitle:e.target.value})})}),(0,X.jsx)($,{label:`Save as a file at`,hint:`Relative path under the workspace home folder or in the data blob store.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`logs/agent.log (optional)`,value:t.filePath,onChange:e=>r({filePath:e.target.value})})}),t.filePath.trim()&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{label:`File lives in`,children:(0,X.jsxs)(`select`,{className:Ap,value:t.fileBackend,onChange:e=>r({fileBackend:e.target.value}),children:[(0,X.jsx)(`option`,{value:`home`,children:`the workspace home folder`}),(0,X.jsx)(`option`,{value:`data`,children:`the data blob store`})]})}),(0,X.jsx)($,{label:`Also file the saved file under`,hint:`Index it as a document at this tree path.`,children:(0,X.jsx)(Qf,{inputClassName:Q,placeholder:`/path (optional)`,value:t.fileInsert,onChange:e=>r({fileInsert:e}),fixedWorkspaceName:e,tabs:[`context`],pickerTitle:`File under…`,onPickTarget:e=>r({fileInsert:e})})})]})]}),(0,X.jsx)(jp,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send me a notification with the result`})]}),l=hp(b.conditions),u=t.kind===`store`&&t.a&&(!t.recursive||o)?_p(t,b.conditions,i):null,d=t.kind===`extractAttachments`&&t.a?zf(t.a,t.storeFolder,t.attachmentPath):null;return(0,X.jsxs)(`div`,{className:`space-y-4 rounded-xl border bg-background p-4`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,X.jsx)(Fp,{icon:s.icon,tone:s.tone}),(0,X.jsx)(`select`,{className:W(Ap,`flex-1 font-medium`),value:t.kind,onChange:e=>r(Z(e.target.value)),children:ip.map(e=>(0,X.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,X.jsx)(q,{size:`sm`,variant:`ghost`,className:`h-10 w-10 shrink-0 p-0 text-muted-foreground`,title:`Remove action`,disabled:b.actions.length===1,onClick:()=>H(`actions`,b.actions.filter((e,t)=>t!==n)),children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),(t.kind===`link`||t.kind===`unlink`)&&(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsx)($,{label:t.kind===`link`?`Folder(s)`:`Remove from folder(s)`,hint:`Context-tree path by default; dir:/path for the directory tree. Comma-separate several.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(G,{className:W(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})}),ye(`action`,n)]})}),t.kind===`link`&&(0,X.jsx)($,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,X.jsx)(jp,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:xe?`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:!xe})]}),t.kind===`moveMessage`&&(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)($,{label:`Mail folder`,hint:`The folder on the email's own IMAP account, with / between levels (works for servers that use . too). {{YYYY}}, {{MM}}, {{DD}} = the email's date.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`INBOX/Accounting/{{YYYY}}/Expenses`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Moves the message on the mail server, like dragging it in a mail client. Put this after Extract attachments so the files are copied first. The folder must already exist on the server; subscribe to it in the mailbox settings to see the moved mail in Canvas.`})]}),t.kind===`tag`&&(0,X.jsx)($,{label:`Tags`,hint:`Comma-separated.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`urgent, follow-up`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`store`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Storage backend`,hint:`Where the file's bytes should live. Only writable backends are listed.`,children:Ce(t.a,e=>r({a:e}),`pick a backend…`)}),(0,X.jsx)($,{label:`Destination root folder`,hint:`Choose the folder beneath which the path will be recreated. Leave empty to use the backend root.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),ye(`storeFolder`,n,`Browse storage backends`)]})}),(0,X.jsx)($,{label:`File name`,children:(0,X.jsx)(`select`,{className:Ap,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:lp.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,X.jsx)($,{label:`Move or copy`,hint:t.storeMode===`move`?`Remove only the selected source copy after the destination is safely stored.`:`Preserve every existing copy.`,children:(0,X.jsx)(Mp,{value:t.storeMode,onChange:e=>r({storeMode:e}),options:[{value:`copy`,label:`Copy`},{value:`move`,label:`Move`}]})}),t.storeMode===`move`&&(0,X.jsx)($,{className:`sm:col-span-2`,label:`Move bytes from (required)`,hint:`Context membership does not identify a source copy. If the file is absent here, nothing is moved. Multiple locations on this backend make the move ambiguous; use copy.`,children:Ce(t.storeFrom,e=>r({storeFrom:e}),`choose a source backend…`,`workspace:data`)}),t.storeName===`custom`&&(0,X.jsx)($,{className:`sm:col-span-2`,label:`Name template`,hint:`Tokens: {{YYYY}} {{MM}} {{DD}} {{HH}} {{mm}} {{ss}} (photo capture time when present), {{ext}} {{basename}} {{filename}} {{title}} {{id}}, plus {{doc.…}} fields. Slashes create sub-folders.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,X.jsx)(jp,{checked:t.recursive,onChange:e=>r({recursive:e}),label:l===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:a?be?l===null?`The path below the source folder is appended beneath the destination root: …/UI/mobile → Root/mobile. Missing destination folders are created.`:`Only inserts or links directly into ctx:${l} trigger this rule. Its full path is appended beneath the destination root; descendant inserts do not match.`:`For Context, choose one folder with “is inserted / linked directly into”. Directory and Backends sources can include sub-folders.`:`Choose a destination that reports support for folder paths. Content-addressed blob stores cannot recreate sub-folder paths.`,disabled:!o&&!t.recursive}),u&&(0,X.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,X.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,X.jsxs)(`span`,{className:`break-all font-mono`,children:[u.root,`/`]})]}),t.recursive&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,X.jsxs)(`span`,{className:`break-all font-mono`,children:[u.recreated||`(root)`,`/`]})]}),(0,X.jsx)(`p`,{className:`break-all font-mono`,children:u.result})]}),(0,X.jsxs)(`details`,{className:`group rounded-lg border`,children:[(0,X.jsxs)(`summary`,{className:`flex cursor-pointer select-none items-center gap-2 px-3 py-2 text-sm font-medium`,children:[(0,X.jsx)(ue,{className:`h-4 w-4 transition-transform group-open:rotate-180`}),` More options`]}),(0,X.jsxs)(`div`,{className:`grid gap-4 border-t p-3 sm:grid-cols-2`,children:[t.storeMode===`copy`&&(0,X.jsx)($,{label:`Copy bytes from`,hint:`Optional source restriction. Default: any readable copy outside the destination backend.`,children:Ce(t.storeFrom,e=>r({storeFrom:e}),`any readable source`,`workspace:data (optional)`)}),(0,X.jsx)($,{label:`If the name is already taken`,children:(0,X.jsxs)(`select`,{className:Ap,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,X.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,X.jsx)(`option`,{value:`error`,children:`skip the file`}),(0,X.jsx)(`option`,{value:`overwrite`,children:`overwrite the existing file`})]})})]})]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The item keeps its id and virtual tree memberships. A move removes the chosen physical source location from the backend tree.`})]}),t.kind===`extractAttachments`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Attachment types`,hint:`MIME types, comma-separated. application/pdf for PDFs, image/* for images, or * for all.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`application/pdf`,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,X.jsx)($,{label:`Attachment filename contains`,hint:`Optional: invoice, faktura, or another literal filename fragment. Every selected attachment must also match its type.`,children:(0,X.jsx)(G,{className:Q,placeholder:`Any matching filename`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})}),(0,X.jsx)($,{label:`Storage backend`,hint:`Choose a writable backend that supports folder paths.`,children:Ce(t.a,e=>r({a:e}),`pick a backend…`)}),(0,X.jsx)($,{label:`Destination root folder`,hint:`Choose the folder beneath which date subfolders will be created. Leave empty to use the backend root.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),ye(`storeFolder`,n,`Browse storage backends`)]})}),(0,X.jsx)($,{label:`Sub-folder path template`,hint:`Appended beneath the root folder. {{YYYY}} = year, {{MM}} = month, {{DD}} = day of the email. Leave empty to file directly in the root folder.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`No subfolders`,value:t.attachmentPath,onChange:e=>r({attachmentPath:e.target.value})})}),(0,X.jsx)($,{label:`If the attachment name is already taken`,children:(0,X.jsxs)(`select`,{className:Ap,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,X.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,X.jsx)(`option`,{value:`error`,children:`skip the file and report the conflict`})]})})]}),!a&&(0,X.jsx)(`p`,{className:`text-sm text-amber-700 dark:text-amber-400`,children:`This destination has not reported support for folder paths. Select a supported backend before saving.`}),d&&(0,X.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,X.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Example email dated `,d.date,`. Each email supplies its own date.`]}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,X.jsxs)(`span`,{className:`break-all font-mono`,children:[d.root,`/`]})]}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,X.jsx)(`span`,{className:`break-all font-mono`,children:d.added?`${d.added}/`:`(none)`})]}),(0,X.jsx)(`p`,{className:`break-all font-mono`,children:d.result})]}),(0,X.jsx)(jp,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Off by default, so signature images and embedded resources are excluded.`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copies matching attachments and keeps the email and its original files. Missing folders are created on the backend. Dates use the email's sent date (received/content date, then creation date if absent), in the server's timezone. This does not read the invoice date from the PDF.`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Use Apply on the saved rule to process existing mail within the selected batch size. Add a subject or attachment filename condition if you need to distinguish invoices from other PDFs.`})]}),t.kind===`download`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Download`,hint:cp.find(e=>e.value===t.dlKind)?.hint,children:(0,X.jsx)(`select`,{className:Ap,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:cp.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),t.dlKind===`website`?(0,X.jsx)($,{label:`Mirror depth`,hint:`How many link hops to follow on the same site (1–5).`,children:(0,X.jsx)(G,{type:`number`,min:1,max:5,className:W(Q,`sm:max-w-32`),value:t.dlDepth,onChange:e=>r({dlDepth:e.target.value})})}):(0,X.jsx)(`div`,{className:`hidden sm:block`}),(0,X.jsx)($,{label:`Storage backend`,hint:`Where the downloaded file's bytes should live.`,children:Ce(t.a,e=>r({a:e}),`workspace:home (default)`)}),(0,X.jsx)($,{label:`Folder on that backend`,hint:`Relative to the backend root.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),ye(`storeFolder`,n,`Browse storage backends`)]})}),(0,X.jsx)($,{label:`File the download under`,hint:`Leave empty to file it in the same folder(s) as the link. Comma-separate several.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),ye(`action`,n)]})}),(0,X.jsx)($,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,X.jsx)(jp,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:xe?`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:!xe}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The link stays as it is; the download becomes a new file item next to it. Each link is downloaded once per rule. Videos need `,(0,X.jsx)(`span`,{className:`font-mono`,children:`yt-dlp`}),`, pages and websites `,(0,X.jsx)(`span`,{className:`font-mono`,children:`wget`}),` on the server.`]})]}),t.kind===`unstore`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Delete the file from`,children:Ce(t.a,e=>r({a:e}),`pick a backend…`,`workspace:data`)}),(0,X.jsx)($,{label:`…but only once it is also on`,hint:`Safety: the copy is dropped only after another backend holds the file.`,children:Ce(t.b,e=>r({b:e}),`anywhere else`,`workspace:home (optional)`)})]}),(0,X.jsx)(jp,{checked:t.keepLast,onChange:e=>r({keepLast:e}),label:`Never delete the last copy`,hint:`Off means the rule may delete the only remaining copy of a file. Leave it on unless you mean exactly that.`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Deletes the stored bytes on that backend only — copies elsewhere and the item itself are kept.`})]}),t.kind===`sendFile`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsx)($,{label:`Files to send`,children:(0,X.jsxs)(`select`,{className:Ap,value:t.sendSource,onChange:e=>r({sendSource:e.target.value}),children:[(0,X.jsx)(`option`,{value:`document`,children:`The file that triggered this rule`}),(0,X.jsx)(`option`,{value:`attachments`,children:`Matching attachments from the email`}),(0,X.jsx)(`option`,{value:`download`,children:`Files from an earlier Download action`})]})}),t.sendSource===`attachments`&&(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Attachment types`,hint:`application/pdf for invoices; * for all files.`,children:(0,X.jsx)(G,{className:Q,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,X.jsx)($,{label:`Attachment filename contains`,hint:`Optional literal filename fragment.`,children:(0,X.jsx)(G,{className:Q,placeholder:`invoice`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})})]}),t.sendSource===`attachments`&&(0,X.jsx)(jp,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Signature images are excluded by default.`}),(0,X.jsx)($,{label:`Sending account`,hint:`Enable sending for the account in Connected services.`,children:(0,X.jsxs)(`select`,{className:Ap,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,X.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,X.jsxs)(`option`,{value:`${t.sendDriver}:${t.a}`,disabled:!0,children:[t.sendDriver,`: `,t.a,` (unavailable)`]}),A.map(e=>(0,X.jsxs)(`option`,{value:`${e.driver}:${e.address}`,disabled:!e.canSend,children:[e.driver===`imap`?`Email (SMTP)`:e.driver===`whatsapp`?`WhatsApp`:`Slack`,` · `,e.from||e.address,e.canSend?``:` — sending disabled`]},`${e.driver}:${e.address}`))]})}),N&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:N}),(0,X.jsx)($,{label:t.sendDriver===`imap`?`Destination email address`:`Destination conversation`,hint:t.sendDriver===`imap`?`The accounting ingestion address; separate multiple recipients with commas.`:t.sendDriver===`slack`?`A configured Slack channel ID or name. The account needs files:write permission.`:`A configured WhatsApp chat ID, e.g. 421…@s.whatsapp.net or …@g.us.`,children:(0,X.jsx)(G,{className:Q,value:t.b,placeholder:t.sendDriver===`imap`?`invoices@accounting-firm.example`:t.sendDriver===`slack`?`C0123456789`:`421…@s.whatsapp.net`,onChange:e=>r({b:e.target.value})})}),t.sendDriver===`imap`&&(0,X.jsx)($,{label:`Email subject`,hint:`{{file.name}} inserts the attachment filename.`,children:(0,X.jsx)(G,{className:Q,value:t.sendSubject,onChange:e=>r({sendSubject:e.target.value})})}),(0,X.jsx)($,{label:t.sendDriver===`imap`?`Email body (optional)`:`Message / caption (optional)`,hint:`Templates: {{file.name}}, {{doc.data.subject}}, {{doc.data.title}}.`,children:(0,X.jsx)(`textarea`,{className:`min-h-20 w-full rounded-md border bg-background p-3 text-sm`,value:t.sendMessage,onChange:e=>r({sendMessage:e.target.value})})}),(0,X.jsxs)(`div`,{className:`rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`File delivery preview`,children:[t.sendSource===`attachments`?`Each matching email attachment`:t.sendSource===`download`?`Each downloaded file`:`The triggering file`,` → `,t.sendDriver===`imap`?`email attachment`:t.sendDriver===`slack`?`Slack file upload`:`WhatsApp document`,` → `,t.b||`choose a destination`]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Sends each file in a separate message and keeps the original. Maximum 18 MB per file. Replaying this rule does not resend the same file version to the same destination. Unconfirmed deliveries are recorded for review, not retried automatically.`}),t.sendSource===`document`&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`For files created by another automation, enable this rule’s option to also run on automation events.`})]}),t.kind===`notify`&&(0,X.jsx)($,{label:`Notification`,hint:`Notifies you through your bound channel, or in Canvas. Templates: {{doc.data.subject}}, {{doc.data.from}}, {{doc.data.title}}…`,children:(0,X.jsx)(G,{className:Q,placeholder:`New mail from {{doc.data.from}}: {{doc.data.subject}}`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`delete`&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Removes the item from the Canvas index. Files, blobs and mail on storage backends stay untouched.`}),t.kind===`destroy`&&(0,X.jsx)(`p`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive`,children:`⚠ Irreversible: deletes the stored bytes too (blobs, workspace files, mail on the server), then removes the item from the index.`}),t.kind===`agent`&&(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsx)($,{label:`Agent`,hint:`The agent's slug.`,children:(0,X.jsx)(G,{className:W(Q,`font-mono sm:max-w-xs`),placeholder:`assistant`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,X.jsx)($,{label:`Prompt`,hint:`Templates use indexed fields: {{doc.id}}, {{doc.data.subject}}, {{doc.data.bodyPreview}} (emails), {{doc.data.url}}… Ask the agent to use canvas_get for full email content. Objects are inserted as JSON.`,children:(0,X.jsx)(`textarea`,{className:`min-h-28 w-full rounded-md border bg-background p-3 text-sm outline-none focus:ring-2 focus:ring-ring`,placeholder:`Read email #{{doc.id}} in full with canvas_get and summarize it in plain markdown.
|
|
16
|
-
|
|
17
|
-
Subject: {{doc.data.subject}}
|
|
18
|
-
Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})}),c(`reply`)]}),t.kind===`script`&&(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsx)($,{label:`Script`,hint:`From the Scripts section of this workspace.`,children:E.length?(0,X.jsxs)(`select`,{className:W(Ap,`font-mono sm:max-w-md`),value:t.a,onChange:e=>r({a:e.target.value}),children:[(0,X.jsx)(`option`,{value:``,children:`pick a script…`}),E.map(e=>(0,X.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,X.jsx)(G,{className:W(Q,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),c(`output`)]})]},n)}),(0,X.jsxs)(q,{size:`sm`,variant:`outline`,onClick:()=>H(`actions`,[...b.actions,Z(`tag`)]),children:[(0,X.jsx)(L,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,X.jsxs)(`section`,{className:`space-y-3`,children:[(0,X.jsx)(Pp,{step:3,title:`Options`}),(0,X.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,X.jsx)(jp,{checked:b.approval,onChange:e=>H(`approval`,e),label:`Ask me before running`,hint:`Actions are held in the Pending queue for review — approve (optionally amended) or decline — instead of running automatically.`}),(0,X.jsx)(jp,{checked:b.cascade,onChange:e=>H(`cascade`,e),label:`Also react to items created by automation`,hint:`Off by default so rules, hooks and agents cannot trigger each other in a loop. A server-side depth limit still stops runaway chains.`})]})]}),(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,X.jsxs)(q,{className:`h-10 px-5`,onClick:ie,disabled:w||_,children:[w?(0,X.jsx)(ke,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,X.jsx)(p,{className:`mr-1.5 h-4 w-4`}),` `,b.id?`Save changes`:`Create rule`]}),(0,X.jsx)(q,{className:`h-10`,variant:`outline`,onClick:()=>{x(null),c?.()},children:`Cancel`})]})]}),pe&&(0,X.jsx)(Ql,{onClose:()=>me(null),children:(0,X.jsx)(Tl,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:pe.target!==`storeFolder`&&!(pe.target===`condition`&&b?.actions.some(e=>e.kind===`store`)),tabs:pe.target===`condition`?[`context`,`directory`,`backends`]:pe.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:pe.target===`condition`?`Choose source folder…`:pe.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:pe.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:ve,onClose:()=>me(null)})}),!o&&(_?(0,X.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):d.length===0?!S&&!b&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`rounded-xl border border-dashed p-6 text-center`,children:[(0,X.jsx)(`p`,{className:`text-base font-medium`,children:`No rules yet`}),(0,X.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Pick a starting point below, or right-click a folder in the tree and choose “Create rule…”.`})]}),Oe]}):(0,X.jsxs)(`div`,{className:`space-y-6`,children:[we.length>0&&(0,X.jsxs)(`section`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-sm text-muted-foreground`,children:[(0,X.jsxs)(`h3`,{className:`flex items-center gap-2 font-semibold uppercase tracking-wide`,children:[(0,X.jsx)(Xe,{className:`h-4 w-4 shrink-0`}),` Folder & storage rules`]}),(0,X.jsx)(`p`,{children:`Right-click a folder in the tree to add one`})]}),(0,X.jsx)(`div`,{className:`space-y-3`,children:we.map(e=>(0,X.jsx)(De,{rule:e},e.id))})]}),Ee.length>0&&(0,X.jsxs)(`section`,{className:`space-y-3`,children:[we.length>0&&(0,X.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,X.jsx)(nt,{className:`h-4 w-4`}),` Other rules`]}),(0,X.jsx)(`div`,{className:`space-y-3`,children:Ee.map(e=>(0,X.jsx)(De,{rule:e},e.id))})]})]}))]})}function Lp({workspaceId:e,document:t,onClose:n}){let[r,i]=(0,J.useState)(null),[a,o]=(0,J.useState)(``),[s,c]=(0,J.useState)(``);_c(n),(0,J.useEffect)(()=>{let n=!1;return(async()=>{if(!Nf(await dn(e)))throw Error(`Only workspace administrators can create rules.`);let r=await Dn(e,t.id);n||i(r)})().catch(e=>{n||o(e instanceof Error?e.message:`Could not load document`)}),()=>{n=!0}},[e,t.id]);let l=(0,J.useMemo)(()=>r?Lf(r):[],[r]),u=l.find(e=>e.id===s)||l[0],d=(0,J.useMemo)(()=>u?{kind:`document`,rule:u.rule}:null,[u]);return(0,X.jsx)(Rf,{label:`Create rule`,onClose:n,children:(0,X.jsxs)(`div`,{className:`p-5`,children:[(0,X.jsxs)(`div`,{className:`mb-4 flex items-start justify-between gap-3`,children:[(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsx)(`h2`,{id:`document-rule-title`,className:`text-lg font-semibold`,children:`Create rule`}),(0,X.jsx)(`p`,{className:`truncate text-sm text-muted-foreground`,children:At(t).title})]}),(0,X.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`rounded-md p-2 hover:bg-accent`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),a?(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}):r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`label`,{className:`mb-4 block space-y-2 text-sm font-medium`,children:[(0,X.jsx)(`span`,{children:`Start with`}),(0,X.jsx)(`select`,{className:`h-10 w-full rounded-md border bg-background px-3`,value:u?.id,onChange:e=>c(e.target.value),children:l.map(e=>(0,X.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,X.jsx)(Ip,{workspaceId:e,prefill:d,createOnly:!0,onCreated:n,onCancel:n})]}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading document…`})]})})}function Rp(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 zp(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 Bp(e,t,n,r){let i=new Set(r?n:[]);for(let n of t)zp(e,n.bounds)&&i.add(n.id);return i}var Vp=`[data-document-id], button, a, input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="dialog"], [role="menu"], [draggable="true"], thead, [data-selection-ignore]`;function Hp(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=Rp(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(Bp(n,o,r.initial,r.additive))},p=(e,t,n)=>{let r=Math.min(40,n/4);return e<t+r?-18*Math.min(1,(t+r-e)/r):e>t+n-r?18*Math.min(1,(e-t-n+r)/r):0},m=t=>{if(!r?.active)return;let i=u(),c=o?Math.min(2,(t-o)/(1e3/60)):1;o=t;let{scrollTop:l,scrollLeft:d}=e;e.scrollTop+=p(r.client.y,i.top,i.height)*c,e.scrollLeft+=p(r.client.x,i.left,i.width)*c,(s||e.scrollTop!==l||e.scrollLeft!==d)&&(f(),s=!1),a=n.requestAnimationFrame(m)},h=(s=!1)=>{if(!r)return;let u=r;r=null,n.cancelAnimationFrame(a),a=0,o=0,i?.remove(),i=null,u.active&&(e.style.userSelect=l,c=!0,s&&t.onSelectionChange(u.initial)),e.hasPointerCapture(u.pointerId)&&e.releasePointerCapture(u.pointerId)},g=n=>{if(c=!1,r||n.button!==0||!n.isPrimary||n.pointerType===`touch`)return;let i=n.target;if(!e.contains(i)||i.closest(Vp))return;let a=u();if(n.clientX<a.left||n.clientX>=a.left+a.width||n.clientY<a.top||n.clientY>=a.top+a.height)return;let o={x:n.clientX,y:n.clientY};r={pointerId:n.pointerId,start:d(o),clientStart:o,client:o,initial:new Set(t.getSelection()),additive:n.ctrlKey||n.metaKey||n.shiftKey,active:!1},n.preventDefault(),e.focus({preventScroll:!0}),e.setPointerCapture(n.pointerId)},_=t=>{if(!(!r||t.pointerId!==r.pointerId)){if(!(t.buttons&1)){h();return}if(r.client={x:t.clientX,y:t.clientY},!r.active){if(Math.hypot(t.clientX-r.clientStart.x,t.clientY-r.clientStart.y)<4)return;r.active=!0,l=e.style.userSelect,e.style.userSelect=`none`,n.getSelection()?.removeAllRanges(),i=e.ownerDocument.createElement(`div`),i.setAttribute(`aria-hidden`,`true`),i.dataset.selectionRectangle=``,i.className=`pointer-events-none absolute z-20 border border-info bg-info/15`,e.append(i),a=n.requestAnimationFrame(m)}s=!0,t.preventDefault()}},v=e=>{!r||e.pointerId!==r.pointerId||(r.client={x:e.clientX,y:e.clientY},r.active?f():r.additive||t.onSelectionChange(new Set),h())},y=()=>h(!0),b=e=>{e.pointerId===r?.pointerId&&y()},x=e=>{r&&e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),y())},S=e=>{c&&(c=!1,e.preventDefault(),e.stopImmediatePropagation())},C=()=>{s=!0};return e.addEventListener(`pointerdown`,g),e.addEventListener(`pointermove`,_),e.addEventListener(`pointerup`,v),e.addEventListener(`pointercancel`,b),e.addEventListener(`lostpointercapture`,b),e.addEventListener(`click`,S,!0),e.addEventListener(`scroll`,C,!0),n.addEventListener(`keydown`,x,!0),n.addEventListener(`blur`,y),()=>{h(),e.removeEventListener(`pointerdown`,g),e.removeEventListener(`pointermove`,_),e.removeEventListener(`pointerup`,v),e.removeEventListener(`pointercancel`,b),e.removeEventListener(`lostpointercapture`,b),e.removeEventListener(`click`,S,!0),e.removeEventListener(`scroll`,C,!0),n.removeEventListener(`keydown`,x,!0),n.removeEventListener(`blur`,y)}}function Up({scope:e,selected:t,onSelectionChange:n,onContextMenu:r,children:i}){let a=(0,J.useRef)(null),o=(0,J.useRef)({selected:t,onSelectionChange:n});return(0,J.useLayoutEffect)(()=>{o.current={selected:t,onSelectionChange:n}},[t,n]),(0,J.useLayoutEffect)(()=>{if(a.current)return Hp(a.current,{getSelection:()=>o.current.selected,onSelectionChange:e=>o.current.onSelectionChange(e)})},[e]),(0,X.jsx)(`div`,{ref:a,tabIndex:-1,"data-document-selection-area":``,onContextMenu:r,className:`relative isolate min-h-0 min-w-0 flex-1 overflow-auto p-2 outline-none`,children:i})}function Wp(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 Gp({workspaceId:e,ids:t,onClose:n,modal:r=!1}){let{showProgress:i}=St();_c(n,r);let[a]=(0,J.useState)(()=>{try{return Wp(e)}catch{return``}}),[o,s]=(0,J.useState)(()=>{try{let e=JSON.parse(localStorage.getItem(a)||`null`);return e&&Array.isArray(e.ids)&&e.target&&e.index<e.ids.length?e:null}catch{return null}}),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(``),f=(0,J.useRef)(!1),p=(0,J.useRef)(!1);(0,J.useEffect)(()=>(f.current=!1,()=>{f.current=!0}),[]);let m=e=>{try{e.index>=e.ids.length?localStorage.removeItem(a):localStorage.setItem(a,JSON.stringify(e))}catch{}f.current||s(e)},h=async t=>{if(p.current)return;p.current=!0,l(!0),d(``);let n=t,r=()=>`${n.index} / ${n.ids.length} document(s) → ${n.target.workspaceName}`,a=i({title:`Copying to workspace…`,description:r()});m(n);try{for(;n.index<n.ids.length&&!f.current;){if(!navigator.onLine)throw Error(`Offline. Your copy is saved; resume when connected.`);await gn(e,n.ids[n.index],{destination:n.target.workspaceName,context:n.paths,treeType:n.target.treeType,treeNameOrTreeId:n.target.treeName,operationId:`${n.id}:${n.index}`}),n={...n,index:n.index+1},m(n),a.update({title:`Copying to workspace…`,description:r()})}a.done({title:n.index>=n.ids.length?`Copy complete`:`Copy paused`,description:r()}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}catch(e){a.fail({title:`Copy incomplete`,description:`${r()}. ${e instanceof Error?e.message:`Copy failed`}`,variant:`destructive`}),f.current||d(`Document ${n.ids[n.index]}: ${e instanceof Error?e.message:`Copy failed`}. Resume to retry.`)}finally{p.current=!1,f.current||l(!1)}},g=()=>{f.current=!0,n()},_=o!=null&&o.index>=o.ids.length,v=r?`h-full min-h-0 w-full`:Zl,y=(0,X.jsx)(X.Fragment,{children:o?(0,X.jsxs)(`section`,{role:`dialog`,"aria-label":`Copy to workspace`,className:`${v} flex flex-col rounded-(--panel-radius) border bg-card p-4 shadow-elevation-4`,children:[(0,X.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,X.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[o.target.workspaceName,`: `,o.paths.join(`, `)]}),(0,X.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[o.index,` of `,o.ids.length,` copied`,_?`.`:c?`…`:` — paused.`]}),u&&(0,X.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:u}),(0,X.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:`Files go to workspace:data. Destination rules handle storage placement. Relationships and sharing permissions are not copied. Source documents stay unchanged.`}),!_&&(0,X.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Closing lets the current item finish and pauses the rest. Reopen Copy to workspace to resume, including after reconnecting.`}),(0,X.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!_&&!c&&(0,X.jsx)(q,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(a)}catch{}s(null),d(``)},children:`Discard remaining`}),!_&&!c&&(0,X.jsx)(q,{onClick:()=>void h(o),children:`Resume copy`}),(0,X.jsx)(q,{variant:_?`default`:`outline`,onClick:g,children:_?`Done`:c?`Pause & close`:`Close`})]})]}):(0,X.jsx)(Tl,{title:`Copy to workspace…`,confirmLabel:`Copy documents`,excludeWorkspace:e,documentCount:t.length,sizeClassName:v,onClose:g,onConfirm:(e,n)=>h({ids:t,target:n,paths:e,index:0,id:crypto.randomUUID()})})});return r?(0,X.jsx)(Rf,{label:`Copy to workspace`,onClose:g,children:y}):(0,X.jsx)(Ql,{onClose:g,children:y})}function Kp(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...Kn(e.data?.tags??[]),...Kn(t)])]}:{},...n?{geo:n}:{}}}function qp(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:Kp(e,t,n),...r===void 0?{}:{comment:r.trim()}}}function Jp({workspaceId:e,documentIds:t,onClose:n}){let[r,i]=(0,J.useState)([]),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(`keep`),[l,u]=(0,J.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,J.useState)(t),[m,h]=(0,J.useState)(!1),[g,_]=(0,J.useState)(``);return _c(n,!m),(0,po.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-scrim p-4`,children:(0,X.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`bulk-edit-title`,className:`max-h-viewport-modal overflow-y-auto w-full max-w-md space-y-4 rounded-(--panel-radius) border bg-background p-5 shadow-elevation-4`,children:[(0,X.jsxs)(`h2`,{id:`bulk-edit-title`,className:`font-semibold`,children:[`Bulk Edit · `,f.length,` documents`]}),(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Add tags to all selected documents. Choosing a location replaces their existing geotags; leaving it unset keeps them.`}),(0,X.jsxs)(`fieldset`,{disabled:m,className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)(`span`,{className:`text-sm font-medium`,children:`Add tags`}),(0,X.jsx)(iu,{tags:r,onChange:i,suggestions:[]})]}),(0,X.jsx)(mu,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,X.jsxs)(`select`,{id:`bulk-comment-mode`,value:s,onChange:e=>c(e.target.value),className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm`,children:[(0,X.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,X.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,X.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,X.jsx)(`textarea`,{id:`bulk-comment`,rows:3,value:l,onChange:e=>u(e.target.value),placeholder:`Comment for all selected documents…`,className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,X.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,X.jsx)(q,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,X.jsx)(q,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await Dn(e,n);await qt(e,qp(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 Yp=e=>`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`;function Xp(e,t,n,r){return typeof e.sourcePath==`string`&&!!t&&e.sourceWorkspaceId===t&&!!n&&e.sourceTreeName===n&&Yp(e.sourcePath)===Yp(r)}function Zp({onClose:e,onConfirm:t,fixedWorkspaceName:n,saving:r=!1,sizeClassName:i}){let[a,o]=(0,J.useState)(n?`browse`:`workspace`),[s,c]=(0,J.useState)([]),[l,u]=(0,J.useState)(!n),[d,f]=(0,J.useState)(n??null),[p,m]=(0,J.useState)(`context`),[h,g]=(0,J.useState)(new Set),[_,v]=(0,J.useState)(n);return n!==_&&(v(n),n||u(!0)),(0,J.useEffect)(()=>{n||jt().then(c).catch(()=>c([])).finally(()=>u(!1))},[n]),(0,X.jsxs)(`div`,{className:W(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,i||`h-viewport-card max-h-full w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(Je,{className:`h-4 w-4`}),a===`workspace`?`Add existing documents…`:`Pick documents…`]}),(0,X.jsx)(`button`,{type:`button`,onClick:e,disabled:r,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,X.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-normal`,style:{transform:a===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,X.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,X.jsx)(Cl,{workspaces:s,loading:l,onPick:e=>{f(e),g(new Set),o(`browse`)}})}),(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:[!n&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>o(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,X.jsx)(gt,{className:`h-4 w-4 rotate-180`})}),[`context`,`directory`].map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>{m(e),g(new Set)},className:W(`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:[hl[e],gl[e]]},e))]}),d&&(0,X.jsx)(wl,{workspaceName:d,treeTab:p,onTreeTabChange:m,selectedDocIds:h,onToggleDoc:e=>{g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onNavigate:()=>g(new Set)})]})]})}),a===`browse`&&(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,X.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[h.size,` document`,h.size===1?``:`s`,` selected`]}),(0,X.jsx)(q,{size:`sm`,onClick:async()=>{!d||h.size===0||r||await t(Array.from(h),{workspaceName:d,treeName:p===`directory`?`directory`:kn,treeType:p})},disabled:h.size===0||r,children:r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(_o,{className:`mr-1.5 h-3.5 w-3.5`}),`Adding…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Je,{className:`mr-1 h-3.5 w-3.5`}),`Add`]})})]})]})}var Qp=a();function $p(e){let{id:t,...n}=e;return n}var em=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`div`,{className:`relative w-full overflow-auto`,children:(0,X.jsx)(`table`,{ref:n,className:W(`w-full caption-bottom text-sm`,e),...t})}));em.displayName=`Table`;var tm=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`thead`,{ref:n,className:W(`[&_tr]:border-b`,e),...t}));tm.displayName=`TableHeader`;var nm=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`tbody`,{ref:n,className:W(`[&_tr:last-child]:border-0`,e),...t}));nm.displayName=`TableBody`;var rm=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`tfoot`,{ref:n,className:W(`border-t bg-muted/50 font-medium [&>tr]:last:border-b-0`,e),...t}));rm.displayName=`TableFooter`;var im=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`tr`,{ref:n,className:W(`border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted`,e),...t}));im.displayName=`TableRow`;var am=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`th`,{ref:n,className:W(`h-12 px-2 md:px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0`,e),...t}));am.displayName=`TableHead`;var om=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`td`,{ref:n,className:W(`p-2 md:p-4 align-middle [&:has([role=checkbox])]:pr-0`,e),...t}));om.displayName=`TableCell`;var sm=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`caption`,{ref:n,className:W(`mt-4 text-sm text-muted-foreground`,e),...t}));sm.displayName=`TableCaption`;var cm=({label:e,sortKey:t,sort:n,onSort:r,className:i})=>{let a=n.key===t;return(0,X.jsx)(am,{"aria-sort":a?n.dir===`asc`?`ascending`:`descending`:`none`,className:W(`cursor-pointer select-none hover:text-foreground transition-colors`,i),onClick:()=>r(t),children:(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,a?n.dir===`asc`?(0,X.jsx)(Le,{className:`h-3.5 w-3.5`}):(0,X.jsx)(Oe,{className:`h-3.5 w-3.5`}):(0,X.jsx)(T,{className:`h-3.5 w-3.5 opacity-40`})]})})};cm.displayName=`SortableTableHead`;function lm(e,t,n={key:null,dir:`asc`}){let[r,i]=J.useState(n);return{sorted:J.useMemo(()=>{let n=r.key?t[r.key]:null;if(!n)return e;let i=r.dir===`asc`?1:-1;return[...e].sort((e,t)=>{let r=n(e)??``,a=n(t)??``;return typeof r==`number`&&typeof a==`number`?(r-a)*i:String(r).localeCompare(String(a),void 0,{numeric:!0})*i})},[e,r,t]),sort:r,toggleSort:J.useCallback(e=>{i(t=>t.key===e?{key:e,dir:t.dir===`asc`?`desc`:`asc`}:{key:e,dir:`asc`})},[])}}var um=`canvas:documentOpenMode`;function dm(){try{return localStorage.getItem(um)===`modal`?`modal`:`side`}catch{return`side`}}var fm=dm(),pm=new Set;function mm(){return fm}function hm(e){try{localStorage.setItem(um,e)}catch{}fm=e;for(let e of pm)e()}function gm(e){pm.add(e);let t=t=>{(t.key===um||t.key===null)&&(fm=dm(),e())};return window.addEventListener(`storage`,t),()=>{pm.delete(e),window.removeEventListener(`storage`,t)}}function _m(){return(0,J.useSyncExternalStore)(gm,mm,()=>`side`)}function vm(e){let t=_m(),n=(0,J.useContext)(td),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=(t===`side`||n?.alwaysOn===!0)&&!!n&&!!i&&!s&&!c;return(0,J.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,X.jsx)(ym,{...e})}function ym({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,J.useState)(!1),c=nr(),{document:l,refresh:u}=jd(r,e);if(_c(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,po.createPortal)((0,X.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:W(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,X.jsxs)(`div`,{className:W(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-(--panel-radius) md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-(--panel-radius)`),onClick:e=>e.stopPropagation(),children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:At(l).title}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=Ft(l);return e?(0,X.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,X.jsx)(je,{className:`h-4 w-4`})}):null})(),(0,X.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,X.jsx)(ve,{className:`h-4 w-4`}):(0,X.jsx)(Qe,{className:`h-4 w-4`})}),(0,X.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,X.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,X.jsx)(as.Provider,{value:()=>s(e=>!e),children:(0,X.jsx)(Ad,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var bm={sortBy:`content`,order:`desc`};function xm(e){return e?.sortBy===`crud:deleted`?{...bm}:{sortBy:e?.sortBy??bm.sortBy,order:e?.order??bm.order}}var Sm={features:{allOf:[],anyOf:[],noneOf:[]},timeline:{quickFilter:null,customRanges:[],indexCreated:!0,indexUpdated:!0,indexDeleted:!1,contentEvents:!1,selectedTimelines:[]},geo:{bbox:null,includeUnlocated:!1},lens:{gps:null,ids:null},sort:{...bm}};function Cm(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function wm(e,t=!1){if(!e.gps)return[];let{lat:n,lon:r,radiusM:i}=e.gps;return[`geo:near:${n},${r},${Math.max(1,Math.round(i))}m`,...t?[`geo:missing`]:[]]}function Tm(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function Em(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Tm(e),c=s.length>0?s.map(e=>`${e.start}..${e.end}`):t?[t]:[];if(c.length===0)return[];let l=[];return n&&l.push(`crud:created`),r&&l.push(`crud:updated`),i&&l.push(`crud:deleted`),a&&l.push(`content`),l.push(...o),l.flatMap(e=>c.map(t=>`t:${e}:${t}`))}function Dm(e,t,n=[]){return{features:e.features,filters:[...Em(e.timeline),...Cm(e.geo),...wm(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 Om=bm,km={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function Am(e){return km[e]??e}function jm(e){let[t,n]=(0,J.useState)([]);return(0,J.useEffect)(()=>{let t=!1;return Ut(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,J.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:Am(e)})),[t])}function Mm({workspaceId:e,value:t,onChange:n}){let r=jm(e);return(0,X.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,X.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value,order:[`alphabetical`,`type`].includes(e.target.value)?`asc`:t.order}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by`,"aria-label":`Sort by`,children:[t.sortBy!==`crud:deleted`&&!r.some(e=>e.value===t.sortBy)&&(0,X.jsx)(`option`,{value:t.sortBy,children:Am(t.sortBy)}),r.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending`:`Descending`,"aria-label":t.order===`asc`?`Ascending`:`Descending`,className:`flex h-7 w-7 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent hover:text-foreground touch-target`,children:t.order===`asc`?(0,X.jsx)(Ce,{className:`h-3.5 w-3.5`}):(0,X.jsx)(U,{className:`h-3.5 w-3.5`})})]})}function Nm(e,t){let n=t?.replace(/^t:/,``)||`crud:created`,r=(n===`crud:created`?[e.createdAt]:n===`crud:updated`?[e.updatedAt]:(e.timelines??[]).filter(e=>(e.timeline||e.name)===n).map(e=>e.start)).map(e=>Date.parse(e??``)).filter(Number.isFinite);if(r.length)return Math.min(...r);let i=n===`content`?Date.parse(e.createdAt??``):NaN;return Number.isFinite(i)?i:null}var Pm={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},Fm=e=>e*1e6;function Im(){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 Lm(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Rm(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=Lm(e);return r.setDate(r.getDate()-n),r}var zm=864e5;function Bm(e){let t=Im(),n=Lm(e),r=Rm(e,t);return{today:n.getTime(),yesterday:n.getTime()-zm,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*zm,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function Vm(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:Fm(Pm.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:Fm(Pm.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:Fm(Pm.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:Fm(Pm.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:Fm(Pm.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:Fm(Pm.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:Fm(Pm.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:Fm(Pm.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:Fm(Pm.year)+i}}function Hm(e,t,n=`desc`,r=new Date){let i=Bm(r),a=new Map;for(let n of e){let e=Vm(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 Um(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 Wm(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function Gm(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 Km=(e,t)=>`${vt.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function qm(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await K.get(`${Km(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 Jm(e,t,n){return Xm(e,t,n,`restore`)}function Ym(e,t,n){return Xm(e,t,n,`discard`)}async function Xm(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await K.post(`${Km(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{rn(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 Zm(e,t){let n=Um(`backends`,t);if(!n?.backend)return;let{items:r}=await qm(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 Jm(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 Qm(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 $m(e,t){let n=Um(`backends`,t);if(!n?.backend)return;let{items:r}=await qm(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Qm(n.backend,i))return;let a=await Ym(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 eh(){let{showProgress:e}=St();return(0,J.useCallback)(async(t,n,r,i)=>{let a=e({title:t,description:n});try{let e=await i();if(e===!1)throw Error(`The operation could not be completed.`);return a.done({title:r,description:n}),e}catch(e){throw a.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}},[e])}var th=new Map;function nh(e,t,n,r,i,a){let o=JSON.stringify([t,n,r,a]),s=th.get(o);if(s)return s;let c=(async()=>{let o=e({title:`Resyncing…`,description:r});try{for(a?await nn(t,n,r,a):await mn(t,n,r);;){let e=await Mt(t,n,r);i?.(e);let s=a?e.containers?.find(e=>e.name===a):void 0;if(a?s?.status!==`syncing`:!e.resyncing&&e.status!==`syncing`){let i=s?s.lastError:e.lastError;if(i)throw Error(i);o.done({title:e.resyncCancelledAt?`Resync stopped`:`Resync complete`,description:`${r}${n!==`imap`&&e.progress?` · ${e.progress.scanned} files scanned`:``}`}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t,treeName:`backends`}}));return}let c=n===`imap`?void 0:e.progress;o.update({title:`Resyncing…`,description:`${r}${c?` · ${c.scanned}${c.total==null?``:` / ${c.total}`} files scanned`:``}`}),await new Promise(e=>setTimeout(e,2e3))}}catch(e){throw o.fail({title:`Resync needs attention`,description:`${r}: ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return th.set(o,c),c.finally(()=>{th.get(o)===c&&th.delete(o)}).catch(()=>{}),c}var rh=[`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`],ih=new Map;function ah(e,t,n){rn(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 oh(e,t){let n=ih.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=rh.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)rn(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return go.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)rn(e,t);a.forEach(([e,t])=>go.off(e,t))}},ih.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),ih.delete(e))}}function sh({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=eh(),{showProgress:a}=St(),o=n||`context`,c=o===`directory`,[l,u]=(0,J.useState)([]);(0,J.useEffect)(()=>{let e=!1,n=()=>{t&&of(t).then(t=>{e||u(t)}).catch(()=>{})};return n(),window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[t,o]);let d=(0,J.useCallback)(e=>{if(o===`backends`)return[e];let t=`${c?`dir`:`ctx`}:${e}`;return[...new Set(l.filter(e=>e.enabled!==!1).flatMap(e=>{let n=e.when.pathExact||e.when.path,r=(Array.isArray(n)?n:[n]).filter(e=>typeof e==`string`&&e.startsWith(`backends:`));return e.then.flatMap(e=>e.action!==`link`||!Array.isArray(e.paths)?[]:e.paths.flatMap(n=>{if(typeof n!=`string`)return[];let i=n===t?``:e.recursive&&t.startsWith(n+`/`)?t.slice(n.length):null;return i===null?[]:r.map(e=>e.slice(9)+i)}))}))]},[l,o,c]),f=(0,J.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),p=(0,J.useCallback)(async(n,r=!0)=>{let i;if(e)i=await sr(e,n,r);else if(t)i=await hn(t,n,r,o);else return!1;let a=Kc(n);if(i&&a)try{e?await tr(e,n,a):t&&await Dt(t,n,a,o)}catch{}return f(),i},[e,t,o,f]),m=(0,J.useCallback)(async(n,r=!1,a=!1,s=!1)=>i(s?`Destroying…`:a?`Purging…`:`Removing…`,n,s?`Destroyed`:a?`Purged`:`Removed`,async()=>{try{return e?await er(e,n,r):t?await un(t,n,r,o,a,s):!1}finally{f()}}),[e,t,o,f,i]),h=(0,J.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await $n(e,n,t.join(`/`),!1)}else if(t)i=await Dt(t,n,{name:r},o);else return!1;return f(),i},[e,t,o,f]),g=(0,J.useCallback)(async(n,r,a=!1,s=o,c=o,l={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await $n(e,n,r,a,l);else if(t)i=await Et(t,n,r,a,s,c,l);else return!1;return f(),i}),[e,t,o,f,i]),_=(0,J.useCallback)(async n=>{let r;if(e)r=await rr(e,n);else if(t)r=await Vt(t,n,o);else return null;return f(),r},[e,t,o,f]),v=(0,J.useCallback)(async n=>{let r;if(e)r=await Qn(e,n);else if(t)r=await Cn(t,n,o);else return null;return f(),r},[e,t,o,f]),y=(0,J.useCallback)(async(n,r,a=!1,s=o,c=o)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await ar(e,n,r,a);else if(t)i=await pn(t,n,r,a,s,c);else return!1;return f(),i}),[e,t,o,f,i]),b=(0,J.useCallback)(async(n,r)=>e?await tr(e,n,r):t?await Dt(t,n,r,o):!1,[e,t,o]),x=(0,J.useCallback)(async(n,r)=>{let i;if(e)i=await cr(e,n,r);else if(t)i=await Gt(t,n,r,o);else return null;return f(),i},[e,t,o,f]),S=(0,J.useCallback)(async(n,r)=>{let i;if(e)i=await ir(e,n,r);else if(t)i=await _n(t,n,r,o);else return null;return f(),i},[e,t,o,f]),C=(0,J.useCallback)(async e=>{if(!t)return!1;let n=await It(t,e,t,o);return f(300),n},[t,o,f]),w=(0,J.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 f(300),!0},[t,o,f]),T=(0,J.useCallback)(async e=>{if(!t)return!1;let n=await wt(t,e,o);return f(),n},[t,o,f]),E=(0,J.useCallback)(async e=>{if(!t)return!1;let n=await Pn(t).catch(()=>[]),r=d(e);for(let e of r){let r=On(e,n);if(!r)continue;let i=n.find(e=>e.driver===r.driver&&e.address===r.address),o=r.driver===`imap`?i?.containers?.find(t=>t.treePath===e):void 0;if(r.driver===`imap`&&e!==i?.treePath&&!o)throw Error(`Select a subscribed mailbox folder to refresh`);await nh(a,t,r.driver,r.address,void 0,o?.name)}return f(300),r.length>0},[t,f,a,d]),D=(0,J.useCallback)(async(e,n)=>{if(!t)return!1;let r=await Pn(t).catch(()=>[]),i=cn(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await an(t,i.driver,i.address,[a]),f(200),!0},[t,f]),O=(0,J.useCallback)(async(e,n)=>{if(!t)return!1;let r=await Pn(t).catch(()=>[]),i=cn(e,r);return!i||!i.key?!1:(await An(t,i.driver,i.address,i.key,n),f(200),!0)},[t,f]),k=(0,J.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await Pn(t),r=jn(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await en(t,r.driver,r.address,r.key),!0}finally{f(200)}}):!1,[t,f,i]),A=(0,J.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await s(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-DRz8kLqY.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([30,3,4,10,11,13,12,14]));r({mode:e,path:n,workspaceId:t,treeName:o,onImported:()=>{ah(t,o),f()}})},[t,o,f]),j=(0,J.useCallback)(async(e,n)=>{if(!t)return;let r=await s(()=>Promise.resolve().then(()=>lh),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await fn(t,n,e,o,sn(o))).length!==e.length)throw Error(`Some documents could not be imported`);return ah(t,o),f(),!0});else{let e=[];for(let r=0;;){let i=await on(t,n,[],{treeName:o,treeType:sn(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,f]);return{onImportDocuments:t&&o!==`backends`?e=>j(`import`,e):void 0,onExportDocuments:t?e=>j(`export`,e):void 0,onInsertPath:p,onRemovePath:m,onRenamePath:h,onMovePath:g,onCopyPath:y,onExportSubtree:t?e=>A(`export`,e):void 0,onImportSubtree:t&&o!==`backends`?e=>A(`import`,e):void 0,onUpdateNode:b,onMergeLayer:x,onSubtractLayer:S,onMergeDown:c?void 0:_,onSubtractDown:c?void 0:v,onLockLayer:t?C:void 0,onUnlockLayer:t?w:void 0,onDestroyLayer:t&&!c?T:void 0,canResyncBackend:e=>d(e).length>0,onResyncBackend:t?E:void 0,onCreateBackendFolder:t?D:void 0,onRenameBackendFolder:t?O:void 0,onDeleteBackendFolder:t?k:void 0}}function ch({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let u=Li(),d=sh({workspaceId:n,treeName:r}),p=r===`backends`,m=p?cn(i):null,[h,g]=(0,J.useState)([]);(0,J.useEffect)(()=>{if(!p)return;let e=!1;return Pn(n).then(t=>{e||g(t)}).catch(()=>{}),()=>{e=!0}},[n,p]);let _=p?jn(i,h):null,y=i.split(`/`).filter(Boolean).pop()||i,[b,x]=(0,J.useState)(void 0);(0,J.useEffect)(()=>{let e=!1;return xn(n).then(t=>{e||x(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||x(null)}),()=>{e=!0}},[n,r,i]);let S=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},C=(e,t,n,r=!1)=>(0,X.jsxs)(`button`,{type:`button`,className:W(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>S(n),children:[e,t]}),w=(0,X.jsx)(`div`,{className:`my-1 h-px bg-border`}),T=e=>{let t=p?(()=>{let t=tf(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:rf(i)};u(`/workspaces/${n}/settings/hooks?${nf(t).toString()}`)},D=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},O=Um(r,i);return O?(0,X.jsxs)(vc,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,X.jsx)(he,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),O.backend&&C((0,X.jsx)(ce,{className:`h-3 w-3`}),`Restore original paths`,()=>Zm(n,i)),O.backend&&C((0,X.jsx)(he,{className:`h-3 w-3`}),`Empty Trash`,()=>$m(n,i),!0)]}):(0,X.jsxs)(vc,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,X.jsx)(ge,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&C((0,X.jsx)(st,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),w,p?m&&(0,X.jsxs)(X.Fragment,{children:[C((0,X.jsx)(L,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=D(`New folder name:`);e&&await d.onCreateBackendFolder?.(i,e)}),m.key&&C((0,X.jsx)(_t,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=D(`New folder name:`,y);e&&await d.onRenameBackendFolder?.(i,e)}),C((0,X.jsx)(B,{className:`w-3 h-3`}),`Create storage rule…`,()=>T(`store`))]}):(0,X.jsxs)(X.Fragment,{children:[C((0,X.jsx)(L,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=D(`New folder name:`);e&&await d.onInsertPath(`${i===`/`?``:i}/${e}`)}),C((0,X.jsx)(_t,{className:`w-3 h-3`}),`Rename`,async()=>{let e=D(`New name:`,y);e&&await d.onRenamePath(i,e)}),C((0,X.jsx)(B,{className:`w-3 h-3`}),`Create rule…`,()=>T(`store`)),C((0,X.jsx)(Ne,{className:`w-3 h-3`}),`Create download rule…`,()=>T(`download`))]}),b!==void 0&&C(b?(0,X.jsx)(E,{className:`w-3 h-3`}):(0,X.jsx)(v,{className:`w-3 h-3`}),b?`Unpin`:`Pin`,async()=>{b?await Kt(n,b.id):await Jt(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),w,d.onImportDocuments&&C((0,X.jsx)(L,{className:`w-3 h-3`}),`Import documents…`,()=>d.onImportDocuments(i)),d.onExportDocuments&&C((0,X.jsx)(Ne,{className:`w-3 h-3`}),`Export documents…`,()=>d.onExportDocuments(i)),C((0,X.jsx)(f,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!p&&l&&c&&c.length>0&&C((0,X.jsx)(te,{className:`w-3 h-3`}),`Paste ${c.length} document(s)`,()=>l(i,c)),p?_&&(0,X.jsxs)(X.Fragment,{children:[w,C((0,X.jsx)(he,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${y}" and its contents from the backend?`)&&await d.onDeleteBackendFolder?.(i)},!0)]}):(0,X.jsxs)(X.Fragment,{children:[w,C((0,X.jsx)(he,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await d.onRemovePath(i,!0)},!0)]})]})}var lh=t({DocumentList:()=>Fh,default:()=>Fh,showDocumentExport:()=>Lh,showDocumentImport:()=>Ih});function uh({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,J.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map($p),l=JSON.stringify(c,null,2),u=async()=>{try{await navigator.clipboard.writeText(l),a(`copied`),setTimeout(()=>a(`idle`),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e),a(`error`),setTimeout(()=>a(`idle`),2e3)}};return(0,X.jsx)(Rf,{label:`Export Documents`,onClose:o,children:(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,X.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,X.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,X.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,X.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,X.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,X.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,X.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,X.jsxs)(q,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,X.jsx)(f,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,X.jsx)(`textarea`,{className:`w-full min-h-24 flex-1 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&u()}},onFocus:e=>e.target.select()})]})}),(0,X.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-end gap-2`,children:[(0,X.jsx)(q,{variant:`outline`,onClick:()=>{let e=URL.createObjectURL(new Blob([l],{type:`application/json`})),t=window.document.createElement(`a`);t.href=e,t.download=`canvas-documents.json`,t.click(),setTimeout(()=>URL.revokeObjectURL(e),1e3)},children:`Download JSON`}),(0,X.jsx)(q,{onClick:o,children:`Close`})]})]})})}function dh({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,J.useState)(``),[a,o]=(0,J.useState)(!1),[s,c]=(0,J.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e||typeof e!=`object`||!e.schema||!e.data){c(`Each document must have "schema" and "data" fields`);return}o(!0),await n(a)?(i(``),t()):c(`Failed to import documents`)}catch(e){c(e instanceof Error?e.message:`Import failed`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,po.createPortal)((0,X.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,X.jsx)(`div`,{className:`bg-background border rounded-(--panel-radius) max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,X.jsxs)(`div`,{className:`p-6`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,X.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data or choose a document export file`})]}),(0,X.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,X.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),className:`w-full h-64 p-3 border rounded-lg font-mono text-sm`,placeholder:`[{"schema": "data/schema/tab", "schemaVersion": "2.0", "data": {...}, "metadata": {...}}]`,disabled:a,autoFocus:!0})]}),s&&(0,X.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,X.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,X.jsxs)(`p`,{children:[(0,X.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,X.jsxs)(`p`,{children:[(0,X.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,X.jsxs)(`label`,{className:`mt-4 block text-sm`,children:[`Import JSON file`,(0,X.jsx)(`input`,{type:`file`,accept:`.json,application/json`,disabled:a,className:`mt-2 block w-full text-sm`,onChange:e=>{let t=e.target.files?.[0];t&&t.text().then(e=>{i(e),c(null)}).catch(e=>c(String(e)))}})]}),(0,X.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,X.jsx)(q,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,X.jsx)(q,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function fh({document:e}){let{replicating:t,label:n}=bn(e);return t?(0,X.jsxs)(`span`,{role:`status`,className:`inline-flex shrink-0 items-center gap-1 rounded-full border bg-muted/60 px-2 py-0.5 text-[11px] font-normal text-muted-foreground`,children:[(0,X.jsx)(ke,{className:`h-3 w-3 animate-spin`}),n]}):null}function ph(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Dc(e.currentTarget,`inside`)}function mh({documentId:e,onOpenActions:t,className:n}){return t?(0,X.jsx)(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),t(n.currentTarget,e)},className:`rounded-sm p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground ${n??``}`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,X.jsx)(Ie,{className:`h-4 w-4`})}):null}function hh(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function gh({document:e}){let t=Ft(e);return t?(0,X.jsx)(`a`,{href:t,target:`_blank`,rel:`noopener noreferrer`,title:`Open original in browser`,"aria-label":`Open original in browser`,className:`shrink-0 rounded p-1 text-muted-foreground hover:text-foreground`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:(0,X.jsx)(je,{className:`h-3.5 w-3.5`})}):null}function _h({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=rd(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=jf(),[u,d]=(0,J.useState)(!1),{replicating:f}=bn(e),p=At(e),m=yh(e),h=m||xh(e),{blobUrl:g}=ds(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),_=t=>{o?.(t,e.id)},v=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),y=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),b=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||d(!0)},x=e=>{e.shiftKey&&e.preventDefault()},S=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(im,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>hh(n,()=>d(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:text-accent-foreground cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring transition-opacity ${f?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:b,onMouseDown:x,...l,onContextMenu:S,draggable:!0,onDragStart:_,children:[(0,X.jsx)(om,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,X.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:!!t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}})}),(0,X.jsx)(om,{className:`w-12`,children:g?(0,X.jsx)(`img`,{src:g,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,X.jsx)(fl,{document:e,chip:!0})}),(0,X.jsx)(om,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),(0,X.jsx)(gh,{document:e}),(0,X.jsx)(fh,{document:e})]}),p.subtitle&&(0,X.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,X.jsx)(om,{className:`hidden md:table-cell`,children:(0,X.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:p.schemaLabel})}),(0,X.jsx)(om,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,X.jsx)(om,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:y&&(0,X.jsx)(`span`,{className:`font-mono`,title:`${y.algo} checksum`,children:y.hash})}),(0,X.jsx)(om,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,X.jsx)(om,{className:`w-12 text-right`,children:(0,X.jsx)(mh,{documentId:e.id,onOpenActions:a})})]}),(0,X.jsx)(vm,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function vh({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=rd(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=jf(),[u,d]=(0,J.useState)(!1),f=e.schema===`data/schema/tab`,{replicating:p}=bn(e),m=At(e),h=yh(e),g=bh(e),_=h||xh(e)||g,{blobUrl:v,loading:y}=ds(n??``,e.id,512,{enabled:_,blobFallback:h,version:e.checksumArray?.[0]??null}),b=t=>{o?.(t,e.id)},x=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),S=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),C=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||d(!0)},w=e=>{e.shiftKey&&e.preventDefault()},T=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>hh(n,()=>d(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:border-primary border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${p?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${f&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:C,onMouseDown:w,...l,onContextMenu:T,draggable:!0,onDragStart:b,children:(0,X.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[_&&(0,X.jsxs)(`div`,{className:`relative h-32 w-40 max-w-[40%] sm:h-40 sm:w-56 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:[v?(0,X.jsx)(`img`,{src:v,alt:m.title,loading:`lazy`,className:`h-full w-full object-cover`}):g&&n&&!y?(0,X.jsx)(Sh,{workspaceId:n,documentId:e.id,fallback:(0,X.jsx)(fl,{document:e})}):y?(0,X.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,X.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,X.jsx)(fl,{document:e})}),g&&(0,X.jsx)(ne,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`})]}),(0,X.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,X.jsx)(fl,{document:e,chip:!0}),(0,X.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:m.title,children:m.title}),(0,X.jsx)(gh,{document:e}),(0,X.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:m.schemaLabel}),(0,X.jsx)(fh,{document:e})]}),m.subtitle&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:m.subtitle,children:m.subtitle}),m.preview&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:m.preview}),(0,X.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,X.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),S&&(0,X.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,X.jsx)(N,{className:`h-3 w-3`}),(0,X.jsx)(`span`,{className:`font-mono`,title:`${S.algo} checksum`,children:S.hash})]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,X.jsx)(pe,{className:`h-3 w-3`}),(0,X.jsx)(`span`,{title:`Created: ${x(e.createdAt)}`,children:x(e.createdAt)})]})]})]}),(0,X.jsx)(mh,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,X.jsx)(vm,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function yh(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function bh(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function xh(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Sh({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Vn(e,t),[a,o]=(0,J.useState)(!1);return i||a?(0,X.jsx)(X.Fragment,{children:n}):r?(0,X.jsxs)(`div`,{className:`relative h-full w-full`,children:[(0,X.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-full w-full object-cover`}),(0,X.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,X.jsx)(ne,{className:`h-3.5 w-3.5`})})]}):(0,X.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function Ch({document:e,workspaceId:t,markdown:n}){let r=(0,J.useRef)(null),[i,a]=(0,J.useState)(()=>typeof IntersectionObserver>`u`);(0,J.useEffect)(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(a(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let{text:o,loading:s,error:c}=Un(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,X.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,X.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,X.jsx)(bs,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,X.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,X.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,X.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,X.jsx)(fl,{document:e,size:10,chip:!0}),i&&s&&(0,X.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function wh({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let[c,l]=(0,J.useState)(null),u=e.metadata?.dimensions,d=c??(u?.width&&u?.height?Math.max(.2,Math.min(5,u.width/u.height)):1),f=rd(),p=f.alwaysOn&&f.entry?.workspaceId===n&&f.entry?.document.id===e.id,m=jf(),[h,g]=(0,J.useState)(!1),_=yh(e),v=bh(e),y=_||xh(e)||v,b=At(e),x=Tn(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||Bt(e)),S=e.schema===`data/schema/file`&&(x===`markdown`||x===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,C=!y&&e.schema!==`data/schema/file`&&!!(b.preview||b.subtitle),{replicating:T}=bn(e),{blobUrl:E,loading:D}=ds(n??``,e.id,768,{enabled:y,blobFallback:_,version:e.checksumArray?.[0]??null}),O=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&r(e.id,!i||!t,i),i||g(!0)},k=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,style:{flexGrow:d,flexBasis:`${d*220}px`,"--tile-ratio":d},"data-reading":p||void 0,"aria-selected":!!t,onKeyDown:n=>hh(n,()=>g(!0),()=>r?.(e.id,!t,!0)),className:`document-tile data-[reading=true]:bg-accent data-[reading=true]:border-primary group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-(--card-radius) border transition cursor-pointer outline-none hover:shadow-elevation-2 focus-visible:ring-2 focus-visible:ring-ring ${T?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:O,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...m,onContextMenu:k,draggable:!0,onDragStart:t=>s?.(t,e.id),title:b.title,children:[(0,X.jsx)(`input`,{type:`checkbox`,className:`absolute left-2 top-2 z-10 h-4 w-4 cursor-pointer accent-primary ${t?``:`reveal-on-hover`}`,checked:t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}}),(0,X.jsxs)(`div`,{className:`document-tile-media relative w-full bg-muted/40 ${y&&E||C||S&&n||v&&n?``:`aspect-square`}`,children:[y&&D&&(0,X.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),y&&E?(0,X.jsx)(`img`,{src:E,alt:b.title,loading:`lazy`,className:`block h-auto w-full`,onLoad:e=>{let t=e.currentTarget;t.naturalHeight&&l(t.naturalWidth/t.naturalHeight)}}):v&&n&&!D?(0,X.jsx)(Sh,{workspaceId:n,documentId:e.id,fallback:(0,X.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,X.jsx)(fl,{document:e,size:10,chip:!0})})}):S&&n?(0,X.jsx)(Ch,{document:e,workspaceId:n,markdown:x===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):C?(0,X.jsxs)(`div`,{className:`flex min-h-28 w-full flex-col gap-1.5 overflow-hidden bg-card p-3 pt-7 text-left`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,X.jsx)(fl,{document:e}),(0,X.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:b.schemaLabel}),(0,X.jsx)(gh,{document:e})]}),(0,X.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:b.title}),b.subtitle&&(0,X.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:b.subtitle}),(0,X.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:b.preview})]}):(0,X.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,X.jsx)(fl,{document:e,size:10,chip:!0})}),v&&E&&(0,X.jsx)(ne,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`}),(0,X.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,X.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Open to the side`,children:(0,X.jsx)(w,{className:`h-3.5 w-3.5`})}),o&&(0,X.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(t.currentTarget,e.id)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,X.jsx)(Ie,{className:`h-3.5 w-3.5`})})]})]}),!C&&(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,X.jsx)(`span`,{className:`truncate text-xs font-medium`,title:b.title,children:b.title}),(0,X.jsx)(gh,{document:e})]})]}),(0,X.jsx)(vm,{document:e,isOpen:h,onClose:()=>g(!1),workspaceId:n})]})}function Th(e,t,n,r,i){let[a,o]=(0,J.useState)(!1),s=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:a,onDragOver:e=>{!t||!s(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,a||o(!0))},onDragLeave:()=>o(!1),onDrop:async a=>{if(o(!1),!t||!s(a))return;a.preventDefault(),a.stopPropagation();let c=null;try{c=JSON.parse(a.dataTransfer.getData(`application/json`))}catch{c=null}if(!(c?.type!==`document`||!Array.isArray(c.documentIds)||c.documentIds.length===0)&&!Xp(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function Eh(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function Dh({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,X.jsx)(dt,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,X.jsx)(fe,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var Oh=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function kh({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Th(e,r,i,a,o);return(0,X.jsxs)(`button`,{type:`button`,title:Oh(e),onClick:()=>t?.(e.path),onContextMenu:t=>Eh(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 max-w-full items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm transition-colors hover:bg-accent ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,X.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,X.jsx)(Dh,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,X.jsx)(dt,{className:`hidden h-4 w-4 group-hover:block`}):(0,X.jsx)(ge,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,X.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,X.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function Ah({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Th(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,X.jsxs)(`button`,{type:`button`,title:Oh(e),onClick:()=>t?.(e.path),onContextMenu:t=>Eh(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-(--card-radius) border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,X.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,X.jsx)(dt,{className:`h-10 w-10`,strokeWidth:1.5}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(fe,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,X.jsx)(ge,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c})]})}),(0,X.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,X.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function jh({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,X.jsx)(`div`,{className:`mb-4 grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,X.jsx)(Ah,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function Mh({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,X.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,X.jsx)(kh,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function Nh({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Th(e,r,i,a,o);return(0,X.jsxs)(im,{"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=>Eh(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:Oh(e),children:[(0,X.jsx)(om,{className:`w-10`}),(0,X.jsx)(om,{className:`w-12`,children:(0,X.jsx)(Dh,{folder:e})}),(0,X.jsx)(om,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,X.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,X.jsx)(om,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,X.jsx)(om,{className:`hidden lg:table-cell`}),(0,X.jsx)(om,{className:`hidden lg:table-cell`}),(0,X.jsx)(om,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,X.jsx)(om,{className:`w-12 md:w-auto`})]})}function Ph({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,X.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-1 mb-2 flex items-center gap-2 bg-background/95 px-1 py-1.5 backdrop-blur-sm`,children:[(0,X.jsx)(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 cursor-pointer accent-primary ${r||i?``:`reveal-on-hover`}`,checked:r,ref:e=>{e&&(e.indeterminate=i&&!r)},onChange:e=>o(e.target.checked),title:`Select everything in "${e}"`,onClick:e=>e.stopPropagation()}),(0,X.jsxs)(`button`,{type:`button`,onClick:a,"aria-expanded":!n,className:`flex min-w-0 items-center gap-1.5 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,X.jsx)(gt,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,X.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,X.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,X.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function Fh({readingPane:e=!1,externalSearchQuery:t,toolbarActions:n,documents:r,isLoading:i,contextPath:a,treeName:o,workspaceId:s,totalCount:l,onRemoveDocument:d,onDeleteDocument:m,onDestroyDocument:h,onRemoveDocuments:g,onDeleteDocuments:_,onDestroyDocuments:v,onCopyDocuments:y,onCutDocuments:x,onPasteDocuments:S,onImportDocuments:C,onSelectionChange:T,pastedDocumentIds:E,viewMode:D=`card`,allowViewToggle:O=!1,activeContextUrl:k,currentContextUrl:A,currentPage:N=1,pageSize:F=50,onPageChange:I,onPageSizeChange:ee,onPurgeDocuments:ne,disablePurgeDocuments:re=!1,backendSearchQueries:R=[],onBackendSearch:z,onRemoveBackendQuery:oe,serverSort:se,onServerSortChange:ce,scope:V=`path`,onScopeChange:le,canSaveChanges:ue=!1,isSavingChanges:fe=!1,onSaveChanges:pe,linkTree:me,folders:ge,onOpenFolder:_e}){let ve=yo(),ye=Oo(),[be,xe]=(0,J.useState)(()=>{if(!O)return D;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return D}),Ce=O?ve?.documentLayout??be:D,we=(0,J.useCallback)(e=>{ve?.selectDocumentLayout(e),xe(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[ve]),[Te,Ee]=(0,J.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),De=(0,J.useCallback)(()=>{Ee(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[Oe,ke]=(0,J.useState)(new Set),Ae=(0,J.useCallback)(e=>{ke(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[U,Pe]=(0,J.useState)(new Set),[Ie,Le]=(0,J.useState)(null),[Re,ze]=(0,J.useState)(null),Ve=nr(),Ue=!!(Ve&&s),We=(0,J.useCallback)((e,t=!1)=>{if(!Ve||!s)return;let n=e.map(e=>r.find(t=>t.id===e)).filter(e=>!!e);n.length!==0&&Ve.openAddRelated({workspaceName:s,documents:n},t)},[Ve,s,r]),[Ge,Ke]=(0,J.useState)(!1),[qe,Xe]=(0,J.useState)(null),[Ze,Qe]=(0,J.useState)(!1),[tt,rt]=(0,J.useState)(null),[it,at]=(0,J.useState)(!1),ot=(0,J.useRef)(!1),ct=(0,J.useRef)(!1),lt=o===`backends`&&V===`path`?tf(a):null;(0,J.useEffect)(()=>()=>{ot.current=!0},[]);let[ut,dt]=(0,J.useState)(!1),[mt,_t]=(0,J.useState)(null),[W,vt]=(0,J.useState)(!1),[G,K]=(0,J.useState)(null),yt=Zn()==null&&!!s,[bt,xt]=(0,J.useState)(null),[wt,Et]=(0,J.useState)(null),Dt=!!(me&&S),Ot=!!s,{showSuccessToast:jt,showErrorToast:Mt}=Ct(),{showProgress:Nt}=St(),Pt=rd(),Ft=s?e=>Pt.open(e,s):void 0,It=V===`workspace`,Lt=It?void 0:d,Rt=It?void 0:g,[zt,Vt]=(0,J.useState)(!1),[Ut,Wt]=(0,J.useState)(!1),[Gt,Kt]=(0,J.useState)(``),qt=t??Gt,Jt=t!==void 0,[Yt,Xt]=(0,J.useState)(!1),Zt=R.length>0,Qt=(0,J.useRef)(null),$t=(0,J.useCallback)(()=>{Kt(``),Qt.current&&(Qt.current.value=``)},[]);(0,J.useEffect)(()=>{if(!O||window.matchMedia(`(max-width: 767px)`).matches)return;let e=Qt.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[O]);let en=JSON.stringify([s,o,a]),[tn,nn]=(0,J.useState)(en);en!==tn&&(nn(en),Pe(new Set),Xe(null),ze(null),Le(null)),(0,J.useEffect)(()=>{T?.(Array.from(U))},[U,T]);let rn=(0,J.useCallback)(()=>{if(!z)return;let e=qt.trim();e&&(z(e),$t())},[z,qt,$t]),an=(0,J.useCallback)(()=>{$t(),oe&&R.length>0&&oe(-1)},[oe,R.length,$t]),on=(0,J.useCallback)((e,t)=>{let n;U.has(t)&&U.size>1?n=Array.from(U):(n=[t],Pe(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:V===`path`?a:void 0,sourceTreeName:o,sourceWorkspaceId:s};e.dataTransfer.setData(`application/json`,JSON.stringify(r)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[U,a,o,s,V]),sn=(0,J.useCallback)(async e=>{if(!S)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let n=null;try{n=JSON.parse(t)}catch{return}n?.type!==`document`||!Array.isArray(n.documentIds)||n.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),Xt(!1),!Xp(n,s,o,a)&&(await S(a,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),Pe(new Set)))},[a,o,s,S]),cn=(0,J.useCallback)(e=>{S&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,Xt(!0))},[S]),ln=(0,J.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||Xt(!1)},[]),un=(0,J.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),dn=(0,J.useMemo)(()=>r.length===0?null:new fr(r,un),[r,un]),fn=(0,J.useDeferredValue)(qt),pn=(0,J.useMemo)(()=>{if(!fn.trim())return r;let{text:e,ids:t,invalid:n}=kf(fn);if(n)return[];let i=e&&dn?dn.search(e).map(e=>e.item):r;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[r,fn,dn]),mn=(0,J.useMemo)(()=>{if(!ge||ge.length===0||fn.trim())return[];let e=se?.order===`desc`?-1:1;return[...ge].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)},[ge,fn,se?.order]),hn=mn.length>0,[gn,_n]=(0,J.useState)(null),vn=(0,J.useMemo)(()=>s&&o&&_e?(e,t)=>_n({x:t.clientX,y:t.clientY,path:e}):void 0,[s,o,_e]),yn={folders:mn,onOpen:_e,onMenu:vn,onPasteDocuments:S,contextPath:a,treeName:o,workspaceId:s},{sorted:bn,sort:xn,toggleSort:Sn}=lm(pn,(0,J.useMemo)(()=>({title:e=>At(e).title?.toLowerCase()??``,schema:e=>At(e).schemaLabel??``,type:Tt,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),Cn=(0,J.useCallback)(e=>Nm(e,se?.sortBy),[se?.sortBy]),wn=(0,J.useMemo)(()=>Hm(pn,Cn,se?.order===`asc`?`asc`:`desc`),[pn,Cn,se?.order]),Tn=Te&&!Ht(se?.sortBy)&&wn.length>1,En=(0,J.useCallback)((e,t)=>{Pe(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),Dn=(0,J.useMemo)(()=>(Ce===`table`?bn:Tn?wn.filter(e=>!Oe.has(e.key)).flatMap(e=>e.items):pn).map(e=>e.id),[Ce,bn,Tn,wn,Oe,pn]),On=(0,J.useRef)(null),kn=JSON.stringify([s,a,o,N]),An=(0,J.useCallback)(e=>{On.current=null,Pe(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),jn=(0,J.useCallback)((e,t,n,r=!1)=>{let i=On.current,a=i?.scope===kn&&Dn.includes(i.id)?i.id:null;(!r||a===null)&&(On.current={scope:kn,id:e}),Pe(i=>{if(r)return Mf(Dn,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[kn,Dn]),Nn=(0,J.useCallback)((e,t)=>{let n;U.has(e)?n=Array.from(U):(n=[e],Pe(new Set([e]))),Le({anchor:t,ids:n})},[U]),Pn=(0,J.useCallback)((e,t)=>{Nn(t,Dc(e))},[Nn]),In=(0,J.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),Nn(t,ph(e)))},[Nn]),Ln=(0,J.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){Ke(!0);try{for(let n of t)await Mn(s,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;jt(`Created ${n} relation${n===1?``:`s`}`),Dl(),ze(null)}catch(e){Mt(e instanceof Error?e.message:`Failed to create relations`)}finally{Ke(!1)}}},[s,jt,Mt]),Rn=(0,J.useCallback)(async(e,t,n)=>{if(S){for(let r of e)await S(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});Pe(new Set)}},[S]),zn=(0,J.useCallback)(async(e,t,n)=>{if(!s||!qe||ct.current)return;ct.current=!0,ot.current=!1,at(!1),Qe(!0);let i=Nt({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${qe.ids.length} document(s) · ${e.join(`, `)}`});try{let a=r=>Fn(s,r,{to:e,mode:t,keepDocument:n.keepDocument,...t===`delete`&<?{deleteFrom:{backend:lt.backend,folder:lt.rel}}:{},folder:n.folder,filename:n.filename,onConflict:n.onConflict}),o=t===`delete`?await zd(qe.ids,a,{shouldStop:()=>ot.current,onProgress:(t,n)=>{rt({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(qe.ids),pending:[]},c=o.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,l=o.successful.filter(e=>e.transfers?.some(e=>e.state===`pending`)).length,u=o.successful.length-c-l,d=o.failed.length,f=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,p=e.join(`, `),m=[c?`${c} already there`:null,l?`${l} queued for backend sync`:null,d?`${d} skipped`:null,o.pending.length?`${o.pending.length} not processed`:null].filter(Boolean).join(` · `),h=`${f} ${p}: ${u} document${u===1?``:`s`}${m?` · ${m}`:``}`;d>0?(i.fail({title:`Operation incomplete`,description:`${h}. ${Xl(o.failed,new Map(r.map(e=>[e.id,At(e).title])))}`,variant:`destructive`}),console.warn(`Backend transfer skipped documents:`,o.failed)):i.done({title:o.pending.length?`Operation stopped`:l?`Transfer queued`:`Operation complete`,description:h}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`));let g=[...o.failed.map(e=>e.id),...o.pending];Xe(g.length?{ids:g,mode:t}:null),Pe(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{ct.current=!1,Qe(!1),rt(null)}},[s,qe,lt,r,Nt]),Bn=(0,J.useCallback)(()=>{U.size===pn.length?Pe(new Set):Pe(new Set(pn.map(e=>e.id)))},[U.size,pn]),Vn=(0,J.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{let t=window.document.createElement(`textarea`);t.value=e,window.document.body.appendChild(t),t.select(),window.document.execCommand(`copy`),window.document.body.removeChild(t)}},[]),Hn=e=>{if(e.length===0)return[];let t=e.length,n=t>1?` (${t})`:``,i=t===1?r.find(t=>t.id===e[0]):void 0,a=()=>Pe(new Set),c=e.some(e=>r.find(t=>t.id===e)?.locations?.some(e=>e.status==null||e.status===`available`)),l=[],u=e=>{e&&l.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;u({id:`view`,group:`open`,label:`View details`,icon:st,run:()=>Et({document:i})}),u(yt&&{id:`edit`,group:`open`,label:`Edit`,icon:ae,run:()=>Et({document:i,edit:!0})}),u(yt&&i.schema===`data/schema/file`&&{id:`rename`,group:`open`,label:`Rename…`,icon:ae,run:()=>Et({document:i,edit:!0})});let t=i.data?.url||i.data?.uri;u(yt&&s&&i.schema!==`data/schema/file`&&typeof t==`string`&&/^https?:\/\//i.test(t)&&{id:`download-link`,group:`open`,label:`Download to workspace`,icon:Ne,run:async()=>{let e=Nt({title:`Downloading file…`});try{await kt(s,i.id),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),e.done({title:`File saved to workspace`})}catch(t){e.fail({title:`Download failed`,description:t instanceof Error?t.message:String(t),variant:`destructive`})}}}),u(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:je,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),u(Ft&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:w,run:()=>Ft(i)})}return u(y&&{id:`copy`,group:`clipboard`,label:`Copy${n}`,icon:f,shortcut:`Mod+C`,run:()=>y(e)}),u(x&&{id:`cut`,group:`clipboard`,label:`Cut${n}`,icon:ft,shortcut:`Mod+X`,run:()=>x(e)}),u(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:Fe,run:()=>Vn(String(i.id))}),u(i&&yt&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:nt,run:()=>xt(i)}),u(Dt&&{id:`link-to`,group:`organize`,label:`Link to…${n}`,icon:Me,run:()=>ze(e)}),u(Ue&&{id:`add-related`,group:`organize`,label:`Add related document…${n}`,icon:L,run:t=>We(e,t?.shiftKey)}),u(yt&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${n}`,icon:ae,run:()=>K(e)}),u(yt&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:f,run:t=>{vt(!!t?.shiftKey),_t(e)}}),u({id:`export`,group:`organize`,label:`Export…${n}`,icon:Ne,run:()=>Vt(!0)}),u(o!==`backends`&&(Lt||Rt)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${n}`,icon:j,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&Lt?Lt(e[0]):Rt?.(e),a()}}),u(o!==`backends`&&(m||_)&&{id:`delete`,group:`remove`,label:`Delete from index${n}`,icon:he,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&m?m(e[0]):_?.(e),a()}}),c&&Ot?(u({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${n}`,icon:B,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Xe({ids:e,mode:`copy`})}),u({id:`backend-move`,group:`backends`,label:`Move to backend…${n}`,icon:Be,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Xe({ids:e,mode:`move`})}),u({id:`backend-delete`,group:`backends`,label:`Delete from backend…${n}`,icon:he,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Xe({ids:e,mode:`delete`})})):c&&(h||v)&&u({id:`destroy`,group:`backends`,label:`Delete from backend(s)${n}`,icon:he,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&h?h(e[0]):v?.(e),a()}}),l},Un=()=>{let e=[],t=t=>{t&&e.push(t)},n=E??[];return t(S&&n.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${n.length})`,icon:te,shortcut:`Mod+V`,run:async()=>{try{await S(a,n)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(pn.length>0&&{id:`select-all`,group:`select`,label:qt?`Select all matches (${pn.length})`:`Select all on this page`,icon:Ye,shortcut:`Mod+A`,run:()=>Pe(new Set(pn.map(e=>e.id)))}),t(U.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:et,run:()=>Pe(new Set)}),t(S&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:Je,hint:`Browse and add existing documents to this folder`,run:()=>dt(!0)}),t(C&&{id:`import`,group:`add`,label:`Import…`,icon:de,run:()=>Wt(!0)}),t(r.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:Ne,run:()=>{Pe(new Set),Vt(!0)}}),t(ne&&l>0&&{id:`purge`,group:`purge`,label:`Purge all (${l})`,icon:he,destructive:!0,disabled:re||!!qt,hint:qt?`Purge is disabled while local search is active`:re?`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:ne}),e},Wn=!!(ce&&se&&s),Gn=Ie?Ie.ids?Hn(Ie.ids):Un():[],Kn=Ie?.ids?.length===1?r.find(e=>e.id===Ie.ids[0]):void 0,qn=Kn?(0,X.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,X.jsx)(fl,{document:Kn,chip:!0}),(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:At(Kn).title}),(0,X.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Kn.id,` · `,Kn.schema]})]})]}):(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Ie?.ids?`${Ie.ids.length} documents`:`This folder`}),Jn=e=>{Le({anchor:Dc(e.currentTarget),ids:U.size>0?Array.from(U):null})},Yn=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),Pe(new Set),Le({anchor:ph(e),ids:null}))},Xn=e=>{if(e.defaultPrevented||Cc(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Tc(e)){e.preventDefault(),t?Nn(Number(t.dataset.documentId),Dc(t,`inside`)):Le({anchor:Dc(e.target,`inside`),ids:U.size>0?Array.from(U):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&&jn(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&U.size>0){e.preventDefault(),Pe(new Set);return}wc(e,[...Hn(Array.from(U)),...Un()])},Qn=(0,J.useCallback)(async e=>{if(!C)return!1;try{return await C(e,a)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[C,a]),$n=e=>Tn?wn.map(t=>{let n=Oe.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!U.has(t),0);return(0,X.jsxs)(`section`,{className:`group mb-4`,children:[(0,X.jsx)(Ph,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>Ae(t.key),onSelectAll:e=>En(r,e)}),!n&&e(t.items)]},t.key)}):e(pn);return i?(0,X.jsx)(Ld,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:[],loading:!0,children:(0,X.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,X.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,X.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})})}):(0,X.jsx)(Ld,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:Ce===`table`?bn:pn,loading:!1,children:(0,X.jsxs)(`div`,{tabIndex:-1,onKeyDown:Xn,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${Yt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:cn,onDragLeave:ln,onDrop:sn,children:[(0,X.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,X.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,X.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,X.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:qt?`${pn.length} of ${r.length}`:`${l.toLocaleString()} document${l===1?``:`s`}`})]}),(0,X.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,X.jsxs)(`p`,{hidden:Jt,className:`min-w-0 truncate`,children:[`Context: `,(0,X.jsx)(`span`,{className:`font-mono`,children:a}),k&&A&&k!==A&&(0,X.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,X.jsxs)(`p`,{className:`shrink-0`,children:[U.size>0&&(0,X.jsxs)(`span`,{className:`text-info`,children:[U.size,` selected`]}),U.size>0&&(qt||l>F)&&(0,X.jsx)(`span`,{className:`mx-1`,children:`·`}),qt?`on this page`:l>F?`Showing ${Math.min((N-1)*F+1,l)}–${Math.min(N*F,l)}`:null]})]})]}),!Jt&&(0,X.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,X.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[!Jt&&le&&(0,X.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:()=>le(`path`),className:`px-2.5 py-2 transition-colors ${V===`path`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List documents in the selected path`,children:`This path`}),(0,X.jsxs)(`button`,{type:`button`,onClick:()=>le(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${V===`workspace`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List every document in the workspace (staging excluded)`,children:[(0,X.jsx)(H,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!Jt&&(0,X.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,X.jsx)(ht,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,X.jsx)(`input`,{ref:Qt,type:`text`,placeholder:z?Zt?`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=>Kt(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`&&z&&(e.preventDefault(),rn())},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`}),(qt||Zt)&&(0,X.jsx)(`button`,{onClick:an,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,X.jsx)(M,{className:`h-4 w-4`})})]}),!Jt&&z&&qt.trim()&&!R.includes(qt.trim())&&(0,X.jsxs)(q,{size:`sm`,variant:`default`,onClick:rn,className:`shrink-0`,title:Zt?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,X.jsx)(ht,{className:`h-3.5 w-3.5 mr-1`}),Zt?`Refine`:`Search server`]})]}),!Jt&&Zt&&(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),R.map((e,t)=>(0,X.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,X.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,X.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,X.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),oe&&(0,X.jsx)(`button`,{onClick:()=>oe(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,X.jsx)(M,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),oe&&R.length>1&&(0,X.jsx)(`button`,{onClick:()=>oe(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,X.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,X.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,X.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[O&&(0,X.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,pt,`Tile view`],[`card`,Se,`Card view`]].map(([e,t,n])=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>we(e),title:n,"aria-pressed":Ce===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${Ce===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,X.jsx)(t,{className:`h-4 w-4`})},e))}),O&&Ce!==`table`&&!Ht(se?.sortBy)&&(0,X.jsx)(`button`,{type:`button`,onClick:De,title:Te?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":Te,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${Te?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,X.jsx)(b,{className:`h-4 w-4`})})]}),I&&l>0&&(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,X.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,X.jsxs)(`select`,{value:F,onChange:e=>ee?.(Number(e.target.value)),className:`h-control-sm rounded-(--input-radius) border-(length:--input-border-width) border-input bg-background px-2 text-sm focus-ring`,"aria-label":`Documents per page`,children:[(0,X.jsx)(`option`,{value:25,children:`25`}),(0,X.jsx)(`option`,{value:50,children:`50`}),(0,X.jsx)(`option`,{value:100,children:`100`}),(0,X.jsx)(`option`,{value:200,children:`200`})]}),(0,X.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,X.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[Wn&&(0,X.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,X.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,X.jsx)(Mm,{workspaceId:s,value:se,onChange:ce})]}),(0,X.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(r.length>0||C||S)&&(0,X.jsxs)(`div`,{className:`contents`,children:[(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:Jn,"aria-haspopup":`menu`,"aria-label":U.size>0?`Actions (${U.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${xc(`Shift+F10`)} or right-click)`,children:[(0,X.jsx)(He,{className:`h-4 w-4`}),(0,X.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,U.size>0?` (${U.size} selected)`:``]})]}),U.size>0&&(0,X.jsxs)(q,{variant:`ghost`,size:`sm`,onClick:()=>Pe(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,X.jsx)(M,{className:`h-3.5 w-3.5`}),(0,X.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),E&&E.length>0&&S&&(0,X.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>S(a,E),className:`flex items-center gap-1.5`,title:`Paste into this folder (${xc(`Mod+V`)})`,children:[(0,X.jsx)(te,{className:`h-4 w-4`}),`Paste (`,E.length,`)`]})]}),ue&&pe&&(0,X.jsx)(q,{size:`sm`,variant:`outline`,onClick:pe,disabled:fe,className:`w-control-sm shrink-0 px-0 touch-target`,"aria-label":fe?`Saving filters`:`Save current query and filters`,title:`Save current query and filters`,children:(0,X.jsx)(p,{className:`h-3.5 w-3.5`})}),n]})]})]})}),I&&l>F&&(0,X.jsxs)(`div`,{className:`document-pagination mt-3 flex min-w-0 flex-wrap items-center justify-end gap-2 border-t pt-3 max-sm:gap-0.5`,children:[(0,X.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((N-1)*F+1,l),` - `,Math.min(N*F,l),` of `,l]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,X.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>I(1),disabled:N===1,className:`p-1 touch-target`,children:(0,X.jsx)(ie,{className:`h-4 w-4`})}),(0,X.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>I(N-1),disabled:N===1,className:`p-1 touch-target`,children:(0,X.jsx)(u,{className:`h-4 w-4`})}),(0,X.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,X.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),N,(0,X.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,X.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(l/F)]}),(0,X.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>I(N+1),disabled:N>=Math.ceil(l/F),className:`p-1 touch-target`,children:(0,X.jsx)(gt,{className:`h-4 w-4`})}),(0,X.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>I(Math.ceil(l/F)),disabled:N>=Math.ceil(l/F),className:`p-1 touch-target`,children:(0,X.jsx)(P,{className:`h-4 w-4`})})]})]})]}),(0,X.jsx)(Up,{scope:JSON.stringify([kn,Ce,Dn]),selected:U,onSelectionChange:An,onContextMenu:Yn,children:pn.length===0&&!hn?(0,X.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,X.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,X.jsx)($e,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:qt?`No documents match your search`:`No documents found in this context`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:qt?(0,X.jsxs)(X.Fragment,{children:[`Search: `,(0,X.jsxs)(`span`,{className:`font-mono`,children:[`"`,qt,`"`]})]}):(0,X.jsxs)(X.Fragment,{children:[`Path: `,(0,X.jsx)(`span`,{className:`font-mono`,children:a})]})}),!Jt&&qt&&(0,X.jsx)(`button`,{onClick:$t,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!qt&&E&&E.length>0&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,xc(`Mod+V`),` to paste `,E.length,` document(s)`]})]})}):Ce===`tile`?(0,X.jsxs)(`div`,{children:[(0,X.jsx)(jh,{...yn}),pn.length===0&&(0,X.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),$n(e=>(0,X.jsx)(`div`,{className:`document-tiles pr-2`,"data-tile-style":ye,children:e.map(e=>(0,X.jsx)(wh,{document:e,isSelected:U.has(e.id),workspaceId:s,onSelect:jn,onOpenToSide:Ft,onRightClick:In,onOpenActions:Pn,onDragStart:on},e.id))}))]}):Ce===`table`?(0,X.jsx)(`div`,{children:(0,X.jsxs)(em,{children:[(0,X.jsx)(tm,{children:(0,X.jsxs)(im,{children:[(0,X.jsx)(am,{className:`w-10`,children:(0,X.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:pn.length>0&&U.size===pn.length,ref:e=>{e&&(e.indeterminate=U.size>0&&U.size<pn.length)},onChange:Bn,title:`Select all on this page`})}),(0,X.jsx)(cm,{label:(0,X.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:xn,onSort:Sn,className:`w-12`}),(0,X.jsx)(cm,{label:`Title`,sortKey:`title`,sort:xn,onSort:Sn,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,X.jsx)(cm,{label:`Schema`,sortKey:`schema`,sort:xn,onSort:Sn,className:`hidden md:table-cell`}),(0,X.jsx)(cm,{label:`ID`,sortKey:`id`,sort:xn,onSort:Sn,className:`hidden lg:table-cell`}),(0,X.jsx)(am,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,X.jsx)(cm,{label:`Created`,sortKey:`created`,sort:xn,onSort:Sn,className:`hidden sm:table-cell`}),(0,X.jsx)(am,{className:`w-12 md:w-auto`,children:(0,X.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,X.jsxs)(nm,{children:[mn.map(e=>(0,X.jsx)(Nh,{folder:e,onOpen:_e,onMenu:vn,onPasteDocuments:S,contextPath:a,treeName:o,workspaceId:s},e.path)),bn.map(e=>(0,X.jsx)(_h,{document:e,isSelected:U.has(e.id),workspaceId:s,onSelect:jn,onOpenToSide:Ft,onRightClick:In,onOpenActions:Pn,onDragStart:on},e.id))]})]})}):(0,X.jsxs)(`div`,{children:[(0,X.jsx)(Mh,{...yn}),pn.length===0&&(0,X.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),$n(e=>(0,X.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,X.jsx)(`div`,{children:(0,X.jsx)(vh,{document:e,isSelected:U.has(e.id),workspaceId:s,onSelect:jn,onOpenToSide:Ft,onRightClick:In,onOpenActions:Pn,onDragStart:on})},e.id))}))]})}),Ie&&(0,X.jsx)(Mc,{anchor:Ie.anchor,items:Gn,onClose:()=>Le(null),label:Ie.ids?`Document actions`:`Folder actions`,header:qn}),(0,X.jsx)(uh,{isOpen:zt,onClose:()=>Vt(!1),documents:r,selectedDocuments:U}),(0,X.jsx)(dh,{isOpen:Ut,onClose:()=>Wt(!1),onImport:Qn}),mt&&s&&(0,X.jsx)(Gp,{modal:W,workspaceId:s,ids:mt,onClose:()=>_t(null)}),Re&&me&&(0,X.jsx)(Rf,{label:`Link to`,onClose:()=>ze(null),children:(0,X.jsx)(Tl,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:Re.length,fixedWorkspaceName:s,tabs:[`context`,`directory`,`relations`],saving:Ge,relationExcludeIds:new Set(Re),onConfirm:(e,t)=>Rn(e,Re,t),onConfirmRelation:e=>Ln(e,Re),onClose:()=>ze(null)})}),qe&&s&&(0,po.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,X.jsx)(ru,{workspaceId:s,documentCount:qe.ids.length,initialMode:qe.mode,defaultFilename:qe.ids.length===1?Bt(r.find(e=>e.id===qe.ids[0])??{}):``,saving:Ze,progress:tt,stopping:it,onStop:()=>{ot.current=!0,at(!0)},deleteFrom:lt?{backend:lt.backend,folder:lt.rel}:void 0,onConfirm:zn,onClose:()=>{Ze||Xe(null)}})}),window.document.body),ut&&S&&(0,po.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>dt(!1),"aria-hidden":!0}),(0,X.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,X.jsx)(Zp,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:s,onConfirm:async e=>{await S(a,e),dt(!1)},onClose:()=>dt(!1)})})]}),window.document.body),bt&&s&&(0,X.jsx)(Lp,{workspaceId:s,document:bt,onClose:()=>xt(null)},`${s}:${bt.id}`),G&&s&&(0,X.jsx)(Jp,{workspaceId:s,documentIds:G,onClose:()=>K(null)}),(0,X.jsx)(vm,{document:wt?.document??null,isOpen:!!wt,onClose:()=>Et(null),workspaceId:s,initialEdit:wt?.edit}),gn&&s&&o&&_e&&(0,X.jsx)(ch,{x:gn.x,y:gn.y,workspaceName:s,treeName:o,path:gn.path,onClose:()=>_n(null),onOpen:_e,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:s,treeName:o,path:e}})),pastedDocumentIds:E,onPasteDocuments:S?(e,t)=>S(e,t):void 0})]})})}function Ih(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,Qp.createRoot)(t);n.render((0,X.jsx)(dh,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function Lh(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,Qp.createRoot)(t);n.render((0,X.jsx)(uh,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{mf as $,wi as $n,Tl as $t,em as A,Rs as An,id as At,Qf as B,Go as Bn,du as Bt,Tm as C,Ws as Cn,Nd as Ct,_m as D,Us as Dn,wd as Dt,hm as E,qs as En,Ed as Et,im as F,bs as Fn,ed as Ft,Kf as G,Oo as Gn,ql as Gt,Yf as H,Io as Hn,Zl as Ht,Zp as I,ds as In,Ku as It,Nf as J,go as Jn,Nl as Jt,Gf as K,yo as Kn,zl as Kt,Xp as L,is as Ln,Vu as Lt,om as M,Bs as Mn,td as Mt,am as N,Hs as Nn,rd as Nt,lm as O,Fs as On,ud as Ot,tm as P,Ms as Pn,Qu as Pt,vf as Q,eo as Qn,Dl as Qt,Jp as R,Yo as Rn,Mu as Rt,wm as S,_c as Sn,Id as St,vm as T,Gs as Tn,Dd as Tt,Jf as U,bo as Un,Ql as Ut,Zf as V,Po as Vn,iu as Vt,Xf as W,Eo as Wn,Jl as Wt,ff as X,gr as Xn,jl as Xt,jf as Y,mo as Yn,Ml as Yt,Of as Z,$a as Zn,Ol as Zt,Sm as _,Fc as _n,Cf as _t,nh as a,tl as an,pa as ar,Hd as at,Em as b,Sc as bn,Zd as bt,$m as c,Ic as cn,Or as cr,Qd as ct,Zm as d,zc as dn,Li as dr,Jd as dt,ml as en,la as er,lf as et,Um as f,Wc as fn,Vi as fr,Vd as ft,Om as g,Kc as gn,nf as gt,Mm as h,qc as hn,wf as ht,oh as i,nl as in,Ti as ir,hf as it,nm as j,zs as jn,od as jt,cm as k,Vs as kn,ad as kt,qm as l,Rc as ln,Tr as lr,_f as lt,Gm as m,Pc as mn,df as mt,sh as n,fl as nn,ua as nr,Wd as nt,Qm as o,el as on,wr as or,Tf as ot,Wm as p,Gc as pn,oo as pr,cf as pt,Rf as q,_o as qn,Vl as qt,ah as r,Zc as rn,da as rr,Ef as rt,Ym as s,Lc as sn,ma as sr,uf as st,Fh as t,pl as tn,Ci as tr,rf as tt,Jm as u,Bc as un,Pi as ur,Yd as ut,bm as v,Mc as vn,Ud as vt,xm as w,Ks as wn,Ad as wt,Cm as x,vc as xn,tf as xt,Dm as y,Cc as yn,gf as yt,Ip as z,Xo as zn,Du as zt};
|