@augmentd-labs/canvas-web 2.26.27 → 2.26.29
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/CalendarApplet-CXG7O1QW.js +1 -0
- package/dist/assets/{DocumentBodyEditor-8DNmOBS0.js → DocumentBodyEditor-DRFQgBNB.js} +1 -1
- package/dist/assets/{DocumentIcon-x299QNu_.js → DocumentIcon-ByDAILhm.js} +1 -1
- package/dist/assets/{EditorOverlay-Cv1MaTok.js → EditorOverlay-DpQKmxkR.js} +1 -1
- package/dist/assets/{FileForm-CqJpRbXv.js → FileForm-B6eFRKG-.js} +1 -1
- package/dist/assets/{FiltersApplet-C-WD5XT9.js → FiltersApplet-C6-D-MEW.js} +1 -1
- package/dist/assets/{HomeFab-CzKEIYDk.js → HomeFab-DZbi60PC.js} +2 -2
- package/dist/assets/{IdentityFields-Bti7ojF3.js → IdentityFields-CEDxU-Hd.js} +1 -1
- package/dist/assets/{LensApplet-BCJXNx84.js → LensApplet-B9OaePzA.js} +1 -1
- package/dist/assets/LinkToCard-VXpoeMDH.js +1 -0
- package/dist/assets/{MarkdownEditor-CNY-VmKb.js → MarkdownEditor-Dnyez7VT.js} +2 -2
- package/dist/assets/{MessageComposerDialog-gbD0Gu_b.js → MessageComposerDialog-BKGlI7jO.js} +1 -1
- package/dist/assets/{NextShell-UX4Efo0u.js → NextShell-BvKyH2Oj.js} +1 -1
- package/dist/assets/{NotesApplet-CvPyt7xB.js → NotesApplet-BM7ksdXl.js} +1 -1
- package/dist/assets/ObjectPropertiesCard-CFZ_LqzX.js +8 -0
- package/dist/assets/{PathPickerField-fZazwxCN.js → PathPickerField-B58yeJGw.js} +1 -1
- package/dist/assets/PickDocumentsCard-B72XNYh3.js +1 -0
- package/dist/assets/{SketchApplet-DDIg411i.js → SketchApplet-BHee4eKG.js} +1 -1
- package/dist/assets/{SketchEditor-CKPPuZt3.js → SketchEditor-Knj-HA0P.js} +1 -1
- package/dist/assets/{TerminalApplet-wGJG1PPc.js → TerminalApplet-Djk4l1Jm.js} +1 -1
- package/dist/assets/{TextDocumentEditor-CRre32cj.js → TextDocumentEditor-rgHsbLCL.js} +1 -1
- package/dist/assets/{TodosApplet-CleBd4uU.js → TodosApplet-DZVcRHmh.js} +1 -1
- package/dist/assets/{TodosWidget-CxiqmDuJ.js → TodosWidget-CX4lgk-9.js} +1 -1
- package/dist/assets/{UploadProgressList-DRJzjy6A.js → UploadProgressList-CHQ-Kn-e.js} +1 -1
- package/dist/assets/{_agentId_-BXYnpAWp.js → _agentId_-CweMTe-q.js} +0 -0
- package/dist/assets/_contextId_-HAAoVKBa.js +1 -0
- package/dist/assets/_workspaceName_-D79RwRsV.js +1 -0
- package/dist/assets/{about-DrgIxiPQ.js → about-dr4T4ju8.js} +1 -1
- package/dist/assets/{add-CPkuZwMW.js → add-fha_SoND.js} +1 -1
- package/dist/assets/agents-CZgEe18J.js +1 -0
- package/dist/assets/{agents-DlLq0q2s.js → agents-DEJU4O1Z.js} +1 -1
- package/dist/assets/{alert-dialog-izlVMXfa.js → alert-dialog-CShuAcnP.js} +1 -1
- package/dist/assets/{api-tokens-DDH7LMJ7.js → api-tokens-CmHhwd58.js} +1 -1
- package/dist/assets/{appearance-DRBtL9nd.js → appearance-SqhMHD_S.js} +1 -1
- package/dist/assets/{applet-target-C_gBgU-Z.js → applet-target-Bl9Je1N-.js} +1 -1
- package/dist/assets/apps-stCO1N5r.js +1 -0
- package/dist/assets/{auth-HZNJB4wv.js → auth-_bmIEN02.js} +1 -1
- package/dist/assets/backend-sync-progress-DyvV8N9D.js +7 -0
- package/dist/assets/{button-SgR3GVvV.js → button-Bum-POPT.js} +1 -1
- package/dist/assets/content-app-view-CotdPc2q.js +1 -0
- package/dist/assets/{context-DQoZFMDQ.js → context-BGgz0Y_q.js} +1 -1
- package/dist/assets/{contexts-CvMtPd1N2.js → contexts-CwGdjtXy2.js} +1 -1
- package/dist/assets/{contexts-Ef3fHwv6.js → contexts-Dtl9oERX.js} +1 -1
- package/dist/assets/{date-time-picker-DebNUTx3.js → date-time-picker-Bzu8H_Oa.js} +1 -1
- package/dist/assets/{devices-C3gLuNDv.js → devices-CmVlYbam.js} +1 -1
- package/dist/assets/{document-DOp6AbOi.js → document-Ds_P5v-f.js} +1 -1
- package/dist/assets/document-list-Cq4rdquK.js +2 -0
- package/dist/assets/{embedding-B5JiUA9X.js → embedding-2EjzoVFT.js} +1 -1
- package/dist/assets/{embedding-B7cWrpy0.js → embedding-BqI3l5RB.js} +1 -1
- package/dist/assets/{form-panel-C34lByEH.js → form-panel-DZj3WZ3z.js} +1 -1
- package/dist/assets/{home-C6aXJsmf.js → home-w5SlrNH7.js} +1 -1
- package/dist/assets/index-DGCnvWMM.js +16 -0
- package/dist/assets/index-XDD8pFI_.css +2 -0
- package/dist/assets/{inferd-config-editor--MDmN_7w.js → inferd-config-editor-CyDCQJRs.js} +1 -1
- package/dist/assets/{key-bindings-BDktmxOD.js → key-bindings-5HbdLjsz.js} +1 -1
- package/dist/assets/{label-Dn4gCMcc.js → label-DJc8-3CQ.js} +1 -1
- package/dist/assets/{lazy-editor-BSRnneOo.js → lazy-editor-Bdm5JEXv.js} +2 -2
- package/dist/assets/{logs-Czn2sPeP.js → logs-DUeiDqCX.js} +1 -1
- package/dist/assets/{offline-COOUcZsG.js → offline-yfQ63Zr7.js} +1 -1
- package/dist/assets/{page-header-DkOHw0g-.js → page-header-BoCaZiqu.js} +1 -1
- package/dist/assets/{public-share-g_wBd6BW.js → public-share-D2S8DEsv.js} +1 -1
- package/dist/assets/{query-debug-CrPsUwT-.js → query-debug-B3pFyO8g.js} +1 -1
- package/dist/assets/registry-BRI7e6jw.js +2 -0
- package/dist/assets/{remotes-CdEU1Y5l.js → remotes-BjjlqN_M.js} +1 -1
- package/dist/assets/{roles-BpVWTMmp.js → roles-BHJYWaBs.js} +1 -1
- package/dist/assets/{roles-Bo9GZdOk.js → roles-CuqCEPC7.js} +1 -1
- package/dist/assets/{settings-TQmRYAGg.js → settings-Btb3SUu6.js} +1 -1
- package/dist/assets/{settings-DJyvE-wf.js → settings-D55sWdd2.js} +1 -1
- package/dist/assets/{settings-Be_a2PGC.js → settings-UMBkdMdX.js} +1 -1
- package/dist/assets/settings-y5FovQxO.js +16 -0
- package/dist/assets/{share-target-BDbVdgTo.js → share-target-5HoF3Y5a.js} +1 -1
- package/dist/assets/{shared-BbAavKdN.js → shared-B24deTOM.js} +1 -1
- package/dist/assets/{shared-BQZGA3ph.js → shared-C-uHNNY8.js} +1 -1
- package/dist/assets/sketch-lazy-BOFTGGTA.js +2 -0
- package/dist/assets/{subtree-transfer-dialog-ChBI5llU.js → subtree-transfer-dialog-BN9xBB9n.js} +1 -1
- package/dist/assets/{text-documents-0P9jkIpu.js → text-documents-CFW8MWES.js} +2 -2
- package/dist/assets/ui-76Hw0NU_.js +41 -0
- package/dist/assets/{use-applet-docs-D5eXpITp.js → use-applet-docs-DBshA7yq.js} +1 -1
- package/dist/assets/use-applet-target-DmIdCxa_.js +1 -0
- package/dist/assets/use-canvas-pins-BZMaPpb7.js +3 -0
- package/dist/assets/{use-menu-BiJ8N7sS.js → use-menu-CaiLyPdw.js} +1 -1
- package/dist/assets/use-settings-back-DE0SPb7h.js +1 -0
- package/dist/assets/{use-sortable-data-BW_0sXBs.js → use-sortable-data-W2inLcb5.js} +1 -1
- package/dist/assets/{use-workspace-identity-BCrrvfeE.js → use-workspace-identity-KxY9injc.js} +1 -1
- package/dist/assets/useAddTarget-D4ra50Am.js +1 -0
- package/dist/assets/{useAgentModels-PQVPjrQu.js → useAgentModels-vTfsjAwS.js} +1 -1
- package/dist/assets/{useDocumentThumbnail-DunxmU1A.js → useDocumentThumbnail-Bs2Ju0eb.js} +1 -1
- package/dist/assets/{useEditNoteFields-BehI0vog.js → useEditNoteFields-CKYMBf8V.js} +1 -1
- package/dist/assets/{users-CKz9kOoR.js → users-DInwKAxz.js} +1 -1
- package/dist/assets/workspace-46EFyEKZ.js +1 -0
- package/dist/assets/{workspace-area-menu-C0-X-FpD.js → workspace-area-menu-COdiU0Xn.js} +1 -1
- package/dist/assets/{workspace-content-gate-9okuA7J7.js → workspace-content-gate-CGZmT2kw.js} +1 -1
- package/dist/assets/{workspace-import-form-aR-DwHf6.js → workspace-import-form-Bu1nlv8u.js} +1 -1
- package/dist/assets/workspaces-BBq3LOwy.js +1 -0
- package/dist/assets/{workspaces-Da_hUIj3.js → workspaces-p959p9BR.js} +1 -1
- package/dist/index.html +36 -36
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/LinkToCard-5dg0jvSY.js +0 -1
- package/dist/assets/ObjectPropertiesCard-BIBMvx_i.js +0 -8
- package/dist/assets/PickDocumentsCard-DamtV7fN.js +0 -1
- package/dist/assets/_contextId_-BEC7o1ya.js +0 -1
- package/dist/assets/_workspaceName_-5rSLTtJT.js +0 -1
- package/dist/assets/agents-jmTwCDAu.js +0 -1
- package/dist/assets/apps-CqFFzo_Z.js +0 -1
- package/dist/assets/backend-sync-progress-pZrhQPk3.js +0 -7
- package/dist/assets/content-app-view-y5TmcjuO.js +0 -1
- package/dist/assets/document-list-DKOU9Kcc.js +0 -2
- package/dist/assets/index-B-PM5mzp.css +0 -2
- package/dist/assets/index-CyEIU2rL.js +0 -16
- package/dist/assets/registry-ZMLdscra.js +0 -2
- package/dist/assets/settings-VF2v3Ya5.js +0 -14
- package/dist/assets/sketch-lazy-C4pjV1WK.js +0 -2
- package/dist/assets/ui-Byg1cZDr.js +0 -41
- package/dist/assets/use-applet-target-gXPvZGgx.js +0 -1
- package/dist/assets/use-canvas-pins-BvN6Gw6f.js +0 -3
- package/dist/assets/use-settings-back-CQauYjQ4.js +0 -1
- package/dist/assets/useAddTarget-CqnDU0Om.js +0 -1
- package/dist/assets/workspace-CrSpR4xf.js +0 -1
- package/dist/assets/workspaces-BGbHBVHs.js +0 -1
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{$r as r,Ct as i,Hr as a,Jn as o,Kn as s,L as c,Nr as l,Nt as u,Q as d,X as f,Y as p,Z as m,Zr as h,_r as g,fn as ee,jn as _,li as v,ri as y,sn as b,st as x,zn as S,zt as te}from"./ui-Byg1cZDr.js";import{t as C}from"./utils-2pl1SbIp.js";import{t as w}from"./button-SgR3GVvV.js";import{t as T}from"./input-BOtCd4HP.js";import{c as ne,t as E}from"./api-CA6WiiYM.js";import{t as D}from"./socket-CtH3EU9m.js";import{n as re}from"./use-toast-BlLDqSUO.js";import{t as ie}from"./LinkToCard-5dg0jvSY.js";import{W as ae,bt as oe,dn as se,fn as ce,gt as O}from"./workspace-CrSpR4xf.js";import{i as le}from"./MessageComposerDialog-gbD0Gu_b.js";import{n as ue}from"./LinkToSidePanel-eCy3nW4R.js";import{t as de}from"./PathPickerField-fZazwxCN.js";var k=e(n(),1);function A(e){return`/workspaces/${e}/hooks`}async function fe(e){return await E.get(A(e))||[]}async function j(e,t){return(await E.get(`${A(e)}/${t}`))?.content??``}async function M(e,t,n){await E.put(`${A(e)}/${t}`,{content:n})}async function N(e,t){await E.delete(`${A(e)}/${t}`)}var pe=[`example-`,`disabled-`,`_`];function P(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function F(e){return pe.find(t=>e.startsWith(t))??null}function me(e){return F(P(e).base)===null}function he(e){return P(e).base.startsWith(`example-`)}function ge(e){let{dir:t,base:n}=P(e),r=F(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function _e(e,t,n){if(me(t)===n)return t;let r=ge(t);return await M(e,r,await j(e,t)),await N(e,t),r}function ve(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 ye(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function be(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function xe(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 Se(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 Ce(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var we=`rules.json`;async function Te(e){try{let t=await j(e,we),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Ee(e,t){await M(e,we,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
2
|
-
`)}async function De(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 E.get(`${A(e)}/pending${r?`?${r}`:``}`)||[]}async function Oe(e,t){return await E.post(`${A(e)}/pending/decisions`,t)}async function ke(e,t){return await E.get(`${A(e)}/runs/${encodeURIComponent(t)}`)}async function Ae(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 E.get(`${A(e)}/runs${r?`?${r}`:``}`)||[]}var I=1e4,je=`canvas.hooks.backfillLimit`;function Me(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?500:Math.min(t,I)}function Ne(){try{let e=localStorage.getItem(je);return e?Me(e):500}catch{return 500}}function Pe(e){let t=Me(e);try{localStorage.setItem(je,String(t))}catch{}return t}function Fe(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 Ie(e,t){return await E.post(`${A(e)}/backfill`,t)}function Le(e,t){return E.post(`${A(e)}/backfill/jobs`,t)}function L(e,t){return E.get(`${A(e)}/backfill/jobs/${t}`)}function Re(e,t){return E.delete(`${A(e)}/backfill/jobs/${t}`)}function ze(e){return E.get(`${A(e)}/backfill/jobs`)}async function R(e,t){return await E.post(`${A(e)}/run`,t)}async function z(e,t){return await E.post(`${A(e)}/runs/${t}/replay`,{})}async function Be(e){return await E.get(`${A(e)}/meta`)}async function Ve(e,t){return await E.post(`${A(e)}/generate`,t)}async function He(e,t){let n=await j(e,we),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 M(e,we,JSON.stringify(o,null,2)+`
|
|
3
|
-
`)}var Ue=He;function We(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 B=`Applying rules to existing documents…`,Ge=new Map;function V(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 Ke(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 H(e,t,n){let r=Ge.get(n.id);if(r)return r;let i=new Promise(r=>{let i={channel:`workspace:${t}`},a=e({title:B,description:V(n),action:{label:`Cancel`,onClick:()=>{a.update({title:`Cancelling…`,description:V(n)}),Re(t,n.id).catch(()=>a.update({title:B,description:`Could not cancel. Try again.`}))}}}),o=()=>{u?.(),D.off(`job.progress`,c),D.off(`job.finished`,c),r()},s=e=>{if(e.status===`running`)return a.update({title:B,description:V(e)});Ke(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=()=>{D.emit(`subscribe`,i),L(t,n.id).then(s,()=>{})},u=D.on(`connect`,l);D.on(`job.progress`,c),D.on(`job.finished`,c),l()});return Ge.set(n.id,i),i.finally(()=>Ge.delete(n.id)),i}async function qe(e,t,n){let r;try{r=await Le(t,{ruleIds:n,limit:Ne()})}catch(t){e({title:B}).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 H(e,t,r)}async function Je(e,t){let n=await ze(t).catch(()=>[]);for(let r of n)r.status===`running`&&H(e,t,r)}function U(e){return`/workspaces/${e}/scripts`}async function Ye(e){return await E.get(U(e))||[]}async function Xe(e,t){return(await E.get(`${U(e)}/${t}`))?.content??``}async function Ze(e,t,n){await E.put(`${U(e)}/${t}`,{content:n})}async function Qe(e,t){await E.delete(`${U(e)}/${t}`)}var W=t(),$e=[{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`}],et=[{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.`}],tt=[{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`}],nt=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),rt=e=>nt.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),it=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:b,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:b,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:b,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:S,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:g,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:o,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:o,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`tag`,label:`add tags`,icon:d,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`},{key:`unstore`,label:`delete the file from a storage backend`,icon:p,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`notify`,label:`Send me a notification`,icon:y,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:m,tone:`text-slate-600 dark:text-slate-300 bg-slate-500/10`},{key:`delete`,label:`delete it from Canvas`,icon:f,tone:`text-destructive bg-destructive/10`},{key:`destroy`,label:`delete it everywhere`,icon:f,tone:`text-destructive bg-destructive/10`}],at=e=>it.find(t=>t.key===e)||it[1],ot=`{{title}}{{ext}}`,G=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,st=[{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.`}],ct=[{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…`}],K=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}),q={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[K(`link`)]},lt=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function ut(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var J=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),dt=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:b,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`,blurb:`Send matching PDF attachments to your accounting firm’s ingestion email, or to a Slack / WhatsApp conversation. Keep the original email and files.`,build:()=>({...q,description:`Send invoice PDFs to accounting`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...K(`sendFile`),sendSource:`attachments`,sendSubject:`Invoice: {{file.name}}`}]})},{id:`attachments`,title:`File PDF email attachments by month`,icon:b,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Choose a recipient and extract PDF attachments into Accounting / year / month, using the email date. Add a subject or filename filter to narrow it to invoices.`,build:()=>({...q,description:`File accounting PDF attachments by month`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...K(`extractAttachments`),a:`workspace:home`,storeFolder:`Accounting`}]})},{id:`store`,title:`Copy/Move file(s) to a storage backend`,icon:S,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})=>({...q,description:`Copy/Move file(s) to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...K(`store`),a:e,recursive:!0}]})},{id:`photos`,title:`Sort photos by date`,icon:_,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})=>({...q,description:`Sort photos by date`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``},{field:`mime`,value:`image/*`}],actions:[{...K(`store`),a:e,storeFolder:`Photos`,storeName:`dated`}]})},{id:`mirror`,title:`Mirror a storage folder`,icon:o,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:()=>({...q,description:`Mirror a storage folder`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:`backends:/workspace/home/`}],actions:[{...K(`link`),a:`dir:/`,recursive:!0}]})},{id:`mail`,title:`File mail from a sender`,icon:b,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Emails from a person or domain are filed into a folder and you get a notification.`,build:()=>({...q,description:`Mail from …`,schema:`email`,conditions:[{field:`from`,value:``}],actions:[{...K(`link`),a:`/work/urgent`},{...K(`notify`),a:`New mail from {{doc.data.from}}: {{doc.data.subject}}`}]})},{id:`download`,title:`Download what links point at`,icon:g,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})=>({...q,description:`Download what links point at`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...K(`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:()=>({...q,description:`Summarize new items`,actions:[{...K(`agent`),b:`Read document #{{doc.id}} in full with canvas_doc_get_by_id, then summarize it in three bullet points.`,notifyReply:!0}]})},{id:`blank`,title:`Start from scratch`,icon:x,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...q})}];function Y(e){let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field));if(t.length!==1||t[0].field!==`eventPathExact`)return null;let n=lt(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function ft(e){if(Y(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>lt(e.value));return t.length>0&&t.every(e=>/^(dir|directory|backends):\//.test(e))}function pt(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=Y(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`?G:e.b||`<filename>`].filter(Boolean).join(`/`)}}function mt(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=nt.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:lt(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${tt.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${tt.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[rt(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=J(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:J(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:J(r),...s,...i?{tags:J(i)}:{}}),n.kind===`unlink`&&r&&o.push({action:`unlink`,paths:J(r),...s}),n.kind===`tag`&&r&&o.push({action:`tag`,tags:J(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&&!ft(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`?ot:n.storeName===`dated`?G: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&&Y(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=J(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:J(i)}:{},...n.dlTags.trim()?{tags:J(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||ut(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 ht(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,...ee}=e.when;if(Object.keys(ee).length>0)return null;let _=Array.isArray(t)?t:[t];if(!_.length||!_.every(e=>typeof e==`string`&&et.some(t=>t.value===e))||n!==void 0&&typeof n!=`string`)return null;let v=[],y=(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)v.push({field:e,value:t})}else if(nt.has(e))for(let t of n){if(!t||typeof t!=`object`||Object.keys(t).length!==1||typeof t.equals!=`string`)return!1;v.push({field:e,value:t.equals})}else if([`from`,`to`,`subject`,`body`,`sender`].includes(e))for(let t of n)if(typeof t==`string`)v.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`)v.push({field:`${e}Exact`,value:t.equals});else if(t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.regex==`string`)v.push({field:`${e}Regex`,value:t.regex});else return!1;else{if(!n.every(e=>typeof e==`string`))return!1;v.push({field:e,value:n.join(` | `)})}return!0};if(d!==void 0&&!y(`path`,d)||f!==void 0&&!y(`pathExact`,f)||p!==void 0&&!y(`eventPathExact`,p)||m!==void 0&&!y(`mime`,m)||r!==void 0&&!y(`from`,r)||i!==void 0&&!y(`to`,i)||a!==void 0&&!y(`subject`,a)||o!==void 0&&!y(`body`,o)||s!==void 0&&!y(`sender`,s)||c!==void 0&&!y(`threadExact`,c)||l!==void 0&&!y(`channelExact`,l)||u!==void 0&&!y(`platformExact`,u)||g!==void 0&&!y(`attachment`,g))return null;if(h!==void 0){if(typeof h==`string`)v.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&&!y(`urlHost`,e.host)||e.contains!==void 0&&!y(`urlContains`,e.contains)||e.regex!==void 0&&!y(`urlRegex`,e.regex))return null}else return null}let b=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}},x=[];for(let t of e.then||[]){if(t.approval!==void 0)return null;if(t.action===`link`&&Array.isArray(t.paths))x.push({...K(`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))x.push({...K(`unlink`),a:t.paths.join(`, `),recursive:t.recursive===!0});else if(t.action===`tag`&&Array.isArray(t.tags))x.push({...K(`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;x.push({...K(`moveMessage`),a:t.folder})}else if(t.action===`notify`&&typeof t.message==`string`)x.push({...K(`notify`),a:t.message});else if(t.action===`store`&&typeof t.to==`string`){if(t.pathMode!==void 0&&(t.pathMode!==`full`||t.recursive!==!0||Y(v)===null)||t.recursive===!0&&Y(v)!==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:``;x.push({...K(`store`),a:t.to,b:e===ot||e===G?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===ot?`title`:e===G?`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;x.push({...K(`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;x.push({...K(`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(!st.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;x.push({...K(`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:``;x.push({...K(`unstore`),a:e(t.from),b:e(t.ifOn),keepLast:t.keepLast!==!1})}else if(t.action===`delete`)x.push(K(`delete`));else if(t.action===`destroy`)x.push(K(`destroy`));else if(t.action===`agent`&&typeof t.slug==`string`&&typeof t.prompt==`string`){let e=b(t);if(!e)return null;x.push({...K(`agent`),a:t.slug,b:t.prompt,...e})}else if(t.action===`script`&&typeof t.path==`string`){let e=b(t);if(!e)return null;x.push({...K(`script`),a:t.path,...e})}else return null}return{id:e.id,description:e.description||``,events:_,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:v,actions:x.length?x:[K(`link`)]}}var gt=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function _t(e,t=$e){let n=e.when,r=ye(e).map(e=>et.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${gt(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 vt(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 yt(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===ot?`, named by title`:e.key===G?`, 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=st.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=vt(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=vt(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function bt(e){return(e.then||[]).map(yt).join(` · `)||`(no actions)`}function xt(e){return be(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function St(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 Ct(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 wt(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function Tt(e){if(e.kind===`document`&&e.rule)return{...ht(e.rule)||q,id:null};if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...q,description:`Download links${t}`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...K(`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{...q,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:[{...K(`store`),a:e.storeTo||``,storeFolder:e.storeFolder||``,recursive:ft(r)}]}}return{...q,description:`Mirror ${e.path} into ${e.target}`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...K(`link`),a:e.target||`dir:/`,recursive:!0}]}}var X=`h-10 w-full rounded-md border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`,Z=`h-10 text-sm`;function Q({label:e,hint:t,children:n,className:r}){return(0,W.jsxs)(`label`,{className:C(`flex min-w-0 flex-col gap-1.5`,r),children:[(0,W.jsx)(`span`,{className:`text-sm font-medium`,children:e}),n,t&&(0,W.jsx)(`span`,{className:`text-xs leading-relaxed text-muted-foreground`,children:t})]})}function $({checked:e,onChange:t,label:n,hint:r,disabled:i}){return(0,W.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:i,onClick:()=>t(!e),className:C(`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,W.jsx)(`span`,{className:C(`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,W.jsx)(`span`,{className:C(`h-4 w-4 rounded-full bg-background shadow transition-transform`,e&&`translate-x-4`)})}),(0,W.jsxs)(`span`,{className:`min-w-0`,children:[(0,W.jsx)(`span`,{className:`block text-sm font-medium`,children:n}),r&&(0,W.jsx)(`span`,{className:`block text-xs leading-relaxed text-muted-foreground`,children:r})]})]})}function Et({value:e,options:t,onChange:n}){return(0,W.jsx)(`div`,{className:`inline-flex h-10 rounded-md border bg-background p-1`,children:t.map(t=>(0,W.jsx)(`button`,{type:`button`,onClick:()=>n(t.value),className:C(`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 Dt({active:e,onClick:t,children:n,title:r}){return(0,W.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:C(`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 Ot({step:e,title:t,hint:n}){return(0,W.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,W.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,W.jsxs)(`div`,{children:[(0,W.jsx)(`h3`,{className:`text-base font-semibold leading-7`,children:t}),n&&(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]})]})}function kt({icon:e,tone:t,size:n=`md`}){return(0,W.jsx)(`span`,{className:C(`inline-flex shrink-0 items-center justify-center rounded-xl`,n===`lg`?`h-12 w-12`:`h-10 w-10`,t),children:(0,W.jsx)(e,{className:n===`lg`?`h-6 w-6`:`h-5 w-5`})})}function At({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:d,onPrefillConsumed:p,createOnly:m=!1,onCreated:g,onCancel:_}){let{showToast:y,showProgress:b}=re(),[S,ne]=(0,k.useState)([]),[E,D]=(0,k.useState)({}),ae=e=>{Ae(e,{limit:500}).then(e=>D(St(e))).catch(()=>D({}))},[se,ce]=(0,k.useState)(!0),[O,A]=(0,k.useState)(null),[fe,j]=(0,k.useState)(!1),[M,N]=(0,k.useState)(!1),[pe,P]=(0,k.useState)([]),[F,me]=(0,k.useState)([]),[he,ge]=(0,k.useState)([]),[_e,ve]=(0,k.useState)(``),ye=(0,k.useRef)(null),[Se,Ce]=(0,k.useState)(e);e!==Se&&(Ce(e),ce(!0)),(0,k.useEffect)(()=>{Te(e).then(e=>ne(e)).finally(()=>ce(!1)),ae(e)},[e]);let[we,De]=(0,k.useState)(null);d!==we&&(De(d),d&&(A(Tt(d)),j(!1))),(0,k.useEffect)(()=>{d&&p?.()},[d,p]),(0,k.useEffect)(()=>{Ye(e).then(e=>P(e.map(e=>e.path))).catch(()=>P([]))},[e]),(0,k.useEffect)(()=>{let t=!1;return le(e).then(e=>{t||(ge([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),ve(``))}).catch(()=>{t||(ge([]),ve(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,k.useEffect)(()=>{oe(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);me(t);let n=wt(t);n&&A(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(()=>me([]))},[e]);let[Oe,ke]=(0,k.useState)($e);(0,k.useEffect)(()=>{Be(e).then(e=>{e.schemas?.length&&ke([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let I=async(t,n)=>{N(!0);try{return await Ee(e,t),ne(t),y({title:n,description:`rules.json updated (committed to workspace git)`}),!0}catch(e){return y({title:`Error`,description:e instanceof Error?e.message:`Failed to save rules`,variant:`destructive`}),!1}finally{N(!1)}},je=async()=>{if(!O||se||M)return;let t;try{t=mt(O,F)}catch(e){y({title:`Invalid rule`,description:e instanceof Error?e.message:`Check the rule conditions and actions`,variant:`destructive`});return}if(!t.then.length){y({title:`Add an action`,description:`Pick at least one "then" action and fill in its fields.`,variant:`destructive`});return}if(m){t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`,N(!0);try{await He(e,t),y({title:`Rule created`,description:`The rule will run for matching new items.`}),g?.()}catch(e){y({title:`Could not create rule`,description:e instanceof Error?e.message:`Failed to save rule`,variant:`destructive`})}finally{N(!1)}return}!O.id&&S.some(e=>e.id===t.id)&&(t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`);let n=O.id?S.map(e=>e.id===O.id?{...t,enabled:e.enabled!==!1}:e):[...S,t];await I(n,O.id?`Rule updated`:`Rule created`)&&(A(null),g?.())},Me=e=>I(S.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),Ne=e=>{confirm(`Delete rule "${e}"?`)&&I(S.filter(t=>t.id!==e),`Rule deleted`)},[Pe,Fe]=(0,k.useState)(null),Le=async t=>{Fe(t);try{let n=await Ie(e,{ruleId:t,dryRun:!0,limit:r}),i=n.results.filter(e=>e.matched).length;if(!i){y({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 qe(b,e,[t])}catch(e){y({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{Fe(null),ae(e)}},L=(e,t)=>A(n=>n&&{...n,[e]:t}),Re=e=>{A(e.build({backend:wt(F)})),j(!1),requestAnimationFrame(()=>ye.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},ze=e=>{let n=ht(e);n?(A(n),j(!1),requestAnimationFrame(()=>ye.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[R,z]=(0,k.useState)(null),Ve=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,Ue=(e,t)=>{if(!R||!O||!e.length){z(null);return}if(R.target===`storeFolder`){let t=xe(e[0]);L(`actions`,O.actions.map((e,n)=>n===R.index?{...e,storeFolder:t?.rel||``,...t?.backend&&F.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(R.target===`condition`){let n=e.map(e=>Ve(e,t)),r=t.treeType===`context`&&O.actions.some(e=>e.kind===`store`);L(`conditions`,O.conditions.map((e,t)=>t===R.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>Ve(e,t));L(`actions`,O.actions.map((e,t)=>t===R.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}z(null)},B=(e,t,n=`Browse…`)=>(0,W.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>z({target:e,index:t}),children:[(0,W.jsx)(s,{className:`h-4 w-4 sm:mr-1.5`}),(0,W.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),Ge=ft(O?.conditions||[]),V=!!O?.conditions.some(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&e.value.trim()),Ke=e=>`${e.address}${e.address===`workspace:data`?` — managed blob store (default)`:e.address===`workspace:home`?` — workspace home folder`:e.driver?` — ${e.driver}`:``}`,H=(e,t,n,r=`workspace:home`)=>F.length?(0,W.jsxs)(`select`,{className:X,value:e,onChange:e=>t(e.target.value),children:[(0,W.jsx)(`option`,{value:``,children:n}),F.map(e=>(0,W.jsx)(`option`,{value:e.address,children:Ke(e)},e.address)),e&&!F.some(t=>t.address===e)&&(0,W.jsx)(`option`,{value:e,children:e})]}):(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),Je=S.filter(xt),U=S.filter(e=>!xt(e)),Xe=({rule:e})=>{let t=e.enabled!==!1,r=ht(e)!==null,i=E[e.id],a=at(e.then?.[0]?.action||`link`),o=be(e);return(0,W.jsxs)(`div`,{className:C(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,W.jsx)(kt,{icon:a.icon,tone:a.tone}),(0,W.jsxs)(`div`,{className:`rule-card-content min-w-0 space-y-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,W.jsx)(`h3`,{className:`text-base font-semibold leading-6`,children:e.description||e.id}),e.approval===!0&&(0,W.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,W.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:`incl. automation-created`}),!r&&(0,W.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,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:_t(e,Oe)}),(0,W.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,W.jsx)(v,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,W.jsx)(`span`,{children:bt(e)})]}),o.length>0&&(0,W.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:o.join(` | `),children:o.join(` | `)}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?(0,W.jsxs)(`button`,{type:`button`,className:C(`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,` `,Ct(i.last.ts)]}):`not run yet`})]}),(0,W.jsxs)(`div`,{className:`rule-card-actions`,children:[(0,W.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t,disabled:M,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>Me(e.id),className:C(`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,W.jsx)(`span`,{className:C(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,W.jsxs)(w,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:e.when.eventPathExact===void 0?`Apply this rule to existing items (dry-run first)`:`Requires an original insert/link event. Current folder membership cannot reconstruct its destination.`,disabled:Pe!==null||e.when.eventPathExact!==void 0,onClick:()=>Le(e.id),children:[Pe===e.id?(0,W.jsx)(ee,{className:`h-4 w-4 animate-spin`}):(0,W.jsx)(l,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Apply`})]}),(0,W.jsxs)(w,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>ze(e),children:[r?(0,W.jsx)(te,{className:`h-4 w-4`}):(0,W.jsx)(h,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,W.jsx)(w,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>Ne(e.id),children:(0,W.jsx)(f,{className:`h-4 w-4`})})]})]})},Ze=(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,W.jsx)(`h3`,{className:`text-base font-semibold`,children:`What should happen automatically?`}),fe&&(0,W.jsxs)(w,{size:`sm`,variant:`ghost`,onClick:()=>j(!1),children:[(0,W.jsx)(c,{className:`mr-1 h-4 w-4`}),` Close`]})]}),(0,W.jsx)(`div`,{className:`grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,17rem),1fr))] gap-3`,children:dt.map(e=>(0,W.jsxs)(`button`,{type:`button`,onClick:()=>Re(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,W.jsx)(kt,{icon:e.icon,tone:e.tone,size:`lg`}),(0,W.jsxs)(`span`,{className:`min-w-0`,children:[(0,W.jsx)(`span`,{className:`block text-base font-semibold leading-6`,children:e.title}),(0,W.jsx)(`span`,{className:`mt-1 block break-words text-sm leading-relaxed text-muted-foreground`,children:e.blurb})]})]},e.id))})]});return(0,W.jsxs)(`div`,{className:`rule-builder min-w-0 space-y-5`,children:[!m&&(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,W.jsxs)(`div`,{className:`min-w-0 flex-[1_1_20rem]`,children:[(0,W.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Rules`}),(0,W.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Rules run automatically as items arrive or get filed — no code needed. Stored in`,` `,(0,W.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` in the workspace git.`]})]}),(0,W.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[t&&(0,W.jsxs)(w,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,W.jsx)(h,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,W.jsxs)(w,{onClick:()=>{A(null),j(!0)},disabled:fe,children:[(0,W.jsx)(u,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),fe&&!O&&Ze,O&&(0,W.jsxs)(`div`,{ref:ye,className:`scroll-mt-4 space-y-6 rounded-xl border bg-card p-4 sm:p-6`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,W.jsx)(`h3`,{className:`text-lg font-semibold`,children:O.id?`Edit rule`:`New rule`}),(0,W.jsxs)(w,{variant:`ghost`,size:`sm`,onClick:()=>A(null),children:[(0,W.jsx)(c,{className:`mr-1 h-4 w-4`}),` Cancel`]})]}),(0,W.jsx)(Q,{label:`Name`,hint:`Shown in the list and the run log.`,children:(0,W.jsx)(T,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:O.description,onChange:e=>L(`description`,e.target.value)})}),(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsx)(Ot,{step:1,title:`When…`,hint:`What the rule reacts to. All conditions must match; repeat a condition for either/or.`}),(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-[minmax(0,220px)_1fr]`,children:[(0,W.jsx)(Q,{label:`Item`,children:(0,W.jsxs)(`select`,{className:X,value:O.schema,onChange:e=>L(`schema`,e.target.value),children:[Oe.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value)),O.schema&&!Oe.some(e=>e.value===O.schema)&&(0,W.jsx)(`option`,{value:O.schema,children:O.schema.replace(/^data\/schema\//,``)})]})}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Event `,(0,W.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(any of)`})]}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:et.map(e=>{let t=O.events.includes(e.value);return(0,W.jsx)(Dt,{active:t,title:e.hint,onClick:()=>{let n=t?O.events.filter(t=>t!==e.value):[...O.events,e.value];n.length&&L(`events`,n)},children:e.label},e.value)})})]})]}),O.conditions.length>0&&(0,W.jsx)(`div`,{className:`space-y-2`,children:O.conditions.map((e,t)=>{let n=tt.find(t=>t.key===e.field);return(0,W.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,W.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:O.conditions.slice(0,t).some(t=>rt(t.field)===rt(e.field))?`or`:`and`}),(0,W.jsx)(`select`,{className:X,value:e.field,onChange:e=>L(`conditions`,O.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:tt.map(e=>(0,W.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,W.jsxs)(`div`,{className:`order-4 col-span-3 flex gap-2 sm:order-3 sm:col-span-1`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>L(`conditions`,O.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&B(`condition`,t,`Browse the workspace trees`)]}),(0,W.jsx)(w,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>L(`conditions`,O.conditions.filter((e,n)=>n!==t)),children:(0,W.jsx)(c,{className:`h-4 w-4`})})]},t)})}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,W.jsxs)(w,{size:`sm`,variant:`outline`,onClick:()=>L(`conditions`,[...O.conditions,{field:O.schema===`email`?`from`:`path`,value:``}]),children:[(0,W.jsx)(u,{className:`mr-1 h-4 w-4`}),` Add condition`]}),(0,W.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,W.jsx)(`span`,{className:`font-mono`,children:`|`}),`, e.g. `,(0,W.jsx)(`span`,{className:`font-mono`,children:`image/* | video/*`}),`.`]})]})]}),(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsx)(Ot,{step:2,title:`Then…`,hint:`Actions run in order. The item keeps its id, tags and folders unless an action says otherwise.`}),O.actions.map((t,n)=>{let r=e=>L(`actions`,O.actions.map((t,r)=>r===n?{...t,...e}:t)),i=F.find(e=>e.address===t.a),o=i?.capabilities?.paths===!0,s=Ge&&o,l=at(t.kind),u=n=>(0,W.jsxs)(`div`,{className:`space-y-3 rounded-lg border border-dashed p-3`,children:[(0,W.jsxs)(`p`,{className:`text-sm font-medium`,children:[`What to do with the `,n]}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Save as a note at`,hint:`Context path by default, dir:/path for the directory tree.`,children:(0,W.jsx)(de,{inputClassName:Z,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,W.jsx)(Q,{label:`Note title`,children:(0,W.jsx)(T,{className:Z,placeholder:`Summary: {{doc.data.subject}}`,value:t.noteTitle,onChange:e=>r({noteTitle:e.target.value})})}),(0,W.jsx)(Q,{label:`Save as a file at`,hint:`Relative path under the workspace home folder or in the data blob store.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`logs/agent.log (optional)`,value:t.filePath,onChange:e=>r({filePath:e.target.value})})}),t.filePath.trim()&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(Q,{label:`File lives in`,children:(0,W.jsxs)(`select`,{className:X,value:t.fileBackend,onChange:e=>r({fileBackend:e.target.value}),children:[(0,W.jsx)(`option`,{value:`home`,children:`the workspace home folder`}),(0,W.jsx)(`option`,{value:`data`,children:`the data blob store`})]})}),(0,W.jsx)(Q,{label:`Also file the saved file under`,hint:`Index it as a document at this tree path.`,children:(0,W.jsx)(de,{inputClassName:Z,placeholder:`/path (optional)`,value:t.fileInsert,onChange:e=>r({fileInsert:e}),fixedWorkspaceName:e,tabs:[`context`],pickerTitle:`File under…`,onPickTarget:e=>r({fileInsert:e})})})]})]}),(0,W.jsx)($,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send me a notification with the result`})]}),d=Y(O.conditions),f=t.kind===`store`&&t.a&&(!t.recursive||s)?pt(t,O.conditions,i):null,p=t.kind===`extractAttachments`&&t.a?We(t.a,t.storeFolder,t.attachmentPath):null;return(0,W.jsxs)(`div`,{className:`space-y-4 rounded-xl border bg-background p-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,W.jsx)(kt,{icon:l.icon,tone:l.tone}),(0,W.jsx)(`select`,{className:C(X,`flex-1 font-medium`),value:t.kind,onChange:e=>r(K(e.target.value)),children:it.map(e=>(0,W.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,W.jsx)(w,{size:`sm`,variant:`ghost`,className:`h-10 w-10 shrink-0 p-0 text-muted-foreground`,title:`Remove action`,disabled:O.actions.length===1,onClick:()=>L(`actions`,O.actions.filter((e,t)=>t!==n)),children:(0,W.jsx)(c,{className:`h-4 w-4`})})]}),(t.kind===`link`||t.kind===`unlink`)&&(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsx)(Q,{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,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`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})}),B(`action`,n)]})}),t.kind===`link`&&(0,W.jsx)(Q,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,W.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:V?`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:!V})]}),t.kind===`moveMessage`&&(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsx)(Q,{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,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`INBOX/Accounting/{{YYYY}}/Expenses`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,W.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,W.jsx)(Q,{label:`Tags`,hint:`Comma-separated.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`urgent, follow-up`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`store`&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Storage backend`,hint:`Where the file's bytes should live. Only writable backends are listed.`,children:H(t.a,e=>r({a:e}),`pick a backend…`)}),(0,W.jsx)(Q,{label:`Destination root folder`,hint:`Choose the folder beneath which the path will be recreated. Leave empty to use the backend root.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),B(`storeFolder`,n,`Browse storage backends`)]})}),(0,W.jsx)(Q,{label:`File name`,children:(0,W.jsx)(`select`,{className:X,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:ct.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,W.jsx)(Q,{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,W.jsx)(Et,{value:t.storeMode,onChange:e=>r({storeMode:e}),options:[{value:`copy`,label:`Copy`},{value:`move`,label:`Move`}]})}),t.storeMode===`move`&&(0,W.jsx)(Q,{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:H(t.storeFrom,e=>r({storeFrom:e}),`choose a source backend…`,`workspace:data`)}),t.storeName===`custom`&&(0,W.jsx)(Q,{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,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,W.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:d===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:o?Ge?d===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:${d} 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:!s&&!t.recursive}),f&&(0,W.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,W.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,W.jsxs)(`span`,{className:`break-all font-mono`,children:[f.root,`/`]})]}),t.recursive&&(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,W.jsxs)(`span`,{className:`break-all font-mono`,children:[f.recreated||`(root)`,`/`]})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:f.result})]}),(0,W.jsxs)(`details`,{className:`group rounded-lg border`,children:[(0,W.jsxs)(`summary`,{className:`flex cursor-pointer select-none items-center gap-2 px-3 py-2 text-sm font-medium`,children:[(0,W.jsx)(a,{className:`h-4 w-4 transition-transform group-open:rotate-180`}),` More options`]}),(0,W.jsxs)(`div`,{className:`grid gap-4 border-t p-3 sm:grid-cols-2`,children:[t.storeMode===`copy`&&(0,W.jsx)(Q,{label:`Copy bytes from`,hint:`Optional source restriction. Default: any readable copy outside the destination backend.`,children:H(t.storeFrom,e=>r({storeFrom:e}),`any readable source`,`workspace:data (optional)`)}),(0,W.jsx)(Q,{label:`If the name is already taken`,children:(0,W.jsxs)(`select`,{className:X,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,W.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,W.jsx)(`option`,{value:`error`,children:`skip the file`}),(0,W.jsx)(`option`,{value:`overwrite`,children:`overwrite the existing file`})]})})]})]}),(0,W.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,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Attachment types`,hint:`MIME types, comma-separated. application/pdf for PDFs, image/* for images, or * for all.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`application/pdf`,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,W.jsx)(Q,{label:`Attachment filename contains`,hint:`Optional: invoice, faktura, or another literal filename fragment. Every selected attachment must also match its type.`,children:(0,W.jsx)(T,{className:Z,placeholder:`Any matching filename`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})}),(0,W.jsx)(Q,{label:`Storage backend`,hint:`Choose a writable backend that supports folder paths.`,children:H(t.a,e=>r({a:e}),`pick a backend…`)}),(0,W.jsx)(Q,{label:`Destination root folder`,hint:`Choose the folder beneath which date subfolders will be created. Leave empty to use the backend root.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),B(`storeFolder`,n,`Browse storage backends`)]})}),(0,W.jsx)(Q,{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,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`No subfolders`,value:t.attachmentPath,onChange:e=>r({attachmentPath:e.target.value})})}),(0,W.jsx)(Q,{label:`If the attachment name is already taken`,children:(0,W.jsxs)(`select`,{className:X,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,W.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,W.jsx)(`option`,{value:`error`,children:`skip the file and report the conflict`})]})})]}),!o&&(0,W.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.`}),p&&(0,W.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,W.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Example email dated `,p.date,`. Each email supplies its own date.`]}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,W.jsxs)(`span`,{className:`break-all font-mono`,children:[p.root,`/`]})]}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,W.jsx)(`span`,{className:`break-all font-mono`,children:p.added?`${p.added}/`:`(none)`})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:p.result})]}),(0,W.jsx)($,{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,W.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,W.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,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Download`,hint:st.find(e=>e.value===t.dlKind)?.hint,children:(0,W.jsx)(`select`,{className:X,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:st.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),t.dlKind===`website`?(0,W.jsx)(Q,{label:`Mirror depth`,hint:`How many link hops to follow on the same site (1–5).`,children:(0,W.jsx)(T,{type:`number`,min:1,max:5,className:C(Z,`sm:max-w-32`),value:t.dlDepth,onChange:e=>r({dlDepth:e.target.value})})}):(0,W.jsx)(`div`,{className:`hidden sm:block`}),(0,W.jsx)(Q,{label:`Storage backend`,hint:`Where the downloaded file's bytes should live.`,children:H(t.a,e=>r({a:e}),`workspace:home (default)`)}),(0,W.jsx)(Q,{label:`Folder on that backend`,hint:`Relative to the backend root.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),B(`storeFolder`,n,`Browse storage backends`)]})}),(0,W.jsx)(Q,{label:`File the download under`,hint:`Leave empty to file it in the same folder(s) as the link. Comma-separate several.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),B(`action`,n)]})}),(0,W.jsx)(Q,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,W.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:V?`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:!V}),(0,W.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,W.jsx)(`span`,{className:`font-mono`,children:`yt-dlp`}),`, pages and websites `,(0,W.jsx)(`span`,{className:`font-mono`,children:`wget`}),` on the server.`]})]}),t.kind===`unstore`&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Delete the file from`,children:H(t.a,e=>r({a:e}),`pick a backend…`,`workspace:data`)}),(0,W.jsx)(Q,{label:`…but only once it is also on`,hint:`Safety: the copy is dropped only after another backend holds the file.`,children:H(t.b,e=>r({b:e}),`anywhere else`,`workspace:home (optional)`)})]}),(0,W.jsx)($,{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,W.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,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsx)(Q,{label:`Files to send`,children:(0,W.jsxs)(`select`,{className:X,value:t.sendSource,onChange:e=>r({sendSource:e.target.value}),children:[(0,W.jsx)(`option`,{value:`document`,children:`The file that triggered this rule`}),(0,W.jsx)(`option`,{value:`attachments`,children:`Matching attachments from the email`}),(0,W.jsx)(`option`,{value:`download`,children:`Files from an earlier Download action`})]})}),t.sendSource===`attachments`&&(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Attachment types`,hint:`application/pdf for invoices; * for all files.`,children:(0,W.jsx)(T,{className:Z,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,W.jsx)(Q,{label:`Attachment filename contains`,hint:`Optional literal filename fragment.`,children:(0,W.jsx)(T,{className:Z,placeholder:`invoice`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})})]}),t.sendSource===`attachments`&&(0,W.jsx)($,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Signature images are excluded by default.`}),(0,W.jsx)(Q,{label:`Sending account`,hint:`Enable sending for the account in Connected services.`,children:(0,W.jsxs)(`select`,{className:X,value:t.a?`${t.sendDriver}:${t.a}`:``,onChange:e=>{let t=he.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&r({a:t.address,sendDriver:t.driver,b:``})},children:[(0,W.jsx)(`option`,{value:``,disabled:!0,children:`Choose email, WhatsApp or Slack…`}),t.a&&!he.some(e=>e.driver===t.sendDriver&&e.address===t.a)&&(0,W.jsxs)(`option`,{value:`${t.sendDriver}:${t.a}`,disabled:!0,children:[t.sendDriver,`: `,t.a,` (unavailable)`]}),he.map(e=>(0,W.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}`))]})}),_e&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:_e}),(0,W.jsx)(Q,{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,W.jsx)(T,{className:Z,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,W.jsx)(Q,{label:`Email subject`,hint:`{{file.name}} inserts the attachment filename.`,children:(0,W.jsx)(T,{className:Z,value:t.sendSubject,onChange:e=>r({sendSubject:e.target.value})})}),(0,W.jsx)(Q,{label:t.sendDriver===`imap`?`Email body (optional)`:`Message / caption (optional)`,hint:`Templates: {{file.name}}, {{doc.data.subject}}, {{doc.data.title}}.`,children:(0,W.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,W.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,W.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,W.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,W.jsx)(Q,{label:`Notification`,hint:`Notifies you through your bound channel, or in Canvas. Templates: {{doc.data.subject}}, {{doc.data.from}}, {{doc.data.title}}…`,children:(0,W.jsx)(T,{className:Z,placeholder:`New mail from {{doc.data.from}}: {{doc.data.subject}}`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`delete`&&(0,W.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,W.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,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsx)(Q,{label:`Agent`,hint:`The agent's slug.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono sm:max-w-xs`),placeholder:`assistant`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,W.jsx)(Q,{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_doc_get_by_id for full email content. Objects are inserted as JSON.`,children:(0,W.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_doc_get_by_id and summarize it in plain markdown.
|
|
4
|
-
|
|
5
|
-
Subject: {{doc.data.subject}}
|
|
6
|
-
Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})}),u(`reply`)]}),t.kind===`script`&&(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsx)(Q,{label:`Script`,hint:`From the Scripts section of this workspace.`,children:pe.length?(0,W.jsxs)(`select`,{className:C(X,`font-mono sm:max-w-md`),value:t.a,onChange:e=>r({a:e.target.value}),children:[(0,W.jsx)(`option`,{value:``,children:`pick a script…`}),pe.map(e=>(0,W.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,W.jsx)(T,{className:C(Z,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),u(`output`)]})]},n)}),(0,W.jsxs)(w,{size:`sm`,variant:`outline`,onClick:()=>L(`actions`,[...O.actions,K(`tag`)]),children:[(0,W.jsx)(u,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,W.jsxs)(`section`,{className:`space-y-3`,children:[(0,W.jsx)(Ot,{step:3,title:`Options`}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsx)($,{checked:O.approval,onChange:e=>L(`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,W.jsx)($,{checked:O.cascade,onChange:e=>L(`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,W.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,W.jsxs)(w,{className:`h-10 px-5`,onClick:je,disabled:M||se,children:[M?(0,W.jsx)(ee,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,W.jsx)(i,{className:`mr-1.5 h-4 w-4`}),` `,O.id?`Save changes`:`Create rule`]}),(0,W.jsx)(w,{className:`h-10`,variant:`outline`,onClick:()=>{A(null),_?.()},children:`Cancel`})]})]}),R&&(0,W.jsx)(ue,{onClose:()=>z(null),children:(0,W.jsx)(ie,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:R.target!==`storeFolder`&&!(R.target===`condition`&&O?.actions.some(e=>e.kind===`store`)),tabs:R.target===`condition`?[`context`,`directory`,`backends`]:R.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:R.target===`condition`?`Choose source folder…`:R.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:R.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:Ue,onClose:()=>z(null)})}),!m&&(se?(0,W.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):S.length===0?!fe&&!O&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`rounded-xl border border-dashed p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-base font-medium`,children:`No rules yet`}),(0,W.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…”.`})]}),Ze]}):(0,W.jsxs)(`div`,{className:`space-y-6`,children:[Je.length>0&&(0,W.jsxs)(`section`,{className:`space-y-3`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-sm text-muted-foreground`,children:[(0,W.jsxs)(`h3`,{className:`flex items-center gap-2 font-semibold uppercase tracking-wide`,children:[(0,W.jsx)(o,{className:`h-4 w-4 shrink-0`}),` Folder & storage rules`]}),(0,W.jsx)(`p`,{children:`Right-click a folder in the tree to add one`})]}),(0,W.jsx)(`div`,{className:`space-y-3`,children:Je.map(e=>(0,W.jsx)(Xe,{rule:e},e.id))})]}),U.length>0&&(0,W.jsxs)(`section`,{className:`space-y-3`,children:[Je.length>0&&(0,W.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,W.jsx)(x,{className:`h-4 w-4`}),` Other rules`]}),(0,W.jsx)(`div`,{className:`space-y-3`,children:U.map(e=>(0,W.jsx)(Xe,{rule:e},e.id))})]})]}))]})}function jt(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 Mt(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function Nt(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 Pt=(e,t)=>`${ne.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Ft(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await E.get(`${Pt(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 It(e,t,n){return Rt(e,t,n,`restore`)}function Lt(e,t,n){return Rt(e,t,n,`discard`)}async function Rt(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await E.post(`${Pt(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{O(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 zt(e,t){let n=jt(`backends`,t);if(!n?.backend)return;let{items:r}=await Ft(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 It(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 Bt(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
|
|
7
|
-
`)+(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 Vt(e,t){let n=jt(`backends`,t);if(!n?.backend)return;let{items:r}=await Ft(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Bt(n.backend,i))return;let a=await Lt(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.`}`)}var Ht=new Map;function Ut(e,t,n,r,i,a){let o=JSON.stringify([t,n,r,a]),s=Ht.get(o);if(s)return s;let c=(async()=>{let o=e({title:`Resyncing…`,description:r});try{for(a?await ce(t,n,r,a):await se(t,n,r);;){let e=await ae(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 Ht.set(o,c),c.finally(()=>{Ht.get(o)===c&&Ht.delete(o)}).catch(()=>{}),c}export{ke as A,R as B,Ce as C,j as D,Ne as E,fe as F,Pe as H,De as I,Ae as L,Fe as M,he as N,Be as O,me as P,z as R,Oe as S,Ve as T,_e as U,M as V,xe as W,qe as _,Ft as a,Ie as b,jt as c,At as d,Qe as f,Je as g,Ze as h,Vt as i,ve as j,Te as k,Mt as l,Ye as m,Bt as n,It as o,Xe as p,Lt as r,zt as s,Ut as t,Nt as u,I as v,N as w,Me as x,Ue as y,Se as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{h as r}from"./chunk-62JRHF6Z-vspAGgtK.js";import{Br as i,Ct as a,G as o,It as s,L as c,Lt as l,Nt as u,St as d,Tr as f,Ut as p,X as m,Yr as h,ct as g,it as _,mn as v,mt as y,ti as b,tt as x,vn as S,yn as C}from"./ui-Byg1cZDr.js";import{t as w}from"./utils-2pl1SbIp.js";import{An as T,Vn as E,q as D}from"./workspace-CrSpR4xf.js";import{t as O}from"./TodosWidget-CxiqmDuJ.js";import{d as ee,o as te,u as ne}from"./ObjectPropertiesCard-BIBMvx_i.js";import{h as re,s as ie,t as ae,u as oe}from"./document-list-DKOU9Kcc.js";import{n as se,r as ce}from"./use-toolbox-Ck_cLGgf.js";import{t as le}from"./useToastHelpers-CRrpIIdY.js";import{n as k}from"./color-DFEH4BfK.js";import{t as ue}from"./DocumentIcon-x299QNu_.js";import{r as de}from"./workspace-BydSRtST.js";import{t as fe}from"./registry-ZMLdscra.js";import{t as A}from"./FileForm-CqJpRbXv.js";import{t as j}from"./applet-target-C_gBgU-Z.js";var M=e(n(),1);function pe(e){let{pathname:t}=r(),n=ce()?.setAgentView,i=JSON.stringify(e);(0,M.useEffect)(()=>(n?.({pathname:t,view:JSON.parse(i)}),()=>n?.(null)),[t,i,n])}function me(e,t,n,r){return structuredClone({...e,query:de(t,n,r),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}var N=t();function he({target:e,children:t}){let[n,r]=(0,M.useState)([]),i=(0,M.useRef)(!1),[a,o]=(0,M.useState)(!1),[s,c]=(0,M.useState)(!1),[l,u]=(0,M.useState)(null),{showErrorToast:d}=le();return(0,N.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0 bg-background ${a?`ring-2 ring-inset ring-primary`:``}`,onDragOverCapture:t=>{s||!e||!Array.from(t.dataTransfer.types).includes(`Files`)||(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=i.current?`none`:`copy`,o(!i.current))},onDragLeaveCapture:e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)},onDropCapture:t=>{if(s||!e||!Array.from(t.dataTransfer.types).includes(`Files`))return;if(t.preventDefault(),t.stopPropagation(),o(!1),i.current){d(`Wait for the current upload to finish`);return}let n=Array.from(t.dataTransfer.files);if(!n.length){d(`Drop files rather than folders`);return}r(n),u(e),c(!0)},children:[t,a&&(0,N.jsxs)(`div`,{className:`pointer-events-none absolute inset-0 z-30 flex items-center justify-center bg-background/80 text-sm font-medium`,children:[`Drop files to upload to `,e?.mode===`workspace`?e.path:`this context`]}),s&&(0,N.jsxs)(oe,{label:`Import files`,onClose:()=>{i.current||c(!1)},children:[(0,N.jsx)(`h2`,{className:`border-b px-4 py-3 text-sm font-medium`,children:`Import files`}),(0,N.jsx)(A,{target:l,initialFiles:n,onClose:()=>c(!1),onBusyChange:e=>{i.current=e}})]})]})}function ge({navigationTabs:e,navigationActions:t,onBack:n,accentColor:r,frameContent:i=!0,urlType:c,urlDisplay:u,contextPath:d,treeName:f,workspaceId:p,workspaceLabel:h,workspaceIcon:g,documentSchema:_,documents:v,isLoading:x,totalCount:S,currentPage:w,pageSize:T,onPageChange:E,onPageSizeChange:D,onRemoveDocument:O,onDeleteDocument:ie,onDestroyDocument:oe,onRemoveDocuments:ce,onDeleteDocuments:le,onDestroyDocuments:k,onCopyDocuments:ue,onCutDocuments:de,onPasteDocuments:fe,onImportDocuments:A,onSelectionChange:j,pastedDocumentIds:pe,onPurgeDocuments:me,disablePurgeDocuments:ge,canvasInfo:P,isCanvasPinned:F,onTogglePinCanvas:I,onSaveAsCanvas:L,onShareCanvas:R,onUnshareCanvas:z,onDeleteCanvas:B,isSharingCanvas:V,isDeletingCanvas:H,isCanvasShared:U,isCanvasLocked:W,backendSearchQueries:G,onBackendSearch:K,onRemoveBackendQuery:_e,serverSort:ve,onServerSortChange:ye,scope:be,onScopeChange:xe,canSaveChanges:Se,isSavingChanges:q,onSaveChanges:J,onBrowseWorkspaces:Ce,onBrowseTree:we,onNavigatePath:Te,linkTree:Ee,children:Y,contentBanner:De,folders:Oe,onOpenFolder:ke}){let Ae=c===`canvas`,X=re(),{state:je,toggleView:Me,hasActiveFilters:Ne,openAddPicker:Pe}=se(),Z=te(),[Fe,Q]=(0,M.useState)(``),$=JSON.stringify([p,f,d,_]),[Ie,Le]=(0,M.useState)($);Ie!==$&&(Le($),Q(``));let Re=(0,N.jsxs)(N.Fragment,{children:[t,L&&(0,N.jsx)(`button`,{type:`button`,onClick:L,title:`Save as canvas`,"aria-label":`Save as canvas`,className:`flex h-control-sm w-control-sm shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent touch-target`,children:(0,N.jsx)(b,{className:`h-4 w-4`})})]});return(0,N.jsxs)(he,{target:A&&p?{mode:`workspace`,workspaceName:p,path:d,treeName:f||`context`,treeType:f===`directory`?`directory`:`context`}:null,children:[e&&!X&&(0,N.jsx)(ee,{accentColor:r,children:e}),(0,N.jsxs)(`div`,{className:`canvas-surface-body${i&&!X?` is-framed`:``}`,children:[(0,N.jsx)(ne,{workspaceIcon:g,workspace:h||p||u.split(`://`)[0]||`Workspace`,actions:X&&e?(0,N.jsxs)(`details`,{className:`relative shrink-0`,"aria-label":`Canvas views`,children:[(0,N.jsx)(`summary`,{className:`cursor-pointer rounded-md border px-2 py-1 text-xs`,title:`Choose or manage content views`,children:`Views`}),(0,N.jsx)(`div`,{className:`absolute right-0 top-full z-30 mt-2 min-w-64 max-w-[80vw] rounded-md border bg-background p-2 shadow-lg`,children:e})]}):void 0,tree:f?`${f}${c.endsWith(`-layer`)?`:layer`:``}`:c.replace(`-layer`,``),path:d,accentColor:r,onBack:Z.location?Z.location.section===`view`?Z.close:()=>Z.update?.({section:`view`}):n,section:Z.location?`document/${Z.location.documentId}/${Z.location.section}`:void 0,onSection:Z.location?()=>Z.update?.({section:`view`}):void 0,onBrowseWorkspaces:Ce,onBrowseTree:we,onNavigatePath:Te,onFilter:()=>Me(`tools`),filtersActive:Ne,filtersOpen:je.t1Open&&je.t1View===`tools`,onAdd:e=>Pe({modal:e.shiftKey,fresh:!0}),search:K||!Y?{workspaceId:p,queries:G||[],onSearch:K??Q,localOnly:!K,onRemoveQuery:_e,scope:be,onScopeChange:xe}:void 0,onDraftChange:Y?void 0:Q}),Ae&&P?(0,N.jsx)(N.Fragment,{children:(0,N.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[P.color&&(0,N.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:P.color}}),(0,N.jsx)(C,{className:`w-4 h-4 shrink-0 text-primary`}),(0,N.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,N.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:P.label||u.split(`://`)[1]||`Canvas`}),P.description&&(0,N.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:P.description})]}),Se&&J&&(0,N.jsxs)(`button`,{type:`button`,onClick:J,disabled:q,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:`Save filters`,children:[(0,N.jsx)(a,{className:`w-3 h-3`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:q?`Saving...`:`Save filters`})]}),I&&(0,N.jsxs)(`button`,{type:`button`,onClick:I,"aria-pressed":!!F,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground`,title:F?`Unpin from home`:`Pin to home`,children:[F?(0,N.jsx)(l,{className:`w-3 h-3`}):(0,N.jsx)(s,{className:`w-3 h-3`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:F?`Unpin`:`Pin`})]}),R&&(0,N.jsxs)(`button`,{type:`button`,onClick:R,disabled:V||H,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:U?`Copy public link`:`Share canvas`,children:[(0,N.jsx)(y,{className:`w-3 h-3`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:V?`Sharing...`:U?`Copy link`:`Share`})]}),U&&z&&(0,N.jsxs)(`button`,{type:`button`,onClick:z,disabled:V||H,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,N.jsx)(o,{className:`w-3 h-3`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),B&&(0,N.jsxs)(`button`,{type:`button`,onClick:B,disabled:H||W&&!U,title:W&&!U?`Unlock this canvas before deleting it`:`Delete canvas`,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,N.jsx)(m,{className:`w-3 h-3`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:H?`Deleting…`:`Delete`})]})]})}):null,Y&&(L||t)&&(0,N.jsx)(`div`,{className:`flex items-center gap-2 border-b px-3 py-1`,children:Re}),(0,N.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[De,Y||(0,N.jsx)(ae,{readingPane:!0,externalSearchQuery:Fe,toolbarActions:Re,documents:_?v.filter(e=>e.schema===_):v,isLoading:x,folders:_?void 0:Oe,onOpenFolder:ke,contextPath:d,treeName:f,workspaceId:p,totalCount:S,viewMode:_?`card`:`table`,allowViewToggle:!0,currentPage:w,pageSize:T,onPageChange:E,onPageSizeChange:D,onRemoveDocument:O,onDeleteDocument:ie,onDestroyDocument:oe,onRemoveDocuments:ce,onDeleteDocuments:le,onDestroyDocuments:k,onCopyDocuments:ue,onCutDocuments:de,onPasteDocuments:fe,onImportDocuments:A,onSelectionChange:j,pastedDocumentIds:pe,onPurgeDocuments:_?void 0:me,disablePurgeDocuments:ge,backendSearchQueries:G,onBackendSearch:K,serverSort:ve,onServerSortChange:ye,onRemoveBackendQuery:_e,scope:be,onScopeChange:xe,canSaveChanges:!Ae&&Se,isSavingChanges:q,onSaveChanges:J,linkTree:Ee},_??`documents`)]})]})]})}var P=[{id:`todos`,label:`Todo list`},{id:`todo-app`,label:`Todo App`},{id:`notes`,label:`Notes list`},{id:`notes-app`,label:`Notes App`},{id:`sketch`,label:`Sketch`},{id:`terminal`,label:`Terminal`}];function F(e){return e?.kind===`app`&&e.app===`notes`?`data/schema/note`:void 0}var I={id:`default`,name:`All`,kind:`documents`};function L(){return[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}]}function R(e){let t=e?.views;if(!Array.isArray(t))return[I];let n=t.filter(e=>{let t=e;return!t||typeof t.id!=`string`||typeof t.name!=`string`?!1:t.kind===`documents`||t.kind===`columns`||t.kind===`app`&&(P.some(e=>e.id===t.app)||t.app===`filters`||t.app===`lens`)});return n.length>0?n:[I]}var z={todos:v,"todo-app":v,notes:x,"notes-app":x,filters:g,sketch:_,Brush:h,terminal:_,lens:d};function B({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let[l,d]=(0,M.useState)(null),[m,h]=(0,M.useState)(``),[g,_]=(0,M.useState)(!1),[v,y]=(0,M.useState)(null),[b,x]=(0,M.useState)(null),C=(0,M.useRef)(null);(0,M.useEffect)(()=>{let e=C.current;if(!e)return;let t=t=>{if(t.ctrlKey||e.scrollWidth<=e.clientWidth)return;let n=Math.abs(t.deltaX)>Math.abs(t.deltaY)?t.deltaX:t.deltaY,r=t.deltaMode===1?16:t.deltaMode===2?e.clientWidth:1;t.preventDefault(),e.scrollLeft+=n*r};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[]),(0,M.useEffect)(()=>{C.current?.querySelector(`[aria-pressed="true"], input`)?.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,l]);let T=()=>{y(null),x(null)},E=()=>{if(v&&b&&v!==b.id){let t=e.find(e=>e.id===v),n=e.filter(e=>e.id!==v),i=n.findIndex(e=>e.id===b.id);t&&i>=0&&(n.splice(b.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}T()},D=()=>{if(!l)return;let t=m.trim();t&&r(e.map(e=>e.id===l?{...e,name:t}:e)),d(null)},O=(t,n)=>{_(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?P.find(e=>e.id===n)?.label??`App`:`List`,o=t===`columns`?{id:i,name:a,kind:t,columns:L()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),d(i),h(a)},ee=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[I],n===t?i[0]?.id??I.id:void 0)};return(0,N.jsxs)(`div`,{className:w(`relative flex h-full min-w-0 items-end`,a),children:[(0,N.jsx)(`div`,{ref:C,className:`flex min-w-0 items-end gap-0.5 overflow-x-auto overscroll-x-contain pt-1 [scrollbar-width:none]`,children:e.map(r=>{let a=r.id===t,u=r.kind===`columns`?f:r.kind===`app`&&r.app?z[r.app]:S;return l===r.id?(0,N.jsx)(`input`,{autoFocus:!0,"aria-label":`Tab name`,value:m,onChange:e=>h(e.target.value),onBlur:D,onKeyDown:e=>{e.key===`Enter`&&D(),e.key===`Escape`&&d(null)},className:w(`relative h-[2.3rem] w-28 shrink-0 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs outline-none ring-0`,a?w(`z-[2] bg-background font-medium`,o?k(o):`text-foreground`):`bg-muted text-muted-foreground`),style:{backgroundColor:a?o:void 0}},r.id):(0,N.jsxs)(`button`,{type:`button`,"aria-pressed":a,onClick:()=>n(r.id),onDoubleClick:()=>{i||(d(r.id),h(r.name))},title:i?r.name:`${r.name}: double-click to rename, drag to reorder`,draggable:!i,onDragStart:e=>{e.dataTransfer.setData(`text/plain`,r.name),e.dataTransfer.effectAllowed=`move`,y(r.id)},onDragOver:e=>{if(!v||v===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;x(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),E()},onDragEnd:T,className:w(`group relative flex h-[2.3rem] shrink-0 items-center gap-1.5 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs transition-colors`,a?w(`z-[2] bg-background font-medium`,o?k(o):`text-foreground`):`bg-muted text-muted-foreground hover:bg-accent hover:text-foreground`,v===r.id&&`opacity-50`),style:{backgroundColor:a?o:void 0,boxShadow:b?.id===r.id?`inset ${b.before?`2px`:`-2px`} 0 0 var(--primary)`:void 0},children:[(0,N.jsx)(u,{className:`h-3 w-3 shrink-0`}),(0,N.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,N.jsx)(p,{className:`h-3 w-3 shrink-0 opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-60`,"aria-label":`Open to the side`,onClick:e=>{e.stopPropagation(),s(r.id)}}),!i&&e.length>1&&(0,N.jsx)(c,{className:w(`h-3 w-3 shrink-0 transition-opacity hover:text-destructive`,a?`opacity-60 hover:opacity-100`:`opacity-0 group-hover:opacity-100`),onClick:e=>{e.stopPropagation(),ee(r.id)}})]},r.id)})}),!i&&(g?(0,N.jsxs)(`span`,{className:`absolute left-0 top-full z-30 flex w-full min-w-64 flex-wrap items-center gap-2 rounded-b-xl border bg-card p-2 shadow-lg`,children:[(0,N.jsxs)(`button`,{type:`button`,onClick:()=>O(`documents`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,N.jsx)(S,{className:`h-3 w-3`}),` List`]}),(0,N.jsxs)(`button`,{type:`button`,onClick:()=>O(`columns`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,N.jsx)(f,{className:`h-3 w-3`}),` Board`]}),P.map(e=>{let t=z[e.id];return(0,N.jsxs)(`button`,{type:`button`,onClick:()=>O(`app`,e.id),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,N.jsx)(t,{className:`h-3 w-3`}),` `,e.label]},e.id)}),(0,N.jsx)(`button`,{type:`button`,onClick:()=>_(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,N.jsx)(c,{className:`h-3 w-3`})})]}):(0,N.jsx)(`button`,{type:`button`,onClick:()=>_(!0),title:`Add view`,"aria-label":`Add view`,className:`relative ml-1 flex h-[2.3rem] w-10 shrink-0 items-center justify-center rounded-md pb-1 text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,N.jsx)(u,{className:`h-3.5 w-3.5`})}))]})}var V=[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}];function H(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function U({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:a=!1}){let[o,s]=(0,M.useState)(null),[l,d]=(0,M.useState)(!1),[f,p]=(0,M.useState)({}),[m,h]=(0,M.useState)({}),g=(0,M.useRef)(null),[_,v]=(0,M.useState)(!1),y=(0,M.useCallback)(()=>{let e=g.current;e&&v(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,M.useEffect)(()=>{let e=g.current;if(!e)return;let t=new ResizeObserver(()=>y());return t.observe(e),()=>t.disconnect()},[y]);let b=(e,t)=>{e.preventDefault();let i=e.currentTarget.parentElement;if(!i)return;let a=e.clientX,o=i.getBoundingClientRect().width,s=o,c=e=>{s=Math.min(900,Math.max(220,o+e.clientX-a)),h(e=>({...e,[t]:s}))},l=()=>{window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),r(n.map(e=>e.id===t?{...e,width:Math.round(s)}:e))};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l)},x=e=>{h(t=>{let n={...t};return delete n[e],n}),r(n.map(t=>t.id===e?{...t,width:void 0}:t))},S=e=>{let t=f[e];if(t===void 0)return;let i=n.find(t=>t.id===e);i&&(i.filter||``)!==t&&r(n.map(n=>n.id===e?{...n,filter:t||void 0}:n))},C=V.filter(e=>!n.some(t=>t.id===e.id));return(0,N.jsxs)(`div`,{className:`relative h-full`,children:[(0,N.jsx)(`div`,{ref:g,onScroll:y,className:`flex h-full snap-x snap-mandatory gap-3 overflow-x-auto overscroll-x-contain p-2`,"data-testid":`schema-columns-board`,children:n.map(t=>{let i=(f[t.id]??t.filter??``).toLowerCase(),o=e.filter(e=>H(e,t.schemas)).filter(e=>{if(!i)return!0;let t=T(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(i)}),l=m[t.id]??t.width;return(0,N.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-(--card-radius) border bg-muted/20 ${l?`sm:basis-[var(--col-w)]`:`sm:basis-[48%] lg:basis-[32%] xl:basis-[24%]`}`,style:l?{"--col-w":`${l}px`}:void 0,children:[!a&&(0,N.jsx)(`div`,{onPointerDown:e=>b(e,t.id),onDoubleClick:()=>x(t.id),title:`Drag to resize; double-click to reset`,className:`absolute right-0 inset-y-0 z-10 w-2 cursor-col-resize touch-none rounded-r-lg transition-colors hover:bg-primary/25 active:bg-primary/40 max-sm:hidden`}),(0,N.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,N.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,N.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:o.length}),(0,N.jsx)(`span`,{className:`flex-1`}),!a&&(0,N.jsx)(`button`,{type:`button`,onClick:()=>r(n.filter(e=>e.id!==t.id)),title:`Remove column`,className:`rounded-sm p-0.5 text-muted-foreground hover:text-destructive`,children:(0,N.jsx)(c,{className:`h-3.5 w-3.5`})})]}),(0,N.jsx)(`div`,{className:`px-3 pb-2`,children:(0,N.jsx)(`input`,{value:f[t.id]??t.filter??``,onChange:e=>p(n=>({...n,[t.id]:e.target.value})),onBlur:()=>S(t.id),onKeyDown:e=>{e.key===`Enter`&&S(t.id)},placeholder:`Filter…`,readOnly:a,className:`h-7 w-full rounded-md border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})}),(0,N.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[o.map(e=>{let t=T(e);return(0,N.jsxs)(`button`,{type:`button`,onClick:()=>s(e),className:`w-full min-w-0 rounded-md border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,N.jsx)(ue,{document:e,size:3.5}),(0,N.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,N.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,N.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground/70`,children:new Date(e.updatedAt||e.createdAt).toLocaleDateString()})]},e.id)}),o.length===0&&(0,N.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground/60`,children:`Empty`})]})]},t.id)})}),(!a&&C.length>0||_)&&(0,N.jsxs)(`div`,{className:`pointer-events-none absolute inset-y-0 right-0 z-20 flex w-7 flex-col items-end bg-gradient-to-l from-background via-background/60 to-transparent py-2`,children:[!a&&C.length>0&&(0,N.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,N.jsx)(`button`,{type:`button`,onClick:()=>d(e=>!e),title:`Add column`,"aria-label":`Add column`,className:`flex h-7 w-6 items-center justify-center rounded-l-md border border-r-0 bg-background text-muted-foreground shadow-elevation-1 hover:bg-accent hover:text-foreground`,children:(0,N.jsx)(u,{className:`h-3.5 w-3.5`})}),l&&(0,N.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,N.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),C.map(e=>(0,N.jsx)(`button`,{type:`button`,onClick:()=>{d(!1),r([...n,{...e}])},className:`w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:e.label},e.id)),(0,N.jsx)(`button`,{type:`button`,onClick:()=>d(!1),className:`mt-1 w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/60 hover:bg-accent/50`,children:`Cancel`})]})]}),_&&(0,N.jsx)(i,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,N.jsx)(ie,{document:o,isOpen:o!==null,onClose:()=>s(null),workspaceId:t})]})}function W(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,M.useState)(0),[c,l]=(0,M.useState)(null);(0,M.useEffect)(()=>{let o=!1;return D(e,n,t,{limit:200,allOf:[r],...i?{sortBy:i,order:`asc`}:{}}).then(e=>{o||l({key:a,docs:e.payload||[]})}).catch(()=>{o||l({key:a,docs:[]})}),()=>{o=!0}},[a,o]);let u=c?.key===a?c.docs:[],d=c?.key!==a;return(0,M.useEffect)(()=>{let e=()=>s(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]),{docs:u,isLoading:d,refresh:(0,M.useCallback)(()=>s(e=>e+1),[])}}function G({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=W(e,t,n,E,`tasks`),[o,s]=(0,M.useState)(!1),c=o?r.filter(e=>e.data?.status!==`completed`):r,l=r.filter(e=>{let t=e.data?.status;return t!==`completed`&&t!==`cancelled`}).length;return(0,N.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,N.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,N.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,N.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,N.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,N.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,N.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,N.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,N.jsx)(O,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function K({app:e,contextId:t,...n}){let r=t&&e!==`lens`?{mode:`context`,contextId:t}:{mode:`workspace`,workspaceName:n.workspaceId,treeName:n.treeName,path:n.path,treeType:n.treeName===`directory`||n.treeName===`backends`?`directory`:`context`},i=e===`todo-app`?`todo`:e===`notes-app`?`notes`:e,a=fe.find(e=>e.id===i);return(0,N.jsx)(j,{target:r,children:e===`todos`?(0,N.jsx)(G,{...n}):a?(0,N.jsx)(a.Component,{}):null})}export{F as a,me as c,I as i,pe as l,U as n,R as o,B as r,ge as s,K as t};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/subtree-transfer-dialog-ChBI5llU.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BOIngd5F.js","assets/react-BHzhHVTZ.js","assets/ui-Byg1cZDr.js","assets/button-SgR3GVvV.js","assets/utils-BxVxyehK.js","assets/utils-2pl1SbIp.js","assets/input-BOtCd4HP.js","assets/api-CA6WiiYM.js","assets/alert-dialog-izlVMXfa.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-BOIngd5F.js";import{vt as i,yt as a}from"./react-BHzhHVTZ.js";import{t as o}from"./preload-helper-Czpn1I53.js";import{g as s}from"./chunk-62JRHF6Z-vspAGgtK.js";import{$ as c,Br as l,Bt as u,Ct as d,Ft as f,Gn as p,Gr as m,Hn as h,It as g,Kr as _,L as v,Lt as y,Nt as b,Rn as x,Rr as S,Sr as C,Tt as ee,Ut as te,Vr as ne,W as w,X as T,Zn as E,Zt as D,_n as re,_r as ie,bn as ae,cr as oe,dr as se,fn as O,gn as ce,gr as le,hr as ue,in as de,ir as fe,kr as pe,oi as me,ot as he,pi as ge,pr as _e,qt as ve,rt as ye,sn as k,sr as be,st as xe,tt as A,ui as Se,vn as Ce,wr as we,xt as Te,yt as Ee,zn as De,zr as Oe,zt as ke}from"./ui-Byg1cZDr.js";import{t as j}from"./utils-2pl1SbIp.js";import{t as M}from"./button-SgR3GVvV.js";import{t as Ae}from"./socket-CtH3EU9m.js";import{n as je}from"./use-toast-BlLDqSUO.js";import{c as Me,d as Ne,f as Pe,h as Fe,l as Ie,p as Le,t as Re,u as ze}from"./LinkToCard-5dg0jvSY.js";import{$ as Be,An as N,Bt as Ve,Dn as He,Ft as Ue,Hn as We,It as P,Lt as Ge,Mn as Ke,Ot as qe,P as Je,Sn as Ye,Tn as Xe,Vt as Ze,Wt as Qe,Xt as $e,Yt as et,_ as tt,_n as nt,bn as rt,bt as it,dt as at,gn as ot,gt as st,h as F,hn as ct,ht as lt,i as ut,it as dt,jn as ft,jt as pt,k as mt,l as I,ln as L,m as R,mn as ht,nt as z,o as gt,s as _t,un as vt,wn as yt,zt as bt}from"./workspace-CrSpR4xf.js";import{a as xt,b as St,c as Ct,f as wt,l as Tt,o as Et,s as B,t as Dt,v as Ot}from"./ObjectPropertiesCard-BIBMvx_i.js";import{i as kt,n as At,s as jt}from"./document-open-mode-DoImW-xs.js";import{t as Mt}from"./use-mobile-Db-vWu9Y.js";import{c as Nt,s as Pt}from"./IdentityFields-Bti7ojF3.js";import{i as Ft}from"./public-share-g_wBd6BW.js";import{o as It,s as Lt}from"./text-documents-0P9jkIpu.js";import{t as V}from"./useDocumentThumbnail-DunxmU1A.js";import{t as Rt}from"./markdown-view-BBBZtNSR.js";import{n as zt}from"./tags-YamdPoBK.js";import{r as Bt}from"./use-toolbox-Ck_cLGgf.js";import{C as Vt,S as Ht,T as Ut,g as Wt,h as Gt,m as Kt,t as qt,u as Jt,y as Yt}from"./context-DQoZFMDQ.js";import{n as Xt}from"./relation-events-CKio19hE.js";import{n as Zt,t as Qt}from"./PickDocumentsCard-DamtV7fN.js";import{t as H}from"./useEscapeClose-DR_xKT_k.js";import{t as $t}from"./useToastHelpers-CRrpIIdY.js";import{u as en}from"./layer-style-Byl5LNFR.js";import{t as U}from"./DocumentIcon-x299QNu_.js";import{n as tn,t as nn}from"./LinkToSidePanel-eCy3nW4R.js";import{C as rn,W as an,c as on,d as sn,i as cn,k as ln,s as un,t as dn,z as fn}from"./backend-sync-progress-pZrhQPk3.js";import{t as pn}from"./workspace-access-C9nZlBBZ.js";import{t as mn}from"./search-COMZIxA7.js";import{a as W,c as hn,i as gn,n as _n,o as vn,r as yn,s as bn,t as xn}from"./use-sortable-data-BW_0sXBs.js";import{n as Sn}from"./workspace-BydSRtST.js";var G=e(r(),1),Cn=(0,G.createContext)(null),wn=()=>(0,G.useContext)(Cn),Tn=`canvas:readerWidth`,K=320,q=1600;function En(){try{let e=Number(sessionStorage.getItem(Tn));return Number.isFinite(e)&&e>=K&&e<=q?e:null}catch{return null}}var Dn=En(),On=new Set;function kn(e){return On.add(e),()=>{On.delete(e)}}function An(e){Dn=e===null?null:Math.round(Math.max(K,Math.min(q,e)));try{Dn===null?sessionStorage.removeItem(Tn):sessionStorage.setItem(Tn,String(Dn))}catch{}On.forEach(e=>e())}function jn(){return(0,G.useSyncExternalStore)(kn,()=>Dn,()=>null)}function Mn(e,t){let[n,r]=(0,G.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,G.useState)(a);a!==o&&(s(a),r(null));let c=(0,G.useRef)(a),l=(0,G.useRef)(0);(0,G.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,G.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}z(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}var J=n();function Nn(e){return e.schema===`data/schema/note`?A:e.schema===`data/schema/tab`?ce:e.schema===`data/schema/file`?fe:e.schema===`data/schema/message/email`?k:oe}function Pn({entry:e,onClose:t,frame:n}={}){let r=Et(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=Mn(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,J.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,J.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,J.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,J.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,J.jsx)(v,{className:`h-4 w-4`})})]}),(0,J.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,J.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,J.jsx)(Zt,{title:N(o).title,icon:Nn(o),onClose:a,onSave:async e=>(await Ve(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:wt(o)===Ot,maximized:e?void 0:r.location?.maximized,onMaximizedChange:e?void 0:e=>r.update?.({maximized:e}),children:t=>(0,J.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,J.jsx)(Dt,{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 Fn=320,In=1600;function Ln({edge:e}){let t=jn(),n=(0,G.useRef)(null),r=e===`left`?-1:1;return(0,J.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":Fn,"aria-valuemax":In,"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(Fn,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&An(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:()=>An(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`?An(null):An(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function Rn(e){let t=wn(),n=kt(),r=Mt(),i=Et();return!e.enabled||!e.workspaceId||r||t?.compact||i.location?e.children:(0,J.jsx)(zn,{...e,workspaceId:e.workspaceId,autoOpen:n},`${e.scope}:${n}`)}function zn({workspaceId:e,scope:t,documents:n,loading:r,children:i,autoOpen:a}){let o=jn(),[s,c]=(0,G.useState)(a),l=`canvas:readerSelection:${t}`,[u,d]=(0,G.useState)(()=>{try{return Number(sessionStorage.getItem(l))||null}catch{return null}}),f=!s||r?null:n.find(e=>e.id===u)??n[0]??null,p=(0,G.useCallback)((t,n)=>{if(n===e){c(!0),d(t.id);try{sessionStorage.setItem(l,String(t.id))}catch{}}},[e,l]),m=(0,G.useMemo)(()=>({entry:f?{document:f,workspaceId:e}:null,alwaysOn:!0,open:p,preview:p,replace:p,close:()=>c(!1)}),[f,e,p]);return(0,J.jsx)(xt.Provider,{value:m,children:(0,J.jsxs)(`div`,{"data-always-reader":!0,className:`flex h-full min-h-0 min-w-0 flex-1 gap-shell`,children:[(0,J.jsx)(`div`,{className:`min-h-0 min-w-0 flex-1 overflow-auto`,children:i}),s&&(0,J.jsxs)(`aside`,{"data-reader-pane":!0,"aria-label":`Document reading pane`,style:{width:o?`${o}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,J.jsx)(Ln,{edge:`left`}),f?(0,J.jsx)(Pn,{},`${e}:${f.id}`):(0,J.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 Bn(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 Vn(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 Hn(){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 Un(){let[e]=(0,G.useState)(Hn);return(0,G.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 Wn(e,t,n,r,i=!1){let a=e.indexOf(n);if(a<0)return new Set(r);let o=t===null?-1:e.indexOf(t),s=o<0?a:o,c=i?new Set(r):new Set;for(let t of e.slice(Math.min(s,a),Math.max(s,a)+1))c.add(t);return c}var Y=e=>typeof e==`string`?e:``,X=e=>e&&typeof e==`object`?e:{},Z=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);function Gn(e){let t=e.data||{},n=e.schema===`data/schema/message/email`,r=!n&&e.schema.startsWith(`data/schema/message`),i=Y(t.platform),a=Y(X(t.channel).id)||Y(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=Y(X(t.from).address)||Y(t.from);e&&s(`sender`,`Mail from ${e}`,{from:{equals:e}}),t.subject&&s(`subject`,`Subject matches regex`,{subject:{regex:Z(t.subject)}})}else if(r){let e=Y(X(t.sender).id)||Y(X(t.sender).username)||Y(X(t.sender).name)||Y(t.sender),n=Y(X(t.sender).name)||Y(X(t.sender).username)||e;e&&s(`sender`,`Messages from ${n}`,{...c,sender:{equals:e}})}let l=Y(t.body)||Y(t.text)||Y(t.content)||Y(t.bodyHtml)||Y(t.bodyPreview);if((n||r||l)&&s(`body`,n?`Email body matches regex`:`Text matches regex`,{...c,body:{regex:Z(l.slice(0,160))}}),r){let n=Y(t.threadId)||([`slack`,`teams`].includes(i)?Y(X(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:Z(t.url)}}),s(`schema`,`All items of this type`,{}),o}var Kn=e(a(),1);function qn({label:e,onClose:t,children:n}){return H(t),(0,Kn.createPortal)((0,J.jsx)(`div`,{className:`fixed inset-0 z-dialog flex items-center justify-center bg-scrim p-4`,onClick:t,children:(0,J.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 Jn({workspaceId:e,document:t,onClose:n}){let[r,i]=(0,G.useState)(null),[a,o]=(0,G.useState)(``),[s,c]=(0,G.useState)(``);H(n),(0,G.useEffect)(()=>{let n=!1;return(async()=>{let r=await Be(e);if(!pn(r))throw Error(`Only workspace administrators can create rules.`);let a=await z(e,t.id);n||i(a)})().catch(e=>{n||o(e instanceof Error?e.message:`Could not load document`)}),()=>{n=!0}},[e,t.id]);let l=(0,G.useMemo)(()=>r?Gn(r):[],[r]),u=l.find(e=>e.id===s)||l[0],d=(0,G.useMemo)(()=>u?{kind:`document`,rule:u.rule}:null,[u]);return(0,J.jsx)(qn,{label:`Create rule`,onClose:n,children:(0,J.jsxs)(`div`,{className:`p-5`,children:[(0,J.jsxs)(`div`,{className:`mb-4 flex items-start justify-between gap-3`,children:[(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsx)(`h2`,{id:`document-rule-title`,className:`text-lg font-semibold`,children:`Create rule`}),(0,J.jsx)(`p`,{className:`truncate text-sm text-muted-foreground`,children:N(t).title})]}),(0,J.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`rounded-md p-2 hover:bg-accent`,children:(0,J.jsx)(v,{className:`h-4 w-4`})})]}),a?(0,J.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}):r?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`mb-4 block space-y-2 text-sm font-medium`,children:[(0,J.jsx)(`span`,{children:`Start with`}),(0,J.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,J.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,J.jsx)(sn,{workspaceId:e,prefill:d,createOnly:!0,onCreated:n,onCancel:n})]}):(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading document…`})]})})}function Yn(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 Xn(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 Zn(e,t,n,r){let i=new Set(r?n:[]);for(let n of t)Xn(e,n.bounds)&&i.add(n.id);return i}var Qn=`[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 $n(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=Yn(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(Zn(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(Qn))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 er({scope:e,selected:t,onSelectionChange:n,onContextMenu:r,children:i}){let a=(0,G.useRef)(null),o=(0,G.useRef)({selected:t,onSelectionChange:n});return(0,G.useLayoutEffect)(()=>{o.current={selected:t,onSelectionChange:n}},[t,n]),(0,G.useLayoutEffect)(()=>{if(a.current)return $n(a.current,{getSelection:()=>o.current.selected,onSelectionChange:e=>o.current.onSelectionChange(e)})},[e]),(0,J.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 tr(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 nr({workspaceId:e,ids:t,onClose:n,modal:r=!1}){let{showProgress:i}=je();H(n,r);let[a]=(0,G.useState)(()=>{try{return tr(e)}catch{return``}}),[o,s]=(0,G.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,G.useState)(!1),[u,d]=(0,G.useState)(``),f=(0,G.useRef)(!1),p=(0,G.useRef)(!1);(0,G.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 R(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`:nn,y=(0,J.jsx)(J.Fragment,{children:o?(0,J.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,J.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,J.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[o.target.workspaceName,`: `,o.paths.join(`, `)]}),(0,J.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[o.index,` of `,o.ids.length,` copied`,_?`.`:c?`…`:` — paused.`]}),u&&(0,J.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:u}),(0,J.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,J.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,J.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!_&&!c&&(0,J.jsx)(M,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(a)}catch{}s(null),d(``)},children:`Discard remaining`}),!_&&!c&&(0,J.jsx)(M,{onClick:()=>void h(o),children:`Resume copy`}),(0,J.jsx)(M,{variant:_?`default`:`outline`,onClick:g,children:_?`Done`:c?`Pause & close`:`Close`})]})]}):(0,J.jsx)(Re,{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,J.jsx)(qn,{label:`Copy to workspace`,onClose:g,children:y}):(0,J.jsx)(tn,{onClose:g,children:y})}function rr(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...zt(e.data?.tags??[]),...zt(t)])]}:{},...n?{geo:n}:{}}}function ir(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:rr(e,t,n),...r===void 0?{}:{comment:r.trim()}}}function ar({workspaceId:e,documentIds:t,onClose:n}){let[r,i]=(0,G.useState)([]),[a,o]=(0,G.useState)(null),[s,c]=(0,G.useState)(`keep`),[l,u]=(0,G.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,G.useState)(t),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)(``);return H(n,!m),(0,Kn.createPortal)((0,J.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-scrim p-4`,children:(0,J.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,J.jsxs)(`h2`,{id:`bulk-edit-title`,className:`font-semibold`,children:[`Bulk Edit · `,f.length,` documents`]}),(0,J.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,J.jsxs)(`fieldset`,{disabled:m,className:`space-y-4`,children:[(0,J.jsxs)(`div`,{className:`space-y-2`,children:[(0,J.jsx)(`span`,{className:`text-sm font-medium`,children:`Add tags`}),(0,J.jsx)(Pt,{tags:r,onChange:i,suggestions:[]})]}),(0,J.jsx)(B,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,J.jsxs)(`div`,{className:`space-y-2`,children:[(0,J.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,J.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,J.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,J.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,J.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,J.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,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,J.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,J.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,J.jsx)(M,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,J.jsx)(M,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await z(e,n);await rt(e,ir(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 or=e=>`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`;function sr(e,t,n,r){return typeof e.sourcePath==`string`&&!!t&&e.sourceWorkspaceId===t&&!!n&&e.sourceTreeName===n&&or(e.sourcePath)===or(r)}var cr=i();function lr(e){let{id:t,...n}=e;return n}function ur(e){let t=At(),n=(0,G.useContext)(xt),{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,G.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,J.jsx)(dr,{...e})}function dr({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,G.useState)(!1),c=Bt(),{document:l,refresh:u}=Mn(r,e);if(H(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,Kn.createPortal)((0,J.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:j(`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,J.jsxs)(`div`,{className:j(`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,J.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:N(l).title}),(0,J.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,J.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=ft(l);return e?(0,J.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,J.jsx)(_e,{className:`h-4 w-4`})}):null})(),(0,J.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,J.jsx)(D,{className:`h-4 w-4`}):(0,J.jsx)(de,{className:`h-4 w-4`})}),(0,J.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,J.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,J.jsx)(Nt.Provider,{value:()=>s(e=>!e),children:(0,J.jsx)(Dt,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var fr=Sn,pr={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function mr(e){return pr[e]??e}function hr(e){let[t,n]=(0,G.useState)([]);return(0,G.useEffect)(()=>{let t=!1;return pt(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,G.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:mr(e)})),[t])}function gr({workspaceId:e,value:t,onChange:n}){let r=hr(e);return(0,J.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,J.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,J.jsx)(`option`,{value:t.sortBy,children:mr(t.sortBy)}),r.map(e=>(0,J.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,J.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,J.jsx)(me,{className:`h-3.5 w-3.5`}):(0,J.jsx)(ge,{className:`h-3.5 w-3.5`})})]})}function _r(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 Q={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},$=e=>e*1e6;function vr(){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 yr(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function br(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=yr(e);return r.setDate(r.getDate()-n),r}var xr=864e5;function Sr(e){let t=vr(),n=yr(e),r=br(e,t);return{today:n.getTime(),yesterday:n.getTime()-xr,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*xr,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function Cr(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:$(Q.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:$(Q.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:$(Q.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:$(Q.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:$(Q.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:$(Q.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:$(Q.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:$(Q.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:$(Q.year)+i}}function wr(e,t,n=`desc`,r=new Date){let i=Sr(r),a=new Map;for(let n of e){let e=Cr(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 Tr(){let{showProgress:e}=je();return(0,G.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 Er=[`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`],Dr=new Map;function Or(e,t,n){st(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 kr(e,t){let n=Dr.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=Er.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)st(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return Ae.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)st(e,t);a.forEach(([e,t])=>Ae.off(e,t))}},Dr.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),Dr.delete(e))}}function Ar({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=Tr(),{showProgress:a}=je(),s=n||`context`,c=s===`directory`,[l,u]=(0,G.useState)([]);(0,G.useEffect)(()=>{let e=!1,n=()=>{t&&ln(t).then(t=>{e||u(t)}).catch(()=>{})};return n(),window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[t,s]);let d=(0,G.useCallback)(e=>{if(s===`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,s,c]),f=(0,G.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),p=(0,G.useCallback)(async(n,r=!0)=>{let i;if(e)i=await Jt(e,n,r);else if(t)i=await lt(t,n,r,s);else return!1;let a=en(n);if(i&&a)try{e?await Ut(e,n,a):t&&await Ye(t,n,a,s)}catch{}return f(),i},[e,t,s,f]),m=(0,G.useCallback)(async(n,r=!1,a=!1,o=!1)=>i(o?`Destroying…`:a?`Purging…`:`Removing…`,n,o?`Destroyed`:a?`Purged`:`Removed`,async()=>{try{return e?await Yt(e,n,r):t?await et(t,n,r,s,a,o):!1}finally{f()}}),[e,t,s,f,i]),h=(0,G.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await Wt(e,n,t.join(`/`),!1)}else if(t)i=await Ye(t,n,{name:r},s);else return!1;return f(),i},[e,t,s,f]),g=(0,G.useCallback)(async(n,r,a=!1,o=s,c=s,l={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await Wt(e,n,r,a,l);else if(t)i=await bt(t,n,r,a,o,c,l);else return!1;return f(),i}),[e,t,s,f,i]),_=(0,G.useCallback)(async n=>{let r;if(e)r=await Gt(e,n);else if(t)r=await P(t,n,s);else return null;return f(),r},[e,t,s,f]),v=(0,G.useCallback)(async n=>{let r;if(e)r=await Vt(e,n);else if(t)r=await L(t,n,s);else return null;return f(),r},[e,t,s,f]),y=(0,G.useCallback)(async(n,r,a=!1,o=s,c=s)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await qt(e,n,r,a);else if(t)i=await F(t,n,r,a,o,c);else return!1;return f(),i}),[e,t,s,f,i]),b=(0,G.useCallback)(async(n,r)=>e?await Ut(e,n,r):t?await Ye(t,n,r,s):!1,[e,t,s]),x=(0,G.useCallback)(async(n,r)=>{let i;if(e)i=await Kt(e,n,r);else if(t)i=await Ge(t,n,r,s);else return null;return f(),i},[e,t,s,f]),S=(0,G.useCallback)(async(n,r)=>{let i;if(e)i=await Ht(e,n,r);else if(t)i=await vt(t,n,r,s);else return null;return f(),i},[e,t,s,f]),C=(0,G.useCallback)(async e=>{if(!t)return!1;let n=await Ue(t,e,t,s);return f(300),n},[t,s,f]),ee=(0,G.useCallback)(async(e,n)=>{if(!t)return!1;try{await ot(t,e,n??t,s)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return f(300),!0},[t,s,f]),te=(0,G.useCallback)(async e=>{if(!t)return!1;let n=await mt(t,e,s);return f(),n},[t,s,f]),ne=(0,G.useCallback)(async e=>{if(!t)return!1;let n=await it(t).catch(()=>[]),r=d(e);for(let e of r){let r=gt(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 dn(a,t,r.driver,r.address,void 0,o?.name)}return f(300),r.length>0},[t,f,a,d]),w=(0,G.useCallback)(async(e,n)=>{if(!t)return!1;let r=await it(t).catch(()=>[]),i=_t(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await ut(t,i.driver,i.address,[a]),f(200),!0},[t,f]),T=(0,G.useCallback)(async(e,n)=>{if(!t)return!1;let r=await it(t).catch(()=>[]),i=_t(e,r);return!i||!i.key?!1:(await $e(t,i.driver,i.address,i.key,n),f(200),!0)},[t,f]),E=(0,G.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await it(t),r=I(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await Qe(t,r.driver,r.address,r.key),!0}finally{f(200)}}):!1,[t,f,i]),D=(0,G.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await o(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-ChBI5llU.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));r({mode:e,path:n,workspaceId:t,treeName:s,onImported:()=>{Or(t,s),f()}})},[t,s,f]),re=(0,G.useCallback)(async(e,n)=>{if(!t)return;let r=await o(()=>Promise.resolve().then(()=>Mr),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await at(t,n,e,s,ct(s))).length!==e.length)throw Error(`Some documents could not be imported`);return Or(t,s),f(),!0});else{let e=[];for(let r=0;;){let i=await dt(t,n,[],{treeName:s,treeType:ct(s),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,s,f]);return{onImportDocuments:t&&s!==`backends`?e=>re(`import`,e):void 0,onExportDocuments:t?e=>re(`export`,e):void 0,onInsertPath:p,onRemovePath:m,onRenamePath:h,onMovePath:g,onCopyPath:y,onExportSubtree:t?e=>D(`export`,e):void 0,onImportSubtree:t&&s!==`backends`?e=>D(`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?ee:void 0,onDestroyLayer:t&&!c?te:void 0,canResyncBackend:e=>d(e).length>0,onResyncBackend:t?ne:void 0,onCreateBackendFolder:t?w:void 0,onRenameBackendFolder:t?T:void 0,onDeleteBackendFolder:t?E:void 0}}function jr({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:c,pastedDocumentIds:l,onPasteDocuments:d}){let f=s(),p=Ar({workspaceId:n,treeName:r}),m=r===`backends`,h=m?_t(i):null,[_,v]=(0,G.useState)([]);(0,G.useEffect)(()=>{if(!m)return;let e=!1;return it(n).then(t=>{e||v(t)}).catch(()=>{}),()=>{e=!0}},[n,m]);let x=m?I(i,_):null,S=i.split(`/`).filter(Boolean).pop()||i,[C,te]=(0,G.useState)(void 0);(0,G.useEffect)(()=>{let e=!1;return qe(n).then(t=>{e||te(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||te(null)}),()=>{e=!0}},[n,r,i]);let ne=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},w=(e,t,n,r=!1)=>(0,J.jsxs)(`button`,{type:`button`,className:j(`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:()=>ne(n),children:[e,t]}),D=(0,J.jsx)(`div`,{className:`my-1 h-px bg-border`}),re=e=>{let t=m?(()=>{let t=an(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:rn(i)};f(`/workspaces/${n}/settings/hooks?${fn(t).toString()}`)},ae=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},oe=on(r,i);return oe?(0,J.jsxs)(Fe,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[w((0,J.jsx)(T,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),oe.backend&&w((0,J.jsx)(ee,{className:`h-3 w-3`}),`Restore original paths`,()=>un(n,i)),oe.backend&&w((0,J.jsx)(T,{className:`h-3 w-3`}),`Empty Trash`,()=>cn(n,i),!0)]}):(0,J.jsxs)(Fe,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[w((0,J.jsx)(E,{className:`w-3 h-3`}),`Open`,()=>o(i)),c&&w((0,J.jsx)(se,{className:`w-3 h-3`}),`Open to the side`,()=>c(i)),D,m?h&&(0,J.jsxs)(J.Fragment,{children:[w((0,J.jsx)(b,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=ae(`New folder name:`);e&&await p.onCreateBackendFolder?.(i,e)}),h.key&&w((0,J.jsx)(u,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=ae(`New folder name:`,S);e&&await p.onRenameBackendFolder?.(i,e)}),w((0,J.jsx)(De,{className:`w-3 h-3`}),`Create storage rule…`,()=>re(`store`))]}):(0,J.jsxs)(J.Fragment,{children:[w((0,J.jsx)(b,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=ae(`New folder name:`);e&&await p.onInsertPath(`${i===`/`?``:i}/${e}`)}),w((0,J.jsx)(u,{className:`w-3 h-3`}),`Rename`,async()=>{let e=ae(`New name:`,S);e&&await p.onRenamePath(i,e)}),w((0,J.jsx)(De,{className:`w-3 h-3`}),`Create rule…`,()=>re(`store`)),w((0,J.jsx)(ie,{className:`w-3 h-3`}),`Create download rule…`,()=>re(`download`))]}),C!==void 0&&w(C?(0,J.jsx)(y,{className:`w-3 h-3`}):(0,J.jsx)(g,{className:`w-3 h-3`}),C?`Unpin`:`Pin`,async()=>{C?await nt(n,C.id):await Ze(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),D,p.onImportDocuments&&w((0,J.jsx)(b,{className:`w-3 h-3`}),`Import documents…`,()=>p.onImportDocuments(i)),p.onExportDocuments&&w((0,J.jsx)(ie,{className:`w-3 h-3`}),`Export documents…`,()=>p.onExportDocuments(i)),w((0,J.jsx)(we,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!m&&d&&l&&l.length>0&&w((0,J.jsx)(pe,{className:`w-3 h-3`}),`Paste ${l.length} document(s)`,()=>d(i,l)),m?x&&(0,J.jsxs)(J.Fragment,{children:[D,w((0,J.jsx)(T,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${S}" and its contents from the backend?`)&&await p.onDeleteBackendFolder?.(i)},!0)]}):(0,J.jsxs)(J.Fragment,{children:[D,w((0,J.jsx)(T,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await p.onRemovePath(i,!0)},!0)]})]})}var Mr=t({DocumentList:()=>ii,default:()=>ii,showDocumentExport:()=>oi,showDocumentImport:()=>ai});function Nr({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,G.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(lr),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,J.jsx)(qn,{label:`Export Documents`,onClose:o,children:(0,J.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,J.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,J.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,J.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,J.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,J.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,J.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,J.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,J.jsxs)(M,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,J.jsx)(we,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,J.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,J.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-end gap-2`,children:[(0,J.jsx)(M,{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,J.jsx)(M,{onClick:o,children:`Close`})]})]})})}function Pr({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.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,Kn.createPortal)((0,J.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,J.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,J.jsxs)(`div`,{className:`p-6`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,J.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data or choose a document export file`})]}),(0,J.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,J.jsxs)(`div`,{className:`space-y-4`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,J.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,J.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,J.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,J.jsxs)(`p`,{children:[(0,J.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,J.jsxs)(`p`,{children:[(0,J.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,J.jsxs)(`label`,{className:`mt-4 block text-sm`,children:[`Import JSON file`,(0,J.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,J.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,J.jsx)(M,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,J.jsx)(M,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function Fr({document:e}){let{replicating:t,label:n}=yt(e);return t?(0,J.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,J.jsx)(O,{className:`h-3 w-3 animate-spin`}),n]}):null}function Ir(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Ie(e.currentTarget,`inside`)}function Lr({documentId:e,onOpenActions:t,className:n}){return t?(0,J.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,J.jsx)(le,{className:`h-4 w-4`})}):null}function Rr(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function zr({document:e}){let t=ft(e);return t?(0,J.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,J.jsx)(_e,{className:`h-3.5 w-3.5`})}):null}function Br({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Et(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=Un(),[u,d]=(0,G.useState)(!1),{replicating:f}=yt(e),p=N(e),m=Hr(e),h=m||Wr(e),{blobUrl:g}=V(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,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(hn,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>Rr(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,J.jsx)(W,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,J.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,J.jsx)(W,{className:`w-12`,children:g?(0,J.jsx)(`img`,{src:g,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,J.jsx)(U,{document:e,chip:!0})}),(0,J.jsx)(W,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,J.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),(0,J.jsx)(zr,{document:e}),(0,J.jsx)(Fr,{document:e})]}),p.subtitle&&(0,J.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,J.jsx)(W,{className:`hidden md:table-cell`,children:(0,J.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:p.schemaLabel})}),(0,J.jsx)(W,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,J.jsx)(W,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:y&&(0,J.jsx)(`span`,{className:`font-mono`,title:`${y.algo} checksum`,children:y.hash})}),(0,J.jsx)(W,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,J.jsx)(W,{className:`w-12 text-right`,children:(0,J.jsx)(Lr,{documentId:e.id,onOpenActions:a})})]}),(0,J.jsx)(ur,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function Vr({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Et(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=Un(),[u,d]=(0,G.useState)(!1),p=e.schema===`data/schema/tab`,{replicating:h}=yt(e),g=N(e),_=Hr(e),v=Ur(e),y=_||Wr(e)||v,{blobUrl:b,loading:S}=V(n??``,e.id,512,{enabled:y,blobFallback:_,version:e.checksumArray?.[0]??null}),C=t=>{o?.(t,e.id)},ee=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),te=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),ne=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,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>Rr(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 ${h?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${p&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:ne,onMouseDown:w,...l,onContextMenu:T,draggable:!0,onDragStart:C,children:(0,J.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[y&&(0,J.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:[b?(0,J.jsx)(`img`,{src:b,alt:g.title,loading:`lazy`,className:`h-full w-full object-cover`}):v&&n&&!S?(0,J.jsx)(Gr,{workspaceId:n,documentId:e.id,fallback:(0,J.jsx)(U,{document:e})}):S?(0,J.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,J.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,J.jsx)(U,{document:e})}),v&&(0,J.jsx)(f,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`})]}),(0,J.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,J.jsx)(U,{document:e,chip:!0}),(0,J.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:g.title,children:g.title}),(0,J.jsx)(zr,{document:e}),(0,J.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:g.schemaLabel}),(0,J.jsx)(Fr,{document:e})]}),g.subtitle&&(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:g.subtitle,children:g.subtitle}),g.preview&&(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:g.preview}),(0,J.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,J.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),te&&(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(x,{className:`h-3 w-3`}),(0,J.jsx)(`span`,{className:`font-mono`,title:`${te.algo} checksum`,children:te.hash})]}),(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(m,{className:`h-3 w-3`}),(0,J.jsx)(`span`,{title:`Created: ${ee(e.createdAt)}`,children:ee(e.createdAt)})]})]})]}),(0,J.jsx)(Lr,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,J.jsx)(ur,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function Hr(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Ur(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function Wr(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Gr({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Lt(e,t),[a,o]=(0,G.useState)(!1);return i||a?(0,J.jsx)(J.Fragment,{children:n}):r?(0,J.jsxs)(`div`,{className:`relative h-full w-full`,children:[(0,J.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-full w-full object-cover`}),(0,J.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,J.jsx)(f,{className:`h-3.5 w-3.5`})})]}):(0,J.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function Kr({document:e,workspaceId:t,markdown:n}){let r=(0,G.useRef)(null),[i,a]=(0,G.useState)(()=>typeof IntersectionObserver>`u`);(0,G.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}=It(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,J.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,J.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,J.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,J.jsx)(Rt,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,J.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,J.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,J.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,J.jsx)(U,{document:e,size:10,chip:!0}),i&&s&&(0,J.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function qr({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let[c,l]=(0,G.useState)(null),u=e.metadata?.dimensions,d=c??(u?.width&&u?.height?Math.max(.2,Math.min(5,u.width/u.height)):1),p=Et(),m=p.alwaysOn&&p.entry?.workspaceId===n&&p.entry?.document.id===e.id,h=Un(),[g,_]=(0,G.useState)(!1),v=Hr(e),y=Ur(e),b=v||Wr(e)||y,x=N(e),S=We(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||Ke(e)),C=e.schema===`data/schema/file`&&(S===`markdown`||S===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,ee=!b&&e.schema!==`data/schema/file`&&!!(x.preview||x.subtitle),{replicating:ne}=yt(e),{blobUrl:w,loading:T}=V(n??``,e.id,768,{enabled:b,blobFallback:v,version:e.checksumArray?.[0]??null}),E=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||_(!0)},D=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,style:{flexGrow:d,flexBasis:`${d*220}px`,"--tile-ratio":d},"data-reading":m||void 0,"aria-selected":!!t,onKeyDown:n=>Rr(n,()=>_(!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 ${ne?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:E,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...h,onContextMenu:D,draggable:!0,onDragStart:t=>s?.(t,e.id),title:x.title,children:[(0,J.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,J.jsxs)(`div`,{className:`document-tile-media relative w-full bg-muted/40 ${b&&w||ee||C&&n||y&&n?``:`aspect-square`}`,children:[b&&T&&(0,J.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),b&&w?(0,J.jsx)(`img`,{src:w,alt:x.title,loading:`lazy`,className:`block h-auto w-full`,onLoad:e=>{let t=e.currentTarget;t.naturalHeight&&l(t.naturalWidth/t.naturalHeight)}}):y&&n&&!T?(0,J.jsx)(Gr,{workspaceId:n,documentId:e.id,fallback:(0,J.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,J.jsx)(U,{document:e,size:10,chip:!0})})}):C&&n?(0,J.jsx)(Kr,{document:e,workspaceId:n,markdown:S===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):ee?(0,J.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,J.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,J.jsx)(U,{document:e}),(0,J.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:x.schemaLabel}),(0,J.jsx)(zr,{document:e})]}),(0,J.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:x.title}),x.subtitle&&(0,J.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:x.subtitle}),(0,J.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:x.preview})]}):(0,J.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,J.jsx)(U,{document:e,size:10,chip:!0})}),y&&w&&(0,J.jsx)(f,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`}),(0,J.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,J.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,J.jsx)(te,{className:`h-3.5 w-3.5`})}),o&&(0,J.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,J.jsx)(le,{className:`h-3.5 w-3.5`})})]})]}),!ee&&(0,J.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,J.jsx)(`span`,{className:`truncate text-xs font-medium`,title:x.title,children:x.title}),(0,J.jsx)(zr,{document:e})]})]}),(0,J.jsx)(ur,{document:e,isOpen:g,onClose:()=>_(!1),workspaceId:n})]})}function Jr(e,t,n,r,i){let[a,o]=(0,G.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)&&!sr(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function Yr(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function Xr({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,J.jsx)(C,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,J.jsx)(p,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var Zr=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function Qr({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Jr(e,r,i,a,o);return(0,J.jsxs)(`button`,{type:`button`,title:Zr(e),onClick:()=>t?.(e.path),onContextMenu:t=>Yr(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,J.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,J.jsx)(Xr,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,J.jsx)(C,{className:`hidden h-4 w-4 group-hover:block`}):(0,J.jsx)(E,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,J.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,J.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function $r({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Jr(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,J.jsxs)(`button`,{type:`button`,title:Zr(e),onClick:()=>t?.(e.path),onContextMenu:t=>Yr(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,J.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,J.jsx)(C,{className:`h-10 w-10`,strokeWidth:1.5}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(p,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,J.jsx)(E,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c})]})}),(0,J.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,J.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function ei({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,J.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,J.jsx)($r,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function ti({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,J.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,J.jsx)(Qr,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function ni({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Jr(e,r,i,a,o);return(0,J.jsxs)(hn,{"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=>Yr(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:Zr(e),children:[(0,J.jsx)(W,{className:`w-10`}),(0,J.jsx)(W,{className:`w-12`,children:(0,J.jsx)(Xr,{folder:e})}),(0,J.jsx)(W,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,J.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,J.jsx)(W,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,J.jsx)(W,{className:`hidden lg:table-cell`}),(0,J.jsx)(W,{className:`hidden lg:table-cell`}),(0,J.jsx)(W,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,J.jsx)(W,{className:`w-12 md:w-auto`})]})}function ri({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,J.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,J.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,J.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,J.jsx)(l,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,J.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,J.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,J.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function ii({readingPane:e=!1,externalSearchQuery:t,toolbarActions:n,documents:r,isLoading:i,contextPath:a,treeName:o,workspaceId:s,totalCount:u,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:g,onDeleteDocuments:y,onDestroyDocuments:x,onCopyDocuments:C,onCutDocuments:ee,onPasteDocuments:E,onImportDocuments:D,onSelectionChange:oe,pastedDocumentIds:O,viewMode:le=`card`,allowViewToggle:de=!1,activeContextUrl:me,currentContextUrl:ge,currentPage:k=1,pageSize:A=50,onPageChange:j,onPageSizeChange:Ae,onPurgeDocuments:Fe,disablePurgeDocuments:Be=!1,backendSearchQueries:Ve=[],onBackendSearch:Ue,onRemoveBackendQuery:We,serverSort:P,onServerSortChange:Ge,scope:qe=`path`,onScopeChange:Ye,canSaveChanges:Ze=!1,isSavingChanges:Qe=!1,onSaveChanges:$e,linkTree:et,folders:nt,onOpenFolder:rt}){let it=wn(),at=jt(),[ot,st]=(0,G.useState)(()=>{if(!de)return le;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return le}),F=de?it?.documentLayout??ot:le,ct=(0,G.useCallback)(e=>{it?.selectDocumentLayout(e),st(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[it]),[lt,ut]=(0,G.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),dt=(0,G.useCallback)(()=>{ut(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[ft,pt]=(0,G.useState)(new Set),mt=(0,G.useCallback)(e=>{pt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[I,L]=(0,G.useState)(new Set),[R,z]=(0,G.useState)(null),[gt,_t]=(0,G.useState)(null),vt=Bt(),yt=!!(vt&&s),bt=(0,G.useCallback)((e,t=!1)=>{if(!vt||!s)return;let n=e.map(e=>r.find(t=>t.id===e)).filter(e=>!!e);n.length!==0&&vt.openAddRelated({workspaceName:s,documents:n},t)},[vt,s,r]),[xt,wt]=(0,G.useState)(!1),[B,Dt]=(0,G.useState)(null),[Ot,kt]=(0,G.useState)(!1),[At,Mt]=(0,G.useState)(null),[Nt,Pt]=(0,G.useState)(!1),It=(0,G.useRef)(!1),Lt=(0,G.useRef)(!1),V=o===`backends`&&qe===`path`?an(a):null;(0,G.useEffect)(()=>()=>{It.current=!0},[]);let[Rt,zt]=(0,G.useState)(!1),[Vt,Ht]=(0,G.useState)(null),[Ut,Wt]=(0,G.useState)(!1),[Gt,Kt]=(0,G.useState)(null),qt=Ft()==null&&!!s,[Jt,Yt]=(0,G.useState)(null),[Zt,H]=(0,G.useState)(null),en=!!(et&&E),tn=!!s,{showSuccessToast:nn,showErrorToast:rn}=$t(),{showProgress:on}=je(),sn=Et(),cn=s?e=>sn.open(e,s):void 0,ln=qe===`workspace`,un=ln?void 0:f,dn=ln?void 0:g,[fn,pn]=(0,G.useState)(!1),[W,Sn]=(0,G.useState)(!1),[Cn,Tn]=(0,G.useState)(``),K=t??Cn,q=t!==void 0,[En,Dn]=(0,G.useState)(!1),On=Ve.length>0,kn=(0,G.useRef)(null),An=(0,G.useCallback)(()=>{Tn(``),kn.current&&(kn.current.value=``)},[]);(0,G.useEffect)(()=>{if(!de||window.matchMedia(`(max-width: 767px)`).matches)return;let e=kn.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[de]);let jn=JSON.stringify([s,o,a]),[Mn,Nn]=(0,G.useState)(jn);jn!==Mn&&(Nn(jn),L(new Set),Dt(null),_t(null),z(null)),(0,G.useEffect)(()=>{oe?.(Array.from(I))},[I,oe]);let Pn=(0,G.useCallback)(()=>{if(!Ue)return;let e=K.trim();e&&(Ue(e),An())},[Ue,K,An]),Fn=(0,G.useCallback)(()=>{An(),We&&Ve.length>0&&We(-1)},[We,Ve.length,An]),In=(0,G.useCallback)((e,t)=>{let n;I.has(t)&&I.size>1?n=Array.from(I):(n=[t],L(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:qe===`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)},[I,a,o,s,qe]),Ln=(0,G.useCallback)(async e=>{if(!E)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(),Dn(!1),!sr(n,s,o,a)&&(await E(a,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),L(new Set)))},[a,o,s,E]),zn=(0,G.useCallback)(e=>{E&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,Dn(!0))},[E]),Hn=(0,G.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||Dn(!1)},[]),Un=(0,G.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}),[]),Y=(0,G.useMemo)(()=>r.length===0?null:new mn(r,Un),[r,Un]),X=(0,G.useDeferredValue)(K),Z=(0,G.useMemo)(()=>{if(!X.trim())return r;let{text:e,ids:t,invalid:n}=Vn(X);if(n)return[];let i=e&&Y?Y.search(e).map(e=>e.item):r;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[r,X,Y]),Gn=(0,G.useMemo)(()=>{if(!nt||nt.length===0||X.trim())return[];let e=P?.order===`desc`?-1:1;return[...nt].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)},[nt,X,P?.order]),Yn=Gn.length>0,[Xn,Zn]=(0,G.useState)(null),Qn=(0,G.useMemo)(()=>s&&o&&rt?(e,t)=>Zn({x:t.clientX,y:t.clientY,path:e}):void 0,[s,o,rt]),$n={folders:Gn,onOpen:rt,onMenu:Qn,onPasteDocuments:E,contextPath:a,treeName:o,workspaceId:s},tr=(0,G.useMemo)(()=>({title:e=>N(e).title?.toLowerCase()??``,schema:e=>N(e).schemaLabel??``,type:Xe,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[]),{sorted:rr,sort:ir,toggleSort:or}=xn(Z,tr),cr=(0,G.useCallback)(e=>_r(e,P?.sortBy),[P?.sortBy]),lr=(0,G.useMemo)(()=>wr(Z,cr,P?.order===`asc`?`asc`:`desc`),[Z,cr,P?.order]),dr=lt&&!He(P?.sortBy)&&lr.length>1,fr=(0,G.useCallback)((e,t)=>{L(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),pr=(0,G.useMemo)(()=>(F===`table`?rr:dr?lr.filter(e=>!ft.has(e.key)).flatMap(e=>e.items):Z).map(e=>e.id),[F,rr,dr,lr,ft,Z]),mr=(0,G.useRef)(null),hr=JSON.stringify([s,a,o,k]),Q=(0,G.useCallback)(e=>{mr.current=null,L(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),$=(0,G.useCallback)((e,t,n,r=!1)=>{let i=mr.current,a=i?.scope===hr&&pr.includes(i.id)?i.id:null;(!r||a===null)&&(mr.current={scope:hr,id:e}),L(i=>{if(r)return Wn(pr,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[hr,pr]),vr=(0,G.useCallback)((e,t)=>{let n;I.has(e)?n=Array.from(I):(n=[e],L(new Set([e]))),z({anchor:t,ids:n})},[I]),yr=(0,G.useCallback)((e,t)=>{vr(t,Ie(e))},[vr]),br=(0,G.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),vr(t,Ir(e)))},[vr]),xr=(0,G.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){wt(!0);try{for(let n of t)await tt(s,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;nn(`Created ${n} relation${n===1?``:`s`}`),Xt(),_t(null)}catch(e){rn(e instanceof Error?e.message:`Failed to create relations`)}finally{wt(!1)}}},[s,nn,rn]),Sr=(0,G.useCallback)(async(e,t,n)=>{if(E){for(let r of e)await E(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});L(new Set)}},[E]),Cr=(0,G.useCallback)(async(e,t,n)=>{if(!s||!B||Lt.current)return;Lt.current=!0,It.current=!1,Pt(!1),kt(!0);let i=on({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${B.ids.length} document(s) · ${e.join(`, `)}`});try{let a=r=>ht(s,r,{to:e,mode:t,keepDocument:n.keepDocument,...t===`delete`&&V?{deleteFrom:{backend:V.backend,folder:V.rel}}:{},folder:n.folder,filename:n.filename,onConflict:n.onConflict}),o=t===`delete`?await Bn(B.ids,a,{shouldStop:()=>It.current,onProgress:(t,n)=>{Mt({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(B.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}. ${Tt(o.failed,new Map(r.map(e=>[e.id,N(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];Dt(g.length?{ids:g,mode:t}:null),L(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{Lt.current=!1,kt(!1),Mt(null)}},[s,B,V,r,on]),Tr=(0,G.useCallback)(()=>{I.size===Z.length?L(new Set):L(new Set(Z.map(e=>e.id)))},[I.size,Z]),Er=(0,G.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)}},[]),Dr=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=()=>L(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:se,run:()=>H({document:i})}),u(qt&&{id:`edit`,group:`open`,label:`Edit`,icon:ke,run:()=>H({document:i,edit:!0})}),u(qt&&i.schema===`data/schema/file`&&{id:`rename`,group:`open`,label:`Rename…`,icon:ke,run:()=>H({document:i,edit:!0})});let t=i.data?.url||i.data?.uri;u(qt&&s&&i.schema!==`data/schema/file`&&typeof t==`string`&&/^https?:\/\//i.test(t)&&{id:`download-link`,group:`open`,label:`Download to workspace`,icon:ie,run:async()=>{let e=on({title:`Downloading file…`});try{await Je(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:_e,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),u(cn&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:te,run:()=>cn(i)})}return u(C&&{id:`copy`,group:`clipboard`,label:`Copy${n}`,icon:we,shortcut:`Mod+C`,run:()=>C(e)}),u(ee&&{id:`cut`,group:`clipboard`,label:`Cut${n}`,icon:Te,shortcut:`Mod+X`,run:()=>ee(e)}),u(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:ce,run:()=>Er(String(i.id))}),u(i&&qt&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:xe,run:()=>Yt(i)}),u(en&&{id:`link-to`,group:`organize`,label:`Link to…${n}`,icon:re,run:()=>_t(e)}),u(yt&&{id:`add-related`,group:`organize`,label:`Add related document…${n}`,icon:b,run:t=>bt(e,t?.shiftKey)}),u(qt&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${n}`,icon:ke,run:()=>Kt(e)}),u(qt&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:we,run:t=>{Wt(!!t?.shiftKey),Ht(e)}}),u({id:`export`,group:`organize`,label:`Export…${n}`,icon:ie,run:()=>pn(!0)}),u(o!==`backends`&&(un||dn)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${n}`,icon:ve,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&un?un(e[0]):dn?.(e),a()}}),u(o!==`backends`&&(p||y)&&{id:`delete`,group:`remove`,label:`Delete from index${n}`,icon:T,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&p?p(e[0]):y?.(e),a()}}),c&&tn?(u({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${n}`,icon:De,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Dt({ids:e,mode:`copy`})}),u({id:`backend-move`,group:`backends`,label:`Move to backend…${n}`,icon:Se,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Dt({ids:e,mode:`move`})}),u({id:`backend-delete`,group:`backends`,label:`Delete from backend…${n}`,icon:T,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Dt({ids:e,mode:`delete`})})):c&&(m||x)&&u({id:`destroy`,group:`backends`,label:`Delete from backend(s)${n}`,icon:T,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&m?m(e[0]):x?.(e),a()}}),l},Or=()=>{let e=[],t=t=>{t&&e.push(t)},n=O??[];return t(E&&n.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${n.length})`,icon:pe,shortcut:`Mod+V`,run:async()=>{try{await E(a,n)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(Z.length>0&&{id:`select-all`,group:`select`,label:K?`Select all matches (${Z.length})`:`Select all on this page`,icon:he,shortcut:`Mod+A`,run:()=>L(new Set(Z.map(e=>e.id)))}),t(I.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:ye,run:()=>L(new Set)}),t(E&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:be,hint:`Browse and add existing documents to this folder`,run:()=>zt(!0)}),t(D&&{id:`import`,group:`add`,label:`Import…`,icon:w,run:()=>Sn(!0)}),t(r.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:ie,run:()=>{L(new Set),pn(!0)}}),t(Fe&&u>0&&{id:`purge`,group:`purge`,label:`Purge all (${u})`,icon:T,destructive:!0,disabled:Be||!!K,hint:K?`Purge is disabled while local search is active`:Be?`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:Fe}),e},kr=!!(Ge&&P&&s),Ar=R?R.ids?Dr(R.ids):Or():[],Mr=R?.ids?.length===1?r.find(e=>e.id===R.ids[0]):void 0,Fr=Mr?(0,J.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,J.jsx)(U,{document:Mr,chip:!0}),(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsx)(`div`,{className:`truncate text-base font-semibold`,children:N(Mr).title}),(0,J.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Mr.id,` · `,Mr.schema]})]})]}):(0,J.jsx)(`div`,{className:`truncate text-base font-semibold`,children:R?.ids?`${R.ids.length} documents`:`This folder`}),Lr=e=>{z({anchor:Ie(e.currentTarget),ids:I.size>0?Array.from(I):null})},Rr=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),L(new Set),z({anchor:Ir(e),ids:null}))},zr=e=>{if(e.defaultPrevented||Le(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Pe(e)){e.preventDefault(),t?vr(Number(t.dataset.documentId),Ie(t,`inside`)):z({anchor:Ie(e.target,`inside`),ids:I.size>0?Array.from(I):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&&$(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&I.size>0){e.preventDefault(),L(new Set);return}ze(e,[...Dr(Array.from(I)),...Or()])},Hr=(0,G.useCallback)(async e=>{if(!D)return!1;try{return await D(e,a)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[D,a]),Ur=e=>dr?lr.map(t=>{let n=ft.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!I.has(t),0);return(0,J.jsxs)(`section`,{className:`group mb-4`,children:[(0,J.jsx)(ri,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>mt(t.key),onSelectAll:e=>fr(r,e)}),!n&&e(t.items)]},t.key)}):e(Z);return i?(0,J.jsx)(Rn,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:[],loading:!0,children:(0,J.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,J.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,J.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})})}):(0,J.jsx)(Rn,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:F===`table`?rr:Z,loading:!1,children:(0,J.jsxs)(`div`,{tabIndex:-1,onKeyDown:zr,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${En?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:zn,onDragLeave:Hn,onDrop:Ln,children:[(0,J.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,J.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,J.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,J.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,J.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:K?`${Z.length} of ${r.length}`:`${u.toLocaleString()} document${u===1?``:`s`}`})]}),(0,J.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,J.jsxs)(`p`,{hidden:q,className:`min-w-0 truncate`,children:[`Context: `,(0,J.jsx)(`span`,{className:`font-mono`,children:a}),me&&ge&&me!==ge&&(0,J.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,J.jsxs)(`p`,{className:`shrink-0`,children:[I.size>0&&(0,J.jsxs)(`span`,{className:`text-info`,children:[I.size,` selected`]}),I.size>0&&(K||u>A)&&(0,J.jsx)(`span`,{className:`mx-1`,children:`·`}),K?`on this page`:u>A?`Showing ${Math.min((k-1)*A+1,u)}–${Math.min(k*A,u)}`:null]})]})]}),!q&&(0,J.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,J.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[!q&&Ye&&(0,J.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,J.jsx)(`button`,{type:`button`,onClick:()=>Ye(`path`),className:`px-2.5 py-2 transition-colors ${qe===`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,J.jsxs)(`button`,{type:`button`,onClick:()=>Ye(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${qe===`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,J.jsx)(h,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!q&&(0,J.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,J.jsx)(Ee,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,J.jsx)(`input`,{ref:kn,type:`text`,placeholder:Ue?On?`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=>Tn(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`&&Ue&&(e.preventDefault(),Pn())},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`}),Ue&&s&&(0,J.jsx)(St,{workspaceId:s,inputRef:kn,onChange:Tn}),(K||On)&&(0,J.jsx)(`button`,{onClick:Fn,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,J.jsx)(v,{className:`h-4 w-4`})})]}),!q&&Ue&&K.trim()&&!Ve.includes(K.trim())&&(0,J.jsxs)(M,{size:`sm`,variant:`default`,onClick:Pn,className:`shrink-0`,title:On?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,J.jsx)(Ee,{className:`h-3.5 w-3.5 mr-1`}),On?`Refine`:`Search server`]})]}),!q&&On&&(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,J.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),Ve.map((e,t)=>(0,J.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,J.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,J.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,J.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),We&&(0,J.jsx)(`button`,{onClick:()=>We(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,J.jsx)(v,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),We&&Ve.length>1&&(0,J.jsx)(`button`,{onClick:()=>We(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,J.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,J.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,J.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,J.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[de&&(0,J.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,ae,`Tile view`],[`card`,Ce,`Card view`]].map(([e,t,n])=>(0,J.jsx)(`button`,{type:`button`,onClick:()=>ct(e),title:n,"aria-pressed":F===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${F===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,J.jsx)(t,{className:`h-4 w-4`})},e))}),de&&F!==`table`&&!He(P?.sortBy)&&(0,J.jsx)(`button`,{type:`button`,onClick:dt,title:lt?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":lt,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${lt?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,J.jsx)(_,{className:`h-4 w-4`})})]}),j&&u>0&&(0,J.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,J.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,J.jsxs)(`select`,{value:A,onChange:e=>Ae?.(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,J.jsx)(`option`,{value:25,children:`25`}),(0,J.jsx)(`option`,{value:50,children:`50`}),(0,J.jsx)(`option`,{value:100,children:`100`}),(0,J.jsx)(`option`,{value:200,children:`200`})]}),(0,J.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,J.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[kr&&(0,J.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,J.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,J.jsx)(gr,{workspaceId:s,value:P,onChange:Ge})]}),(0,J.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(r.length>0||D||E)&&(0,J.jsxs)(`div`,{className:`contents`,children:[(0,J.jsxs)(M,{variant:`outline`,size:`sm`,onClick:Lr,"aria-haspopup":`menu`,"aria-label":I.size>0?`Actions (${I.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${Ne(`Shift+F10`)} or right-click)`,children:[(0,J.jsx)(ue,{className:`h-4 w-4`}),(0,J.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,I.size>0?` (${I.size} selected)`:``]})]}),I.size>0&&(0,J.jsxs)(M,{variant:`ghost`,size:`sm`,onClick:()=>L(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,J.jsx)(v,{className:`h-3.5 w-3.5`}),(0,J.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),O&&O.length>0&&E&&(0,J.jsxs)(M,{variant:`outline`,size:`sm`,onClick:()=>E(a,O),className:`flex items-center gap-1.5`,title:`Paste into this folder (${Ne(`Mod+V`)})`,children:[(0,J.jsx)(pe,{className:`h-4 w-4`}),`Paste (`,O.length,`)`]})]}),Ze&&$e&&(0,J.jsx)(M,{size:`sm`,variant:`outline`,onClick:$e,disabled:Qe,className:`w-control-sm shrink-0 px-0 touch-target`,"aria-label":Qe?`Saving filters`:`Save current query and filters`,title:`Save current query and filters`,children:(0,J.jsx)(d,{className:`h-3.5 w-3.5`})}),n]})]})]})}),j&&u>A&&(0,J.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,J.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((k-1)*A+1,u),` - `,Math.min(k*A,u),` of `,u]}),(0,J.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>j(1),disabled:k===1,className:`p-1 touch-target`,children:(0,J.jsx)(Oe,{className:`h-4 w-4`})}),(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>j(k-1),disabled:k===1,className:`p-1 touch-target`,children:(0,J.jsx)(ne,{className:`h-4 w-4`})}),(0,J.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,J.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),k,(0,J.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,J.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(u/A)]}),(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>j(k+1),disabled:k>=Math.ceil(u/A),className:`p-1 touch-target`,children:(0,J.jsx)(l,{className:`h-4 w-4`})}),(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>j(Math.ceil(u/A)),disabled:k>=Math.ceil(u/A),className:`p-1 touch-target`,children:(0,J.jsx)(S,{className:`h-4 w-4`})})]})]})]}),(0,J.jsx)(er,{scope:JSON.stringify([hr,F,pr]),selected:I,onSelectionChange:Q,onContextMenu:Rr,children:Z.length===0&&!Yn?(0,J.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,J.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,J.jsx)(fe,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:K?`No documents match your search`:`No documents found in this context`}),(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:K?(0,J.jsxs)(J.Fragment,{children:[`Search: `,(0,J.jsxs)(`span`,{className:`font-mono`,children:[`"`,K,`"`]})]}):(0,J.jsxs)(J.Fragment,{children:[`Path: `,(0,J.jsx)(`span`,{className:`font-mono`,children:a})]})}),!q&&K&&(0,J.jsx)(`button`,{onClick:An,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!K&&O&&O.length>0&&(0,J.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,Ne(`Mod+V`),` to paste `,O.length,` document(s)`]})]})}):F===`tile`?(0,J.jsxs)(`div`,{children:[(0,J.jsx)(ei,{...$n}),Z.length===0&&(0,J.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Ur(e=>(0,J.jsx)(`div`,{className:`document-tiles pr-2`,"data-tile-style":at,children:e.map(e=>(0,J.jsx)(qr,{document:e,isSelected:I.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:cn,onRightClick:br,onOpenActions:yr,onDragStart:In},e.id))}))]}):F===`table`?(0,J.jsx)(`div`,{children:(0,J.jsxs)(yn,{children:[(0,J.jsx)(bn,{children:(0,J.jsxs)(hn,{children:[(0,J.jsx)(vn,{className:`w-10`,children:(0,J.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:Z.length>0&&I.size===Z.length,ref:e=>{e&&(e.indeterminate=I.size>0&&I.size<Z.length)},onChange:Tr,title:`Select all on this page`})}),(0,J.jsx)(_n,{label:(0,J.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:ir,onSort:or,className:`w-12`}),(0,J.jsx)(_n,{label:`Title`,sortKey:`title`,sort:ir,onSort:or,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,J.jsx)(_n,{label:`Schema`,sortKey:`schema`,sort:ir,onSort:or,className:`hidden md:table-cell`}),(0,J.jsx)(_n,{label:`ID`,sortKey:`id`,sort:ir,onSort:or,className:`hidden lg:table-cell`}),(0,J.jsx)(vn,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,J.jsx)(_n,{label:`Created`,sortKey:`created`,sort:ir,onSort:or,className:`hidden sm:table-cell`}),(0,J.jsx)(vn,{className:`w-12 md:w-auto`,children:(0,J.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,J.jsxs)(gn,{children:[Gn.map(e=>(0,J.jsx)(ni,{folder:e,onOpen:rt,onMenu:Qn,onPasteDocuments:E,contextPath:a,treeName:o,workspaceId:s},e.path)),rr.map(e=>(0,J.jsx)(Br,{document:e,isSelected:I.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:cn,onRightClick:br,onOpenActions:yr,onDragStart:In},e.id))]})]})}):(0,J.jsxs)(`div`,{children:[(0,J.jsx)(ti,{...$n}),Z.length===0&&(0,J.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Ur(e=>(0,J.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,J.jsx)(`div`,{children:(0,J.jsx)(Vr,{document:e,isSelected:I.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:cn,onRightClick:br,onOpenActions:yr,onDragStart:In})},e.id))}))]})}),R&&(0,J.jsx)(Me,{anchor:R.anchor,items:Ar,onClose:()=>z(null),label:R.ids?`Document actions`:`Folder actions`,header:Fr}),(0,J.jsx)(Nr,{isOpen:fn,onClose:()=>pn(!1),documents:r,selectedDocuments:I}),(0,J.jsx)(Pr,{isOpen:W,onClose:()=>Sn(!1),onImport:Hr}),Vt&&s&&(0,J.jsx)(nr,{modal:Ut,workspaceId:s,ids:Vt,onClose:()=>Ht(null)}),gt&&et&&(0,J.jsx)(qn,{label:`Link to`,onClose:()=>_t(null),children:(0,J.jsx)(Re,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:gt.length,fixedWorkspaceName:s,tabs:[`context`,`directory`,`relations`],saving:xt,relationExcludeIds:new Set(gt),onConfirm:(e,t)=>Sr(e,gt,t),onConfirmRelation:e=>xr(e,gt),onClose:()=>_t(null)})}),B&&s&&(0,Kn.createPortal)((0,J.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,J.jsx)(Ct,{workspaceId:s,documentCount:B.ids.length,initialMode:B.mode,defaultFilename:B.ids.length===1?Ke(r.find(e=>e.id===B.ids[0])??{}):``,saving:Ot,progress:At,stopping:Nt,onStop:()=>{It.current=!0,Pt(!0)},deleteFrom:V?{backend:V.backend,folder:V.rel}:void 0,onConfirm:Cr,onClose:()=>{Ot||Dt(null)}})}),window.document.body),Rt&&E&&(0,Kn.createPortal)((0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>zt(!1),"aria-hidden":!0}),(0,J.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,J.jsx)(Qt,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:s,onConfirm:async e=>{await E(a,e),zt(!1)},onClose:()=>zt(!1)})})]}),window.document.body),Jt&&s&&(0,J.jsx)(Jn,{workspaceId:s,document:Jt,onClose:()=>Yt(null)},`${s}:${Jt.id}`),Gt&&s&&(0,J.jsx)(ar,{workspaceId:s,documentIds:Gt,onClose:()=>Kt(null)}),(0,J.jsx)(ur,{document:Zt?.document??null,isOpen:!!Zt,onClose:()=>H(null),workspaceId:s,initialEdit:Zt?.edit}),Xn&&s&&o&&rt&&(0,J.jsx)(jr,{x:Xn.x,y:Xn.y,workspaceName:s,treeName:o,path:Xn.path,onClose:()=>Zn(null),onOpen:rt,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:s,treeName:o,path:e}})),pastedDocumentIds:O,onPasteDocuments:E?(e,t)=>E(e,t):void 0})]})})}function ai(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,cr.createRoot)(t);n.render((0,J.jsx)(Pr,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function oi(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,cr.createRoot)(t);n.render((0,J.jsx)(Nr,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{gr as a,sr as c,Un as d,Ln as f,wn as h,kr as i,ar as l,jn as m,Ar as n,fr as o,Pn as p,Or as r,ur as s,ii as t,qn as u};
|