@augmentd-labs/canvas-web 2.26.43 → 2.26.45

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.
Files changed (119) hide show
  1. package/dist/assets/CalendarApplet-CsyUmI2B.js +2 -0
  2. package/dist/assets/{DocumentBodyEditor-CVO5KPCs.js → DocumentBodyEditor-C8AEpqX3.js} +1 -1
  3. package/dist/assets/{DocumentIcon-9i1uCMQa.js → DocumentIcon-0ya9gycp.js} +1 -1
  4. package/dist/assets/{EditorOverlay-D5t3xg4w.js → EditorOverlay-DglJkHo3.js} +1 -1
  5. package/dist/assets/{FiltersApplet-gQ6jhX7q.js → FiltersApplet-CVnCAs-P.js} +1 -1
  6. package/dist/assets/HomeFab-iC5BF7LV.js +3 -0
  7. package/dist/assets/{IdentityFields-D-NCTUaE.js → IdentityFields-CB3Ap0bl.js} +1 -1
  8. package/dist/assets/{LensApplet-WFygUZx1.js → LensApplet-DA0ZWS1k.js} +1 -1
  9. package/dist/assets/LinkToCard-oi3wGP0a.js +1 -0
  10. package/dist/assets/{MarkdownEditor-DbpRWbO6.js → MarkdownEditor-bDoyR7l2.js} +2 -2
  11. package/dist/assets/{MessageComposerDialog-CdPp-3GR.js → MessageComposerDialog-CLrwtB76.js} +1 -1
  12. package/dist/assets/{NextShell-ull6WmMg.js → NextShell-DCWxD5TR.js} +1 -1
  13. package/dist/assets/{NotesApplet-D8cseekh.js → NotesApplet-BSJ-9RKl.js} +1 -1
  14. package/dist/assets/ObjectPropertiesCard-DesXRw-_.js +8 -0
  15. package/dist/assets/{PathPickerField-CW2yG2Yg.js → PathPickerField-CSIa7jSl.js} +1 -1
  16. package/dist/assets/PickDocumentsCard-DVdBxx3s.js +1 -0
  17. package/dist/assets/{SketchApplet-BKnhzTBA.js → SketchApplet--3uyqpmo.js} +1 -1
  18. package/dist/assets/{SketchEditor-DmGMcbU0.js → SketchEditor-CSA7dTyq.js} +2 -2
  19. package/dist/assets/{TerminalApplet-D7YxftqM.js → TerminalApplet-BZJx2ztD.js} +1 -1
  20. package/dist/assets/{TextDocumentEditor-BQnVD0dd.js → TextDocumentEditor-VYIF2XCX.js} +1 -1
  21. package/dist/assets/{TodosApplet-DU5VWc5i.js → TodosApplet-DY7JzeZS.js} +1 -1
  22. package/dist/assets/{TodosWidget-CNnfNk4L.js → TodosWidget-DGftEAbs.js} +1 -1
  23. package/dist/assets/{_agentId_-DVR-2m5A.js → _agentId_-BrzFDu8r.js} +0 -0
  24. package/dist/assets/{_contextId_-BofzZDP6.js → _contextId_-DS6b9Uml.js} +1 -1
  25. package/dist/assets/_workspaceName_-XRqfa4c6.js +1 -0
  26. package/dist/assets/{about-lxN3BXmR.js → about-hcdKJNm5.js} +1 -1
  27. package/dist/assets/{add-LFFQQgj3.js → add-CEBusWuu.js} +1 -1
  28. package/dist/assets/{agents-DxqAi3vk.js → agents-BfSFdg41.js} +1 -1
  29. package/dist/assets/{agents-DHexvztp.js → agents-wFp7Vh3p.js} +1 -1
  30. package/dist/assets/{alert-dialog-CFeuDt0T.js → alert-dialog-BKtaX1_a.js} +1 -1
  31. package/dist/assets/{api-tokens-drrVuCYc.js → api-tokens-Biqt5TnG.js} +1 -1
  32. package/dist/assets/{appearance-0-j0SAoe.js → appearance-D5BUjZm8.js} +1 -1
  33. package/dist/assets/{applet-target-pLdP-R76.js → applet-target-LvhUEvE5.js} +1 -1
  34. package/dist/assets/{apps-ylUU3K5c.js → apps-65YXCnzH.js} +1 -1
  35. package/dist/assets/{auth-PqttD05H.js → auth-BwxT5xRB.js} +1 -1
  36. package/dist/assets/{button-SeUZ_Pvi.js → button--VYZekMF.js} +1 -1
  37. package/dist/assets/{context-t3rdtGUB.js → context-DY40EDc6.js} +1 -1
  38. package/dist/assets/{contexts-DDJagU4j.js → contexts-BPO_Wb9W.js} +1 -1
  39. package/dist/assets/{contexts-Bq8LHUTK2.js → contexts-DBJ0_-AO2.js} +1 -1
  40. package/dist/assets/{date-time-picker-DCikruos.js → date-time-picker-p3vy4nst.js} +1 -1
  41. package/dist/assets/{devices-BwU9M8-W.js → devices-DZbbaWYU.js} +1 -1
  42. package/dist/assets/{document-Cr7GhnVd.js → document-Dv8NCUoM.js} +1 -1
  43. package/dist/assets/document-list-Bbbx-pTZ.js +3 -0
  44. package/dist/assets/document-paste-BuTC6S7_.js +1 -0
  45. package/dist/assets/{embedding-D-I_ygUZ.js → embedding-B9vSy_a9.js} +1 -1
  46. package/dist/assets/{embedding-BvXcVfij.js → embedding-M2hUmnk0.js} +1 -1
  47. package/dist/assets/{form-panel-3p-ncEVK.js → form-panel-CEbNKttr.js} +1 -1
  48. package/dist/assets/{home-CfYR15C5.js → home-vr8b8oR-.js} +1 -1
  49. package/dist/assets/index-CTvqbEB8.js +16 -0
  50. package/dist/assets/index-CoVFQpP3.css +2 -0
  51. package/dist/assets/{inferd-config-editor-B8x_XPOt.js → inferd-config-editor-Dpdj90iN.js} +1 -1
  52. package/dist/assets/{key-bindings-DAIw70SC.js → key-bindings-DmqvYSaF.js} +1 -1
  53. package/dist/assets/{label-BSTdjCWU.js → label-RuOXXC8t.js} +1 -1
  54. package/dist/assets/{lazy-editor-BUFAkTGl.js → lazy-editor-CShGeIep.js} +2 -2
  55. package/dist/assets/{logs-DjG8_wJ2.js → logs-7eSz9yjc.js} +1 -1
  56. package/dist/assets/{offline-ByoT6JJX.js → offline-C-Yvb6LA.js} +1 -1
  57. package/dist/assets/{page-header-DrDt1sQ2.js → page-header-NyYSXjfY.js} +1 -1
  58. package/dist/assets/{public-share-CXR25Q1X.js → public-share-0DqS7L2Q.js} +1 -1
  59. package/dist/assets/{query-debug-lD5vbJGi.js → query-debug-PEWbZsOP.js} +1 -1
  60. package/dist/assets/registry-g1SKt_fD.js +2 -0
  61. package/dist/assets/{remotes-RPGcw6fH.js → remotes-DqCLds8Q.js} +1 -1
  62. package/dist/assets/{roles-sb8vgjV_.js → roles-BwVDE1aQ.js} +1 -1
  63. package/dist/assets/{roles-p2cRajz-.js → roles-W7oJ5WMg.js} +1 -1
  64. package/dist/assets/rule-builder-CziPqpNe.js +6 -0
  65. package/dist/assets/settings-BIoSwdXv.js +16 -0
  66. package/dist/assets/{settings-C5cS_cw0.js → settings-BWCMmkjr.js} +1 -1
  67. package/dist/assets/{settings-Bojeuvgh.js → settings-CbMkpipO.js} +1 -1
  68. package/dist/assets/settings-XMhqrvTu.js +1 -0
  69. package/dist/assets/{share-target-PgtwhQo-.js → share-target-hDXdgW6o.js} +1 -1
  70. package/dist/assets/{shared-BLOuO2Is.js → shared-CLjTxih0.js} +1 -1
  71. package/dist/assets/{shared-fdwDs5-g.js → shared-DVlDThVA.js} +1 -1
  72. package/dist/assets/sketch-lazy-CtjOUfVz.js +2 -0
  73. package/dist/assets/{subtree-transfer-dialog-DQM5zfx2.js → subtree-transfer-dialog-DtE6JSUr.js} +1 -1
  74. package/dist/assets/{text-documents-Cdb3U63i.js → text-documents-wu6fzOuw.js} +2 -2
  75. package/dist/assets/tree-folders-IDoobsGN.js +1 -0
  76. package/dist/assets/ui-DEgHnkQu.js +41 -0
  77. package/dist/assets/{use-applet-docs-rimRHjID.js → use-applet-docs-C08GAUm3.js} +1 -1
  78. package/dist/assets/{use-applet-target-BygCSj5n.js → use-applet-target-BlpVWlnA.js} +1 -1
  79. package/dist/assets/{use-canvas-pins-Bmj8upH3.js → use-canvas-pins-q5Tncavk.js} +2 -2
  80. package/dist/assets/{use-menu-DIP1zh7I.js → use-menu-CKSpS96u.js} +1 -1
  81. package/dist/assets/use-settings-back-D_MM9diy.js +1 -0
  82. package/dist/assets/{use-sortable-data-BBKmqs79.js → use-sortable-data-D7zS2qCC.js} +1 -1
  83. package/dist/assets/{use-workspace-identity-CSkRwVyo.js → use-workspace-identity-XSv3dATQ.js} +1 -1
  84. package/dist/assets/{useAddTarget-DeRZWtGg.js → useAddTarget-BvuFR5pN.js} +1 -1
  85. package/dist/assets/{useAgentModels-DLjVm0T8.js → useAgentModels-CI9XT6yc.js} +1 -1
  86. package/dist/assets/{useDocumentThumbnail-Cj4UYyhC.js → useDocumentThumbnail-CZIaXkIi.js} +1 -1
  87. package/dist/assets/{useEditNoteFields-BT1ASu_q.js → useEditNoteFields-DsVKIHWm.js} +1 -1
  88. package/dist/assets/{users-DuVk-TEd.js → users-DzlbKZp6.js} +1 -1
  89. package/dist/assets/workspace-4hWrSEku.js +1 -0
  90. package/dist/assets/{workspace-content-gate-C54J9Man.js → workspace-content-gate-BlFdbi67.js} +1 -1
  91. package/dist/assets/{workspace-import-form-DTvV9jYt.js → workspace-import-form-CWs9ZTts.js} +1 -1
  92. package/dist/assets/{workspaces-CqHYstZv.js → workspaces-67v2hWrl.js} +1 -1
  93. package/dist/assets/workspaces-ByYQ6L3I.js +1 -0
  94. package/dist/index.html +36 -38
  95. package/dist/sw.js +1 -1
  96. package/package.json +2 -2
  97. package/dist/assets/CalendarApplet-JRMqt67k.js +0 -2
  98. package/dist/assets/FileForm-CDiVKvxq.js +0 -1
  99. package/dist/assets/HomeFab-Bp9cpmps.js +0 -3
  100. package/dist/assets/LinkToCard-CKVi4Nrg.js +0 -1
  101. package/dist/assets/ObjectPropertiesCard-D2lrTQqT.js +0 -8
  102. package/dist/assets/PickDocumentsCard-BWgc-A02.js +0 -1
  103. package/dist/assets/UploadProgressList-D2wEpa7t.js +0 -1
  104. package/dist/assets/_workspaceName_-Ds__P3h9.js +0 -1
  105. package/dist/assets/backend-sync-progress-Dp12uN4y.js +0 -6
  106. package/dist/assets/document-list-BLu9S0zR.js +0 -3
  107. package/dist/assets/index-BNP_llN_.js +0 -16
  108. package/dist/assets/index-CYvpxvg6.css +0 -2
  109. package/dist/assets/registry-H_3ckTyM.js +0 -2
  110. package/dist/assets/settings-COqQc1hP.js +0 -16
  111. package/dist/assets/settings-DziSEdYH.js +0 -1
  112. package/dist/assets/sketch-lazy-BY_ka1hw.js +0 -2
  113. package/dist/assets/tree-folders-Da9k9cbV.js +0 -1
  114. package/dist/assets/ui-CDoK3F3U.js +0 -41
  115. package/dist/assets/use-settings-back-DGmLAD63.js +0 -1
  116. package/dist/assets/workspace-C5V-ZCOE.js +0 -1
  117. package/dist/assets/workspace-area-menu-LLSySOlH.js +0 -1
  118. package/dist/assets/workspaces-DxvxX0wQ.js +0 -1
  119. /package/dist/assets/{backend-sync-progress-DU-e9TWi.css → rule-builder-DU-e9TWi.css} +0 -0
@@ -1,6 +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,Bn as i,Bt as a,Ct as o,L as s,Mn as c,Pr as l,Pt as u,Q as d,Ur as ee,X as f,Y as p,Yn as m,Z as h,ai as te,cn as g,di as _,pn as v,qn as ne,st as y,ti as re,vr as b}from"./ui-CDoK3F3U.js";import{t as x}from"./utils-2pl1SbIp.js";import{t as S}from"./button-SeUZ_Pvi.js";import{t as C}from"./input-BOtCd4HP.js";import{t as w}from"./api-CA6WiiYM.js";import{t as T}from"./socket-CtH3EU9m.js";import{n as ie}from"./use-toast-BlLDqSUO.js";import{t as ae}from"./LinkToCard-CKVi4Nrg.js";import{H as oe,cn as se,sn as ce,vt as le}from"./workspace-C5V-ZCOE.js";import{i as ue}from"./MessageComposerDialog-CdPp-3GR.js";import{n as de}from"./LinkToSidePanel-eCy3nW4R.js";import{t as fe}from"./PathPickerField-CW2yG2Yg.js";var E=e(n(),1);function D(e){return`/workspaces/${e}/hooks`}async function O(e){return await w.get(D(e))||[]}async function k(e,t){return(await w.get(`${D(e)}/${t}`))?.content??``}async function A(e,t,n){await w.put(`${D(e)}/${t}`,{content:n})}async function j(e,t){await w.delete(`${D(e)}/${t}`)}var pe=[`example-`,`disabled-`,`_`];function M(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function me(e){return pe.find(t=>e.startsWith(t))??null}function he(e){return me(M(e).base)===null}function N(e){return M(e).base.startsWith(`example-`)}function ge(e){let{dir:t,base:n}=M(e),r=me(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function _e(e,t,n){if(he(t)===n)return t;let r=ge(t);return await A(e,r,await k(e,t)),await j(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 P=`rules.json`;async function we(e){try{let t=await k(e,P),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Te(e,t){await A(e,P,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
2
- `)}async function Ee(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(),i=await w.getEnvelope(`${D(e)}/pending${r?`?${r}`:``}`),a=i.payload||[];return{actions:a,total:i.totalCount??a.length}}async function De(e,t){return await w.post(`${D(e)}/pending/decisions`,t)}async function Oe(e,t){return w.post(`${D(e)}/pending/decisions/all`,t)}async function ke(e){return await w.get(`${D(e)}/pending/decisions/all`)??null}async function Ae(e,t){return await w.get(`${D(e)}/runs/${encodeURIComponent(t)}`)}async function je(e,t={}){let n=new URLSearchParams;t.limit&&n.set(`limit`,String(t.limit)),t.handler&&n.set(`handler`,t.handler),t.event&&n.set(`event`,t.event),t.failed&&n.set(`failed`,`true`);let r=n.toString();return await w.get(`${D(e)}/runs${r?`?${r}`:``}`)||[]}var F=1e4,Me=`canvas.hooks.backfillLimit`;function Ne(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?500:Math.min(t,F)}function Pe(){try{let e=localStorage.getItem(Me);return e?Ne(e):500}catch{return 500}}function Fe(e){let t=Ne(e);try{localStorage.setItem(Me,String(t))}catch{}return t}function Ie(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 Le(e,t){return await w.post(`${D(e)}/backfill`,t)}function Re(e,t){return w.post(`${D(e)}/backfill/jobs`,t)}function I(e,t){return w.get(`${D(e)}/backfill/jobs/${t}`)}function ze(e,t){return w.delete(`${D(e)}/backfill/jobs/${t}`)}function Be(e){return w.get(`${D(e)}/backfill/jobs`)}async function L(e,t){return await w.post(`${D(e)}/run`,t)}async function R(e,t){return await w.post(`${D(e)}/runs/${t}/replay`,{})}async function Ve(e){return await w.get(`${D(e)}/meta`)}async function He(e,t){return await w.post(`${D(e)}/generate`,t)}async function Ue(e,t){let n=await k(e,P),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 A(e,P,JSON.stringify(o,null,2)+`
3
- `)}var We=Ue;function Ge(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 z=`Applying rules to existing documents…`,B=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=B.get(n.id);if(r)return r;let i=new Promise(r=>{let i={channel:`workspace:${t}`},a=e({title:z,description:V(n),action:{label:`Cancel`,onClick:()=>{a.update({title:`Cancelling…`,description:V(n)}),ze(t,n.id).catch(()=>a.update({title:z,description:`Could not cancel. Try again.`}))}}}),o=()=>{u?.(),T.off(`job.progress`,c),T.off(`job.finished`,c),r()},s=e=>{if(e.status===`running`)return a.update({title:z,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=()=>{T.emit(`subscribe`,i),I(t,n.id).then(s,()=>{})},u=T.on(`connect`,l);T.on(`job.progress`,c),T.on(`job.finished`,c),l()});return B.set(n.id,i),i.finally(()=>B.delete(n.id)),i}async function qe(e,t,n){let r;try{r=await Re(t,{ruleIds:n,limit:Pe()})}catch(t){e({title:z}).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 Be(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 w.get(U(e))||[]}async function Xe(e,t){return(await w.get(`${U(e)}/${t}`))?.content??``}async function Ze(e,t,n){await w.put(`${U(e)}/${t}`,{content:n})}async function Qe(e,t){await w.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.moved`,label:`is moved or renamed`,hint:`Fires when the file behind the item changes its path. Its content and modified date stay the same.`},{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:g,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:g,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:g,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:i,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:b,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:m,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:m,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:te,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:re,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`},{key:`script`,label:`run a script`,icon:h,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,deleteSource:!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:g,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:g,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:i,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:c,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:m,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:g,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:b,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:re,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:y,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=>/^(ctx|context|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 Context, Directory or Backends source 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.deleteSource?{deleteSource:!0}:{},...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.deleteSource?{deleteSource:!0}:{},...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:ee,eventPathExact:f,mime:p,url:m,attachment:h,...te}=e.when;if(Object.keys(te).length>0)return null;let g=Array.isArray(t)?t:[t];if(!g.length||!g.every(e=>typeof e==`string`&&et.some(t=>t.value===e))||n!==void 0&&typeof n!=`string`)return null;let _=[],v=(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)_.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;_.push({field:e,value:t.equals})}else if([`from`,`to`,`subject`,`body`,`sender`].includes(e))for(let t of n)if(typeof t==`string`)_.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`)_.push({field:`${e}Exact`,value:t.equals});else if(t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.regex==`string`)_.push({field:`${e}Regex`,value:t.regex});else return!1;else{if(!n.every(e=>typeof e==`string`))return!1;_.push({field:e,value:n.join(` | `)})}return!0};if(d!==void 0&&!v(`path`,d)||ee!==void 0&&!v(`pathExact`,ee)||f!==void 0&&!v(`eventPathExact`,f)||p!==void 0&&!v(`mime`,p)||r!==void 0&&!v(`from`,r)||i!==void 0&&!v(`to`,i)||a!==void 0&&!v(`subject`,a)||o!==void 0&&!v(`body`,o)||s!==void 0&&!v(`sender`,s)||c!==void 0&&!v(`threadExact`,c)||l!==void 0&&!v(`channelExact`,l)||u!==void 0&&!v(`platformExact`,u)||h!==void 0&&!v(`attachment`,h))return null;if(m!==void 0){if(typeof m==`string`)_.push({field:`urlContains`,value:m});else if(m&&typeof m==`object`){let e=m;if(Object.keys(e).filter(e=>e!==`host`&&e!==`contains`&&e!==`regex`).length||e.host!==void 0&&!v(`urlHost`,e.host)||e.contains!==void 0&&!v(`urlContains`,e.contains)||e.regex!==void 0&&!v(`urlRegex`,e.regex))return null}else return null}let ne=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}},y=[];for(let t of e.then||[]){if(t.approval!==void 0)return null;if(t.action===`link`&&Array.isArray(t.paths))y.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))y.push({...K(`unlink`),a:t.paths.join(`, `),recursive:t.recursive===!0});else if(t.action===`tag`&&Array.isArray(t.tags))y.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;y.push({...K(`moveMessage`),a:t.folder})}else if(t.action===`notify`&&typeof t.message==`string`)y.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(_)===null)||t.recursive===!0&&Y(_)!==null&&t.pathMode!==`full`||t.folder!==void 0&&typeof t.folder!=`string`||t.key!==void 0&&typeof t.key!=`string`)return null;let e=typeof t.key==`string`?t.key:``;y.push({...K(`store`),a:t.to,b:e===ot||e===G?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,deleteSource:t.deleteSource===!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;y.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;y.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`,`deleteSource`]);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;y.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,deleteSource:t.deleteSource===!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:``;y.push({...K(`unstore`),a:e(t.from),b:e(t.ifOn),keepLast:t.keepLast!==!1})}else if(t.action===`delete`)y.push(K(`delete`));else if(t.action===`destroy`)y.push(K(`destroy`));else if(t.action===`agent`&&typeof t.slug==`string`&&typeof t.prompt==`string`){let e=ne(t);if(!e)return null;y.push({...K(`agent`),a:t.slug,b:t.prompt,...e})}else if(t.action===`script`&&typeof t.path==`string`){let e=ne(t);if(!e)return null;y.push({...K(`script`),a:t.path,...e})}else return null}return{id:e.id,description:e.description||``,events:g,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:_,actions:y.length?y:[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:x(`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:x(`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:x(`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:x(`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:x(`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:x(`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:x(`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:i,prefill:c,onPrefillConsumed:d,createOnly:p=!1,onCreated:h,onCancel:te}){let{showToast:g,showProgress:re}=ie(),[b,w]=(0,E.useState)([]),[T,oe]=(0,E.useState)({}),se=e=>{je(e,{limit:500}).then(e=>oe(St(e))).catch(()=>oe({}))},[ce,D]=(0,E.useState)(!0),[O,k]=(0,E.useState)(null),[A,j]=(0,E.useState)(!1),[pe,M]=(0,E.useState)(!1),[me,he]=(0,E.useState)([]),[N,ge]=(0,E.useState)([]),[_e,ve]=(0,E.useState)([]),[ye,Se]=(0,E.useState)(``),Ce=(0,E.useRef)(null),[P,Ee]=(0,E.useState)(e);e!==P&&(Ee(e),D(!0)),(0,E.useEffect)(()=>{we(e).then(e=>w(e)).finally(()=>D(!1)),se(e)},[e]);let[De,Oe]=(0,E.useState)(null);c!==De&&(Oe(c),c&&(k(Tt(c)),j(!1))),(0,E.useEffect)(()=>{c&&d?.()},[c,d]),(0,E.useEffect)(()=>{Ye(e).then(e=>he(e.map(e=>e.path))).catch(()=>he([]))},[e]),(0,E.useEffect)(()=>{let t=!1;return ue(e).then(e=>{t||(ve([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),Se(``))}).catch(()=>{t||(ve([]),Se(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,E.useEffect)(()=>{le(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);ge(t);let n=wt(t);n&&k(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(()=>ge([]))},[e]);let[ke,Ae]=(0,E.useState)($e);(0,E.useEffect)(()=>{Ve(e).then(e=>{e.schemas?.length&&Ae([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let F=async(t,n)=>{M(!0);try{return await Te(e,t),w(t),g({title:n,description:`rules.json updated (committed to workspace git)`}),!0}catch(e){return g({title:`Error`,description:e instanceof Error?e.message:`Failed to save rules`,variant:`destructive`}),!1}finally{M(!1)}},Me=async()=>{if(!O||ce||pe)return;let t;try{t=mt(O,N)}catch(e){g({title:`Invalid rule`,description:e instanceof Error?e.message:`Check the rule conditions and actions`,variant:`destructive`});return}if(!t.then.length){g({title:`Add an action`,description:`Pick at least one "then" action and fill in its fields.`,variant:`destructive`});return}if(p){t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`,M(!0);try{await Ue(e,t),g({title:`Rule created`,description:`The rule will run for matching new items.`}),h?.()}catch(e){g({title:`Could not create rule`,description:e instanceof Error?e.message:`Failed to save rule`,variant:`destructive`})}finally{M(!1)}return}!O.id&&b.some(e=>e.id===t.id)&&(t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`);let n=O.id?b.map(e=>e.id===O.id?{...t,enabled:e.enabled!==!1}:e):[...b,t];await F(n,O.id?`Rule updated`:`Rule created`)&&(k(null),h?.())},Ne=e=>F(b.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),Pe=e=>{confirm(`Delete rule "${e}"?`)&&F(b.filter(t=>t.id!==e),`Rule deleted`)},[Fe,Ie]=(0,E.useState)(null),Re=async t=>{Ie(t);try{let n=await Le(e,{ruleId:t,dryRun:!0,limit:i}),r=n.results.filter(e=>e.matched).length;if(!r){g({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 ${r} of the first ${n.processed} of ${n.total??n.processed} existing documents. Run its actions on all of them now?`))return;await qe(re,e,[t])}catch(e){g({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{Ie(null),se(e)}},I=(e,t)=>k(n=>n&&{...n,[e]:t}),ze=e=>{k(e.build({backend:wt(N)})),j(!1),requestAnimationFrame(()=>Ce.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},Be=e=>{let n=ht(e);n?(k(n),j(!1),requestAnimationFrame(()=>Ce.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[L,R]=(0,E.useState)(null),He=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,We=(e,t)=>{if(!L||!O||!e.length){R(null);return}if(L.target===`storeFolder`){let t=xe(e[0]);I(`actions`,O.actions.map((e,n)=>n===L.index?{...e,storeFolder:t?.rel||``,...t?.backend&&N.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(L.target===`condition`){let n=e.map(e=>He(e,t)),r=t.treeType===`context`&&O.actions.some(e=>e.kind===`store`);I(`conditions`,O.conditions.map((e,t)=>t===L.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>He(e,t));I(`actions`,O.actions.map((e,t)=>t===L.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}R(null)},z=(e,t,n=`Browse…`)=>(0,W.jsxs)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>R({target:e,index:t}),children:[(0,W.jsx)(ne,{className:`h-4 w-4 sm:mr-1.5`}),(0,W.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),B=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`)=>N.length?(0,W.jsxs)(`select`,{className:X,value:e,onChange:e=>t(e.target.value),children:[(0,W.jsx)(`option`,{value:``,children:n}),N.map(e=>(0,W.jsx)(`option`,{value:e.address,children:Ke(e)},e.address)),e&&!N.some(t=>t.address===e)&&(0,W.jsx)(`option`,{value:e,children:e})]}):(0,W.jsx)(C,{className:x(Z,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),Je=b.filter(xt),U=b.filter(e=>!xt(e)),Xe=({rule:e})=>{let t=e.enabled!==!1,i=ht(e)!==null,o=T[e.id],s=at(e.then?.[0]?.action||`link`),c=be(e);return(0,W.jsxs)(`div`,{className:x(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,W.jsx)(kt,{icon:s.icon,tone:s.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`}),!i&&(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,ke)}),(0,W.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,W.jsx)(_,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,W.jsx)(`span`,{children:bt(e)})]}),c.length>0&&(0,W.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:c.join(` | `),children:c.join(` | `)}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:o?(0,W.jsxs)(`button`,{type:`button`,className:x(`text-left underline-offset-2 hover:underline`,o.last.status===`error`&&`text-destructive`,!n&&`cursor-default hover:no-underline`),title:n?`Show this rule's run log`:o.last.error||o.last.skipReason||``,onClick:()=>n?.(e.id),children:[`ran `,o.count,`×`,o.errors?` (${o.errors} failed)`:``,` · last `,o.last.status,` `,Ct(o.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:pe,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>Ne(e.id),className:x(`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:x(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,W.jsxs)(S,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:e.when.eventPathExact===void 0?`Apply this rule to existing items (dry-run first)`:`Requires an original insert/link event. Current folder membership cannot reconstruct its destination.`,disabled:Fe!==null||e.when.eventPathExact!==void 0,onClick:()=>Re(e.id),children:[Fe===e.id?(0,W.jsx)(v,{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)(S,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:i?`Edit rule`:`Edit as JSON`,onClick:()=>Be(e),children:[i?(0,W.jsx)(a,{className:`h-4 w-4`}):(0,W.jsx)(r,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,W.jsx)(S,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>Pe(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?`}),A&&(0,W.jsxs)(S,{size:`sm`,variant:`ghost`,onClick:()=>j(!1),children:[(0,W.jsx)(s,{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:()=>ze(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:[!p&&(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)(S,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,W.jsx)(r,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,W.jsxs)(S,{onClick:()=>{k(null),j(!0)},disabled:A,children:[(0,W.jsx)(u,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),A&&!O&&Ze,O&&(0,W.jsxs)(`div`,{ref:Ce,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)(S,{variant:`ghost`,size:`sm`,onClick:()=>k(null),children:[(0,W.jsx)(s,{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)(C,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:O.description,onChange:e=>I(`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=>I(`schema`,e.target.value),children:[ke.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value)),O.schema&&!ke.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&&I(`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=>I(`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)(C,{className:x(Z,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>I(`conditions`,O.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&z(`condition`,t,`Browse the workspace trees`)]}),(0,W.jsx)(S,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>I(`conditions`,O.conditions.filter((e,n)=>n!==t)),children:(0,W.jsx)(s,{className:`h-4 w-4`})})]},t)})}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,W.jsxs)(S,{size:`sm`,variant:`outline`,onClick:()=>I(`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=>I(`actions`,O.actions.map((t,r)=>r===n?{...t,...e}:t)),i=N.find(e=>e.address===t.a),a=i?.capabilities?.paths===!0,o=B&&a,c=at(t.kind),l=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)(fe,{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)(C,{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)(C,{className:x(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)(fe,{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`})]}),u=Y(O.conditions),d=t.kind===`store`&&t.a&&(!t.recursive||o)?pt(t,O.conditions,i):null,f=t.kind===`extractAttachments`&&t.a?Ge(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:c.icon,tone:c.tone}),(0,W.jsx)(`select`,{className:x(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)(S,{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:()=>I(`actions`,O.actions.filter((e,t)=>t!==n)),children:(0,W.jsx)(s,{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)(C,{className:x(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})}),z(`action`,n)]})}),t.kind===`link`&&(0,W.jsx)(Q,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(C,{className:x(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)(C,{className:x(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)(C,{className:x(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)(C,{className:x(Z,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),z(`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)(C,{className:x(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:u===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:a?B?u===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:${u} trigger this rule. Its full path is appended beneath the destination root; descendant inserts do not match.`:`Choose a source folder. Context paths use the destination of the insertion or link event.`:`Choose a destination that reports support for folder paths. Content-addressed blob stores cannot recreate sub-folder paths.`,disabled:!o&&!t.recursive}),d&&(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:[d.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:[d.recreated||`(root)`,`/`]})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:d.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)(ee,{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`})]})})]})]}),t.storeMode===`copy`&&(0,W.jsx)($,{checked:t.deleteSource,onChange:e=>r({deleteSource:e}),label:`Delete source link from Canvas`,hint:`For links without stored bytes, download the target and remove the link only after success. Files are copied normally.`}),(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)(C,{className:x(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)(C,{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)(C,{className:x(Z,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),z(`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)(C,{className:x(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`})]})})]}),!a&&(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.`}),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:[`Example email dated `,f.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:[f.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:f.added?`${f.added}/`:`(none)`})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:f.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)(C,{type:`number`,min:1,max:5,className:x(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)(C,{className:x(Z,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),z(`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)(C,{className:x(Z,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),z(`action`,n)]})}),(0,W.jsx)(Q,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(C,{className:x(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.jsx)($,{checked:t.deleteSource,onChange:e=>r({deleteSource:e}),label:`Delete source link from Canvas`,hint:`Remove the source item only after the download is saved successfully. Kept links are related to their downloads.`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The download becomes a file item at the filing destination. Repeated events reuse the saved download. 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)(C,{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)(C,{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=_e.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&&!_e.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)`]}),_e.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}`))]})}),ye&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:ye}),(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)(C,{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)(C,{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)(C,{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)(C,{className:x(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})})}),l(`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:me.length?(0,W.jsxs)(`select`,{className:x(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…`}),me.map(e=>(0,W.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,W.jsx)(C,{className:x(Z,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),l(`output`)]})]},n)}),(0,W.jsxs)(S,{size:`sm`,variant:`outline`,onClick:()=>I(`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=>I(`approval`,e),label:`Ask me before running`,hint:`Actions are held in the Pending queue for review — approve (optionally amended) or decline — instead of running automatically.`}),(0,W.jsx)($,{checked:O.cascade,onChange:e=>I(`cascade`,e),label:`Also react to items created by automation`,hint:`Off by default so rules, hooks and agents cannot trigger each other in a loop. A server-side depth limit still stops runaway chains.`})]})]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,W.jsxs)(S,{className:`h-10 px-5`,onClick:Me,disabled:pe||ce,children:[pe?(0,W.jsx)(v,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,W.jsx)(o,{className:`mr-1.5 h-4 w-4`}),` `,O.id?`Save changes`:`Create rule`]}),(0,W.jsx)(S,{className:`h-10`,variant:`outline`,onClick:()=>{k(null),te?.()},children:`Cancel`})]})]}),L&&(0,W.jsx)(de,{onClose:()=>R(null),children:(0,W.jsx)(ae,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:L.target!==`storeFolder`&&!(L.target===`condition`&&O?.actions.some(e=>e.kind===`store`)),tabs:L.target===`condition`?[`context`,`directory`,`backends`]:L.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:L.target===`condition`?`Choose source folder…`:L.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:L.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:We,onClose:()=>R(null)})}),!p&&(ce?(0,W.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):b.length===0?!A&&!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)(m,{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)(y,{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))})]})]}))]})}var jt=new Map;function Mt(e,t,n,r,i,a){let o=JSON.stringify([t,n,r,a]),s=jt.get(o);if(s)return s;let c=(async()=>{let o=e({title:`Resyncing…`,description:r});try{for(a?await se(t,n,r,a):await ce(t,n,r);;){let e=await oe(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 jt.set(o,c),c.finally(()=>{jt.get(o)===c&&jt.delete(o)}).catch(()=>{}),c}export{R as A,ve as C,O as D,he as E,_e as F,xe as I,Oe as L,L as M,A as N,Ee as O,Fe as P,Ae as S,N as T,Pe as _,Ye as a,Ve as b,qe as c,Le as d,Ne as f,He as g,j as h,Xe as i,Se as j,je as k,F as l,Ce as m,At as n,Ze as o,De as p,Qe as r,Je as s,Mt as t,We as u,ke as v,Ie as w,we as x,k as y};
@@ -1,3 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/subtree-transfer-dialog-DQM5zfx2.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BOIngd5F.js","assets/react-BHzhHVTZ.js","assets/ui-CDoK3F3U.js","assets/button-SeUZ_Pvi.js","assets/utils-BxVxyehK.js","assets/utils-2pl1SbIp.js","assets/input-BOtCd4HP.js","assets/api-CA6WiiYM.js","assets/alert-dialog-CFeuDt0T.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,Ar as l,Bn as u,Br as d,Bt as f,Cr as p,Ct as m,Hr as h,It as g,Jr as _,Jt as v,Kn as y,Kr as b,L as x,Lt as S,Pt as C,Qn as w,Qt as ee,Rt as T,Tr as te,Tt as ne,Un as re,Vr as E,Vt as D,W as ie,Wt as ae,X as oe,_n as se,_r as O,an as ce,ar as le,ci as k,cn as ue,cr as de,fi as fe,fr as pe,gr as me,hi as he,lr as ge,mr as _e,ot as ve,pn as ye,rt as be,st as xe,tt as A,vn as Se,vr as Ce,xn as we,xt as Te,yn as Ee,yt as De,zn as j,zr as Oe}from"./ui-CDoK3F3U.js";import{t as M}from"./utils-2pl1SbIp.js";import{t as N}from"./button-SeUZ_Pvi.js";import{c as ke,t as Ae}from"./api-CA6WiiYM.js";import{t as je}from"./socket-CtH3EU9m.js";import{n as Me}from"./use-toast-BlLDqSUO.js";import{c as Ne,d as Pe,f as Fe,h as P,l as Ie,p as Le,t as Re,u as ze}from"./LinkToCard-CKVi4Nrg.js";import{Bn as Be,Dn as F,It as Ve,Kt as I,Lt as He,Mt as Ue,N as We,Nt as Ge,O as Ke,On as qe,Ot as Je,Pt as Ye,Rt as Xe,Sn as Ze,Tt as Qe,Vt as $e,Z as et,_n as tt,a as nt,an as L,bn as rt,c as it,cn as at,dn as ot,et as st,fn as ct,g as lt,hn as ut,kn as dt,lt as R,m as z,mt as B,nt as ft,o as pt,on as mt,p as ht,pt as gt,qt as _t,r as vt,un as yt,vt as bt,wn as xt,xn as V}from"./workspace-C5V-ZCOE.js";import{a as St,b as Ct,c as wt,f as Tt,l as Et,o as Dt,s as Ot,t as kt,v as At}from"./ObjectPropertiesCard-D2lrTQqT.js";import{i as jt,n as Mt,s as Nt}from"./document-open-mode-DoImW-xs.js";import{t as Pt}from"./use-mobile-Db-vWu9Y.js";import{c as Ft,s as It}from"./IdentityFields-D-NCTUaE.js";import{i as Lt}from"./public-share-CXR25Q1X.js";import{o as Rt,s as zt}from"./text-documents-Cdb3U63i.js";import{t as Bt}from"./useDocumentThumbnail-Cj4UYyhC.js";import{t as Vt}from"./markdown-view-BBBZtNSR.js";import{n as Ht}from"./tags-YamdPoBK.js";import{r as Ut}from"./use-toolbox-Ck_cLGgf.js";import{C as Wt,S as Gt,T as Kt,g as qt,h as Jt,m as Yt,t as Xt,u as Zt,y as Qt}from"./context-t3rdtGUB.js";import{n as $t}from"./relation-events-CKio19hE.js";import{n as en,t as tn}from"./PickDocumentsCard-BWgc-A02.js";import{t as nn}from"./useEscapeClose-DR_xKT_k.js";import{t as rn}from"./useToastHelpers-CRrpIIdY.js";import{u as an}from"./layer-style-Byl5LNFR.js";import{t as H}from"./DocumentIcon-9i1uCMQa.js";import{n as on,t as sn}from"./LinkToSidePanel-eCy3nW4R.js";import{I as cn,j as ln,m as un,n as dn,t as fn,x as pn}from"./backend-sync-progress-Dp12uN4y.js";import{t as mn}from"./workspace-access-C9nZlBBZ.js";import{t as hn}from"./search-COMZIxA7.js";import{a as U,c as gn,i as _n,n as vn,o as yn,r as bn,s as xn,t as Sn}from"./use-sortable-data-BBKmqs79.js";import{n as Cn}from"./workspace-BydSRtST.js";var W=e(r(),1),wn=(0,W.createContext)(null),Tn=()=>(0,W.useContext)(wn),En=`canvas:readerWidth`,G=320,K=1600;function Dn(){try{let e=Number(sessionStorage.getItem(En));return Number.isFinite(e)&&e>=G&&e<=K?e:null}catch{return null}}var On=Dn(),kn=new Set;function An(e){return kn.add(e),()=>{kn.delete(e)}}function q(e){On=e===null?null:Math.round(Math.max(G,Math.min(K,e)));try{On===null?sessionStorage.removeItem(En):sessionStorage.setItem(En,String(On))}catch{}kn.forEach(e=>e())}function jn(){return(0,W.useSyncExternalStore)(An,()=>On,()=>null)}function Mn(e,t){let[n,r]=(0,W.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,W.useState)(a);a!==o&&(s(a),r(null));let c=(0,W.useRef)(a),l=(0,W.useRef)(0);(0,W.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,W.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}st(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`?se:e.schema===`data/schema/file`?le:e.schema===`data/schema/message/email`?ue:ge}function Pn({entry:e,onClose:t,frame:n}={}){let r=Dt(),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)(x,{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)(en,{title:F(o).title,icon:Nn(o),onClose:a,onSave:async e=>(await He(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:Tt(o)===At,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)(kt,{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,W.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&&q(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:()=>q(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`?q(null):q(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function Rn(e){let t=Tn(),n=jt(),r=Pt(),i=Dt();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,W.useState)(a),l=`canvas:readerSelection:${t}`,[u,d]=(0,W.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,W.useCallback)((t,n)=>{if(n===e){c(!0),d(t.id);try{sessionStorage.setItem(l,String(t.id))}catch{}}},[e,l]),m=(0,W.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)(St.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,W.useState)(Hn);return(0,W.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 nn(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,W.useState)(null),[a,o]=(0,W.useState)(``),[s,c]=(0,W.useState)(``);nn(n),(0,W.useEffect)(()=>{let n=!1;return(async()=>{let r=await et(e);if(!mn(r))throw Error(`Only workspace administrators can create rules.`);let a=await st(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,W.useMemo)(()=>r?Gn(r):[],[r]),u=l.find(e=>e.id===s)||l[0],d=(0,W.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:F(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)(x,{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)(dn,{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,W.useRef)(null),o=(0,W.useRef)({selected:t,onSelectionChange:n});return(0,W.useLayoutEffect)(()=>{o.current={selected:t,onSelectionChange:n}},[t,n]),(0,W.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}=Me();nn(n,r);let[a]=(0,W.useState)(()=>{try{return tr(e)}catch{return``}}),[o,s]=(0,W.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,W.useState)(!1),[u,d]=(0,W.useState)(``),f=(0,W.useRef)(!1),p=(0,W.useRef)(!1);(0,W.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 ht(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`:sn,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)(N,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(a)}catch{}s(null),d(``)},children:`Discard remaining`}),!_&&!c&&(0,J.jsx)(N,{onClick:()=>void h(o),children:`Resume copy`}),(0,J.jsx)(N,{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)(on,{onClose:g,children:y})}function rr(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...Ht(e.data?.tags??[]),...Ht(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,W.useState)([]),[a,o]=(0,W.useState)(null),[s,c]=(0,W.useState)(`keep`),[l,u]=(0,W.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,W.useState)(t),[m,h]=(0,W.useState)(!1),[g,_]=(0,W.useState)(``);return nn(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)(It,{tags:r,onChange:i,suggestions:[]})]}),(0,J.jsx)(Ot,{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)(N,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,J.jsx)(N,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await st(e,n);await ut(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=Mt(),n=(0,W.useContext)(St),{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,W.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,W.useState)(!1),c=Ut(),{document:l,refresh:u}=Mn(r,e);if(nn(()=>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:M(`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:M(`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:F(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=qe(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)(ee,{className:`h-4 w-4`}):(0,J.jsx)(ce,{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)(Ft.Provider,{value:()=>s(e=>!e),children:(0,J.jsx)(kt,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var fr=Cn,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,W.useState)([]);return(0,W.useEffect)(()=>{let t=!1;return Je(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,W.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)(k,{className:`h-3.5 w-3.5`}):(0,J.jsx)(he,{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(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 Er(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function Dr(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 Or=(e,t)=>`${ke.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function kr(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await Ae.get(`${Or(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 Ar(e,t,n){return Mr(e,t,n,`restore`)}function jr(e,t,n){return Mr(e,t,n,`discard`)}async function Mr(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await Ae.post(`${Or(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{B(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 Nr(e,t){let n=Tr(`backends`,t);if(!n?.backend)return;let{items:r}=await kr(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 Ar(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 Pr(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
3
- `)+(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 Fr(e,t){let n=Tr(`backends`,t);if(!n?.backend)return;let{items:r}=await kr(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Pr(n.backend,i))return;let a=await jr(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} deleted; ${o.length} remain in Trash. ${o[0].message||o[0].reason||`Please retry.`}`)}function Ir(){let{showProgress:e}=Me();return(0,W.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 Lr=[`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`],Rr=new Map;function zr(e,t,n){B(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 Br(e,t){let n=Rr.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=Lr.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)B(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return je.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)B(e,t);a.forEach(([e,t])=>je.off(e,t))}},Rr.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),Rr.delete(e))}}function Vr({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=Ir(),{showProgress:a}=Me(),s=n||`context`,c=s===`directory`,[l,u]=(0,W.useState)([]);(0,W.useEffect)(()=>{let e=!1,n=()=>{t&&pn(t).then(t=>{e||u(t)}).catch(()=>{})};return n(),window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[t,s]);let d=(0,W.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,W.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),p=(0,W.useCallback)(async(n,r=!0)=>{let i;if(e)i=await Zt(e,n,r);else if(t)i=await gt(t,n,r,s);else return!1;let a=an(n);if(i&&a)try{e?await Kt(e,n,a):t&&await tt(t,n,a,s)}catch{}return f(),i},[e,t,s,f]),m=(0,W.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 Qt(e,n,r):t?await I(t,n,r,s,a,o):!1}finally{f()}}),[e,t,s,f,i]),h=(0,W.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await qt(e,n,t.join(`/`),!1)}else if(t)i=await tt(t,n,{name:r},s);else return!1;return f(),i},[e,t,s,f]),g=(0,W.useCallback)(async(n,r,a=!1,o=s,c=s,l={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await qt(e,n,r,a,l);else if(t)i=await Ve(t,n,r,a,o,c,l);else return!1;return f(),i}),[e,t,s,f,i]),_=(0,W.useCallback)(async n=>{let r;if(e)r=await Jt(e,n);else if(t)r=await Ge(t,n,s);else return null;return f(),r},[e,t,s,f]),v=(0,W.useCallback)(async n=>{let r;if(e)r=await Wt(e,n);else if(t)r=await L(t,n,s);else return null;return f(),r},[e,t,s,f]),y=(0,W.useCallback)(async(n,r,a=!1,o=s,c=s)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await Xt(e,n,r,a);else if(t)i=await z(t,n,r,a,o,c);else return!1;return f(),i}),[e,t,s,f,i]),b=(0,W.useCallback)(async(n,r)=>e?await Kt(e,n,r):t?await tt(t,n,r,s):!1,[e,t,s]),x=(0,W.useCallback)(async(n,r)=>{let i;if(e)i=await Yt(e,n,r);else if(t)i=await Ye(t,n,r,s);else return null;return f(),i},[e,t,s,f]),S=(0,W.useCallback)(async(n,r)=>{let i;if(e)i=await Gt(e,n,r);else if(t)i=await mt(t,n,r,s);else return null;return f(),i},[e,t,s,f]),C=(0,W.useCallback)(async e=>{if(!t)return!1;let n=await Ue(t,e,t,s);return f(300),n},[t,s,f]),w=(0,W.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]),ee=(0,W.useCallback)(async e=>{if(!t)return!1;let n=await Ke(t,e,s);return f(),n},[t,s,f]),T=(0,W.useCallback)(async e=>{if(!t)return!1;let n=await bt(t).catch(()=>[]),r=d(e);for(let e of r){let r=nt(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 fn(a,t,r.driver,r.address,void 0,o?.name)}return f(300),r.length>0},[t,f,a,d]),te=(0,W.useCallback)(async e=>{if(!t)return;let n=d(e);if(!n.length)return;let r=await bt(t);for(let e of n){let n=nt(e,r);if(n?.driver!==`imap`)continue;let i=r.find(e=>e.driver===`imap`&&e.address===n.address)?.containers?.find(t=>t.treePath===e);i&&await at(t,`imap`,n.address,i.name)}},[t,d]),ne=(0,W.useCallback)(async(e,n)=>{if(!t)return!1;let r=await bt(t).catch(()=>[]),i=pt(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await vt(t,i.driver,i.address,[a]),f(200),!0},[t,f]),re=(0,W.useCallback)(async(e,n)=>{if(!t)return!1;let r=await bt(t).catch(()=>[]),i=pt(e,r);return!i||!i.key?!1:(await _t(t,i.driver,i.address,i.key,n),f(200),!0)},[t,f]),E=(0,W.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await bt(t),r=it(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await $e(t,r.driver,r.address,r.key),!0}finally{f(200)}}):!1,[t,f,i]),D=(0,W.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await o(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-DQM5zfx2.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:()=>{zr(t,s),f()}})},[t,s,f]),ie=(0,W.useCallback)(async(e,n)=>{if(!t)return;let r=await o(()=>Promise.resolve().then(()=>Ur),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await R(t,n,e,s,rt(s))).length!==e.length)throw Error(`Some documents could not be imported`);return zr(t,s),f(),!0});else{let e=[];for(let r=0;;){let i=await ft(t,n,[],{treeName:s,treeType:rt(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=>ie(`import`,e):void 0,onExportDocuments:t?e=>ie(`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?w:void 0,onDestroyLayer:t&&!c?ee:void 0,canResyncBackend:e=>d(e).length>0,onResyncBackend:t?T:void 0,onCheckMailboxes:t?te:void 0,onCreateBackendFolder:t?ne:void 0,onRenameBackendFolder:t?re:void 0,onDeleteBackendFolder:t?E:void 0}}function Hr({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:c,pastedDocumentIds:d,onPasteDocuments:f}){let p=s(),m=Vr({workspaceId:n,treeName:r}),h=r===`backends`,g=h?pt(i):null,[_,v]=(0,W.useState)([]);(0,W.useEffect)(()=>{if(!h)return;let e=!1;return bt(n).then(t=>{e||v(t)}).catch(()=>{}),()=>{e=!0}},[n,h]);let y=h?it(i,_):null,b=i.split(`/`).filter(Boolean).pop()||i,[x,ee]=(0,W.useState)(void 0);(0,W.useEffect)(()=>{let e=!1;return Qe(n).then(t=>{e||ee(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||ee(null)}),()=>{e=!0}},[n,r,i]);let re=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},E=(e,t,n,r=!1)=>(0,J.jsxs)(`button`,{type:`button`,className:M(`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:()=>re(n),children:[e,t]}),ie=(0,J.jsx)(`div`,{className:`my-1 h-px bg-border`}),ae=e=>{let t=h?(()=>{let t=cn(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:un(i)};p(`/workspaces/${n}/settings/hooks?${ln(t).toString()}`)},se=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},O=Tr(r,i);return O?(0,J.jsxs)(P,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[E((0,J.jsx)(oe,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),O.backend&&E((0,J.jsx)(ne,{className:`h-3 w-3`}),`Restore original paths`,()=>Nr(n,i)),O.backend&&E((0,J.jsx)(oe,{className:`h-3 w-3`}),`Empty Trash`,()=>Fr(n,i),!0)]}):(0,J.jsxs)(P,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[E((0,J.jsx)(w,{className:`w-3 h-3`}),`Open`,()=>o(i)),c&&E((0,J.jsx)(pe,{className:`w-3 h-3`}),`Open to the side`,()=>c(i)),ie,h?g&&(0,J.jsxs)(J.Fragment,{children:[E((0,J.jsx)(C,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=se(`New folder name:`);e&&await m.onCreateBackendFolder?.(i,e)}),g.key&&E((0,J.jsx)(D,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=se(`New folder name:`,b);e&&await m.onRenameBackendFolder?.(i,e)}),E((0,J.jsx)(u,{className:`w-3 h-3`}),`Create storage rule…`,()=>ae(`store`))]}):(0,J.jsxs)(J.Fragment,{children:[E((0,J.jsx)(C,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=se(`New folder name:`);e&&await m.onInsertPath(`${i===`/`?``:i}/${e}`)}),E((0,J.jsx)(D,{className:`w-3 h-3`}),`Rename`,async()=>{let e=se(`New name:`,b);e&&await m.onRenamePath(i,e)}),E((0,J.jsx)(u,{className:`w-3 h-3`}),`Create rule…`,()=>ae(`store`)),E((0,J.jsx)(Ce,{className:`w-3 h-3`}),`Create download rule…`,()=>ae(`download`))]}),x!==void 0&&E(x?(0,J.jsx)(T,{className:`w-3 h-3`}):(0,J.jsx)(S,{className:`w-3 h-3`}),x?`Unpin`:`Pin`,async()=>{x?await ct(n,x.id):await Xe(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),ie,m.onImportDocuments&&E((0,J.jsx)(C,{className:`w-3 h-3`}),`Import documents…`,()=>m.onImportDocuments(i)),m.onExportDocuments&&E((0,J.jsx)(Ce,{className:`w-3 h-3`}),`Export documents…`,()=>m.onExportDocuments(i)),E((0,J.jsx)(te,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!h&&f&&d&&d.length>0&&E((0,J.jsx)(l,{className:`w-3 h-3`}),`Paste ${d.length} document(s)`,()=>f(i,d)),h?y&&(0,J.jsxs)(J.Fragment,{children:[ie,E((0,J.jsx)(oe,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${b}" and its contents from the backend?`)&&await m.onDeleteBackendFolder?.(i)},!0)]}):(0,J.jsxs)(J.Fragment,{children:[ie,E((0,J.jsx)(oe,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await m.onRemovePath(i,!0)},!0)]})]})}var Ur=t({DocumentList:()=>hi,default:()=>hi,showDocumentExport:()=>_i,showDocumentImport:()=>gi});function Wr({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,W.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)(N,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,J.jsx)(te,{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)(N,{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)(N,{onClick:o,children:`Close`})]})]})})}function Gr({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,W.useState)(``),[a,o]=(0,W.useState)(!1),[s,c]=(0,W.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)(N,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,J.jsx)(N,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function Kr({document:e}){let{replicating:t,label:n}=V(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)(ye,{className:`h-3 w-3 animate-spin`}),n]}):null}function qr(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Ie(e.currentTarget,`inside`)}function Jr({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)(O,{className:`h-4 w-4`})}):null}function Yr(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function Xr({document:e}){let t=qe(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 Zr({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Dt(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=Un(),[u,d]=(0,W.useState)(!1),{replicating:f}=V(e),p=F(e),m=$r(e),h=m||ti(e),{blobUrl:g}=Bt(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)(gn,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>Yr(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)(U,{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)(U,{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)(H,{document:e,chip:!0})}),(0,J.jsx)(U,{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)(Xr,{document:e}),(0,J.jsx)(Kr,{document:e})]}),p.subtitle&&(0,J.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,J.jsx)(U,{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)(U,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,J.jsx)(U,{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)(U,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,J.jsx)(U,{className:`w-12 text-right`,children:(0,J.jsx)(Jr,{documentId:e.id,onOpenActions:a})})]}),(0,J.jsx)(ur,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function Qr({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Dt(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=Un(),[u,d]=(0,W.useState)(!1),f=e.schema===`data/schema/tab`,{replicating:p}=V(e),m=F(e),h=$r(e),_=ei(e),v=h||ti(e)||_,{blobUrl:y,loading:x}=Bt(n??``,e.id,512,{enabled:v,blobFallback:h,version:e.checksumArray?.[0]??null}),S=t=>{o?.(t,e.id)},C=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),w=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),ee=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)},T=e=>{e.shiftKey&&e.preventDefault()},te=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=>Yr(n,()=>d(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:border-primary border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${p?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${f&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:ee,onMouseDown:T,...l,onContextMenu:te,draggable:!0,onDragStart:S,children:(0,J.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[v&&(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:[y?(0,J.jsx)(`img`,{src:y,alt:m.title,loading:`lazy`,className:`h-full w-full object-cover`}):_&&n&&!x?(0,J.jsx)(ni,{workspaceId:n,documentId:e.id,fallback:(0,J.jsx)(H,{document:e})}):x?(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)(H,{document:e})}),_&&(0,J.jsx)(g,{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)(H,{document:e,chip:!0}),(0,J.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:m.title,children:m.title}),(0,J.jsx)(Xr,{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:m.schemaLabel}),(0,J.jsx)(Kr,{document:e})]}),m.subtitle&&(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:m.subtitle,children:m.subtitle}),m.preview&&(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:m.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})]}),w&&(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(j,{className:`h-3 w-3`}),(0,J.jsx)(`span`,{className:`font-mono`,title:`${w.algo} checksum`,children:w.hash})]}),(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(b,{className:`h-3 w-3`}),(0,J.jsx)(`span`,{title:`Created: ${C(e.createdAt)}`,children:C(e.createdAt)})]})]})]}),(0,J.jsx)(Jr,{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 $r(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function ei(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function ti(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function ni({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=zt(e,t),[a,o]=(0,W.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)(g,{className:`h-3.5 w-3.5`})})]}):(0,J.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function ri({document:e,workspaceId:t,markdown:n}){let r=(0,W.useRef)(null),[i,a]=(0,W.useState)(()=>typeof IntersectionObserver>`u`);(0,W.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}=Rt(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)(Vt,{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)(H,{document:e,size:10,chip:!0}),i&&s&&(0,J.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function ii({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let[c,l]=(0,W.useState)(null),u=e.metadata?.dimensions,d=c??(u?.width&&u?.height?Math.max(.2,Math.min(5,u.width/u.height)):1),f=Dt(),p=f.alwaysOn&&f.entry?.workspaceId===n&&f.entry?.document.id===e.id,m=Un(),[h,_]=(0,W.useState)(!1),v=$r(e),y=ei(e),b=v||ti(e)||y,x=F(e),S=Be(String(e.metadata?.contentType||``),e.metadata?.filename||dt(e)),C=e.schema===`data/schema/file`&&(S===`markdown`||S===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,w=!b&&e.schema!==`data/schema/file`&&!!(x.preview||x.subtitle),{replicating:ee}=V(e),{blobUrl:T,loading:te}=Bt(n??``,e.id,768,{enabled:b,blobFallback:v,version:e.checksumArray?.[0]??null}),ne=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)},re=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":p||void 0,"aria-selected":!!t,onKeyDown:n=>Yr(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 ${ee?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:ne,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...m,onContextMenu:re,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&&T||w||C&&n||y&&n?``:`aspect-square`}`,children:[b&&te&&(0,J.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),b&&T?(0,J.jsx)(`img`,{src:T,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&&!te?(0,J.jsx)(ni,{workspaceId:n,documentId:e.id,fallback:(0,J.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,J.jsx)(H,{document:e,size:10,chip:!0})})}):C&&n?(0,J.jsx)(ri,{document:e,workspaceId:n,markdown:S===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):w?(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)(H,{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)(Xr,{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)(H,{document:e,size:10,chip:!0})}),y&&T&&(0,J.jsx)(g,{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)(ae,{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)(O,{className:`h-3.5 w-3.5`})})]})]}),!w&&(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)(Xr,{document:e})]})]}),(0,J.jsx)(ur,{document:e,isOpen:h,onClose:()=>_(!1),workspaceId:n})]})}function ai(e,t,n,r,i){let[a,o]=(0,W.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 oi(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function si({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,J.jsx)(p,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,J.jsx)(y,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var ci=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function li({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=ai(e,r,i,a,o);return(0,J.jsxs)(`button`,{type:`button`,title:ci(e),onClick:()=>t?.(e.path),onContextMenu:t=>oi(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)(si,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,J.jsx)(p,{className:`hidden h-4 w-4 group-hover:block`}):(0,J.jsx)(w,{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 ui({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=ai(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,J.jsxs)(`button`,{type:`button`,title:ci(e),onClick:()=>t?.(e.path),onContextMenu:t=>oi(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)(p,{className:`h-10 w-10`,strokeWidth:1.5}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(y,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,J.jsx)(w,{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 di({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)(ui,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function fi({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)(li,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function pi({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=ai(e,r,i,a,o);return(0,J.jsxs)(gn,{"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=>oi(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:ci(e),children:[(0,J.jsx)(U,{className:`w-10`}),(0,J.jsx)(U,{className:`w-12`,children:(0,J.jsx)(si,{folder:e})}),(0,J.jsx)(U,{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)(U,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,J.jsx)(U,{className:`hidden lg:table-cell`}),(0,J.jsx)(U,{className:`hidden lg:table-cell`}),(0,J.jsx)(U,{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)(U,{className:`w-12 md:w-auto`})]})}function mi({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)(E,{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 hi({readingPane:e=!1,externalSearchQuery:t,toolbarActions:n,documents:r,isLoading:i,contextPath:a,treeName:o,workspaceId:s,totalCount:p,onRemoveDocument:g,onDeleteDocument:y,onDestroyDocument:b,onRemoveDocuments:S,onDeleteDocuments:w,onDestroyDocuments:ee,onCopyDocuments:T,onCutDocuments:ne,onPasteDocuments:D,onImportDocuments:O,onSelectionChange:ce,pastedDocumentIds:k,viewMode:ue=`card`,allowViewToggle:he=!1,activeContextUrl:ge,currentContextUrl:ye,currentPage:A=1,pageSize:j=50,onPageChange:M,onPageSizeChange:ke,onPurgeDocuments:Ae,disablePurgeDocuments:je=!1,backendSearchQueries:P=[],onBackendSearch:Be,onRemoveBackendQuery:Ve,serverSort:I,onServerSortChange:He,scope:Ue=`path`,onScopeChange:Ge,canSaveChanges:Ke=!1,isSavingChanges:qe=!1,onSaveChanges:Je,linkTree:Ye,folders:Xe,onOpenFolder:Qe}){let $e=Tn(),et=Nt(),[tt,nt]=(0,W.useState)(()=>{if(!he)return ue;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return ue}),L=he?$e?.documentLayout??tt:ue,rt=(0,W.useCallback)(e=>{$e?.selectDocumentLayout(e),nt(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[$e]),[it,at]=(0,W.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),ot=(0,W.useCallback)(()=>{at(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[st,ct]=(0,W.useState)(new Set),ut=(0,W.useCallback)(e=>{ct(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[R,z]=(0,W.useState)(new Set),[B,ft]=(0,W.useState)(null),[pt,mt]=(0,W.useState)(null),ht=Ut(),gt=!!(ht&&s),_t=(0,W.useCallback)((e,t=!1)=>{if(!ht||!s)return;let n=e.map(e=>r.find(t=>t.id===e)).filter(e=>!!e);n.length!==0&&ht.openAddRelated({workspaceName:s,documents:n},t)},[ht,s,r]),[vt,bt]=(0,W.useState)(!1),[V,St]=(0,W.useState)(null),[Tt,Ot]=(0,W.useState)(!1),[kt,At]=(0,W.useState)(null),[jt,Mt]=(0,W.useState)(!1),Pt=(0,W.useRef)(!1),Ft=(0,W.useRef)(!1),It=o===`backends`&&Ue===`path`?cn(a):null;(0,W.useEffect)(()=>()=>{Pt.current=!0},[]);let[Rt,zt]=(0,W.useState)(!1),[Bt,Vt]=(0,W.useState)(null),[Ht,Wt]=(0,W.useState)(!1),[Gt,Kt]=(0,W.useState)(null),qt=Lt()==null&&!!s,[Jt,Yt]=(0,W.useState)(null),[Xt,Zt]=(0,W.useState)(null),Qt=!!(Ye&&D),en=!!s,{showSuccessToast:nn,showErrorToast:an}=rn(),{showProgress:on}=Me(),sn=Dt(),ln=s?e=>sn.open(e,s):void 0,un=Ue===`workspace`,dn=un?void 0:g,fn=un?void 0:S,[pn,mn]=(0,W.useState)(!1),[U,Cn]=(0,W.useState)(!1),[wn,En]=(0,W.useState)(``),G=t??wn,K=t!==void 0,[Dn,On]=(0,W.useState)(!1),kn=P.length>0,An=(0,W.useRef)(null),q=(0,W.useCallback)(()=>{En(``),An.current&&(An.current.value=``)},[]);(0,W.useEffect)(()=>{if(!he||window.matchMedia(`(max-width: 767px)`).matches)return;let e=An.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[he]);let jn=JSON.stringify([s,o,a]),[Mn,Nn]=(0,W.useState)(jn);jn!==Mn&&(Nn(jn),z(new Set),St(null),mt(null),ft(null)),(0,W.useEffect)(()=>{ce?.(Array.from(R))},[R,ce]);let Pn=(0,W.useCallback)(()=>{if(!Be)return;let e=G.trim();e&&(Be(e),q())},[Be,G,q]),Fn=(0,W.useCallback)(()=>{q(),Ve&&P.length>0&&Ve(-1)},[Ve,P.length,q]),In=(0,W.useCallback)((e,t)=>{let n;R.has(t)&&R.size>1?n=Array.from(R):(n=[t],z(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:Ue===`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)},[R,a,o,s,Ue]),Ln=(0,W.useCallback)(async e=>{if(!D)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(),On(!1),!sr(n,s,o,a)&&(await D(a,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),z(new Set)))},[a,o,s,D]),zn=(0,W.useCallback)(e=>{D&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,On(!0))},[D]),Hn=(0,W.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||On(!1)},[]),Un=(0,W.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,W.useMemo)(()=>r.length===0?null:new hn(r,Un),[r,Un]),X=(0,W.useDeferredValue)(G),Z=(0,W.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,W.useMemo)(()=>{if(!Xe||Xe.length===0||X.trim())return[];let e=I?.order===`desc`?-1:1;return[...Xe].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)},[Xe,X,I?.order]),Yn=Gn.length>0,[Xn,Zn]=(0,W.useState)(null),Qn=(0,W.useMemo)(()=>s&&o&&Qe?(e,t)=>Zn({x:t.clientX,y:t.clientY,path:e}):void 0,[s,o,Qe]),$n={folders:Gn,onOpen:Qe,onMenu:Qn,onPasteDocuments:D,contextPath:a,treeName:o,workspaceId:s},tr=(0,W.useMemo)(()=>({title:e=>F(e).title?.toLowerCase()??``,schema:e=>F(e).schemaLabel??``,type:Ze,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[]),{sorted:rr,sort:ir,toggleSort:or}=Sn(Z,tr),cr=(0,W.useCallback)(e=>_r(e,I?.sortBy),[I?.sortBy]),lr=(0,W.useMemo)(()=>wr(Z,cr,I?.order===`asc`?`asc`:`desc`),[Z,cr,I?.order]),dr=it&&!xt(I?.sortBy)&&lr.length>1,fr=(0,W.useCallback)((e,t)=>{z(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),pr=(0,W.useMemo)(()=>(L===`table`?rr:dr?lr.filter(e=>!st.has(e.key)).flatMap(e=>e.items):Z).map(e=>e.id),[L,rr,dr,lr,st,Z]),mr=(0,W.useRef)(null),hr=JSON.stringify([s,a,o,A]),Q=(0,W.useCallback)(e=>{mr.current=null,z(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),$=(0,W.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}),z(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,W.useCallback)((e,t)=>{let n;R.has(e)?n=Array.from(R):(n=[e],z(new Set([e]))),ft({anchor:t,ids:n})},[R]),yr=(0,W.useCallback)((e,t)=>{vr(t,Ie(e))},[vr]),br=(0,W.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),vr(t,qr(e)))},[vr]),xr=(0,W.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){bt(!0);try{for(let n of t)await lt(s,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;nn(`Created ${n} relation${n===1?``:`s`}`),$t(),mt(null)}catch(e){an(e instanceof Error?e.message:`Failed to create relations`)}finally{bt(!1)}}},[s,nn,an]),Sr=(0,W.useCallback)(async(e,t,n)=>{if(D){for(let r of e)await D(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});z(new Set)}},[D]),Cr=(0,W.useCallback)(async(e,t,n)=>{if(!s||!V||Ft.current)return;Ft.current=!0,Pt.current=!1,Mt(!1),Ot(!0);let i=on({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${V.ids.length} document(s) · ${e.join(`, `)}`});try{let a=r=>yt(s,r,{to:e,mode:t,keepDocument:n.keepDocument,...t===`delete`&&It?{deleteFrom:{backend:It.backend,folder:It.rel}}:{},folder:n.folder,filename:n.filename,onConflict:n.onConflict}),o=t===`delete`?await Bn(V.ids,a,{shouldStop:()=>Pt.current,onProgress:(t,n)=>{At({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(V.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}. ${Et(o.failed,new Map(r.map(e=>[e.id,F(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];St(g.length?{ids:g,mode:t}:null),z(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{Ft.current=!1,Ot(!1),At(null)}},[s,V,It,r,on]),Tr=(0,W.useCallback)(()=>{R.size===Z.length?z(new Set):z(new Set(Z.map(e=>e.id)))},[R.size,Z]),Er=(0,W.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=()=>z(new Set),c=e.some(e=>r.find(t=>t.id===e)?.locations?.some(e=>e.status==null||e.status===`available`)),l=[],d=e=>{e&&l.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;d({id:`view`,group:`open`,label:`View details`,icon:pe,run:()=>Zt({document:i})}),d(qt&&{id:`edit`,group:`open`,label:`Edit`,icon:f,run:()=>Zt({document:i,edit:!0})}),d(qt&&i.schema===`data/schema/file`&&{id:`rename`,group:`open`,label:`Rename…`,icon:f,run:()=>Zt({document:i,edit:!0})});let t=i.data?.url||i.data?.uri;d(qt&&s&&i.schema!==`data/schema/file`&&typeof t==`string`&&/^https?:\/\//i.test(t)&&{id:`download-link`,group:`open`,label:`Download to workspace`,icon:Ce,run:async()=>{let e=on({title:`Downloading file…`});try{await We(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`})}}}),d(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:_e,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),d(ln&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:ae,run:()=>ln(i)})}return d(T&&{id:`copy`,group:`clipboard`,label:`Copy${n}`,icon:te,shortcut:`Mod+C`,run:()=>T(e)}),d(ne&&{id:`cut`,group:`clipboard`,label:`Cut${n}`,icon:Te,shortcut:`Mod+X`,run:()=>ne(e)}),d(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:se,run:()=>Er(String(i.id))}),d(i&&qt&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:xe,run:()=>Yt(i)}),d(Qt&&{id:`link-to`,group:`organize`,label:`Link to…${n}`,icon:Se,run:()=>mt(e)}),d(gt&&{id:`add-related`,group:`organize`,label:`Add related document…${n}`,icon:C,run:t=>_t(e,t?.shiftKey)}),d(qt&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${n}`,icon:f,run:()=>Kt(e)}),d(qt&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:te,run:t=>{Wt(!!t?.shiftKey),Vt(e)}}),d({id:`export`,group:`organize`,label:`Export…${n}`,icon:Ce,run:()=>mn(!0)}),d(o!==`backends`&&(dn||fn)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${n}`,icon:v,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&dn?dn(e[0]):fn?.(e),a()}}),d(o!==`backends`&&(y||w)&&{id:`delete`,group:`remove`,label:`Delete from index${n}`,icon:oe,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&y?y(e[0]):w?.(e),a()}}),c&&en?(d({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${n}`,icon:u,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>St({ids:e,mode:`copy`})}),d({id:`backend-move`,group:`backends`,label:`Move to backend…${n}`,icon:fe,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>St({ids:e,mode:`move`})}),d({id:`backend-delete`,group:`backends`,label:`Delete from backend…${n}`,icon:oe,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>St({ids:e,mode:`delete`})})):c&&(b||ee)&&d({id:`destroy`,group:`backends`,label:`Delete from backend(s)${n}`,icon:oe,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&b?b(e[0]):ee?.(e),a()}}),l},Or=()=>{let e=[],t=t=>{t&&e.push(t)},n=k??[];return t(D&&n.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${n.length})`,icon:l,shortcut:`Mod+V`,run:async()=>{try{await D(a,n)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(Z.length>0&&{id:`select-all`,group:`select`,label:G?`Select all matches (${Z.length})`:`Select all on this page`,icon:ve,shortcut:`Mod+A`,run:()=>z(new Set(Z.map(e=>e.id)))}),t(R.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:be,run:()=>z(new Set)}),t(D&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:de,hint:`Browse and add existing documents to this folder`,run:()=>zt(!0)}),t(O&&{id:`import`,group:`add`,label:`Import…`,icon:ie,run:()=>Cn(!0)}),t(r.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:Ce,run:()=>{z(new Set),mn(!0)}}),t(Ae&&p>0&&{id:`purge`,group:`purge`,label:`Purge all (${p})`,icon:oe,destructive:!0,disabled:je||!!G,hint:G?`Purge is disabled while local search is active`:je?`Purge requires loaded server results with no browser-only or live selection`:`Delete all documents matching the current server-side filters across all pages`,run:Ae}),e},kr=!!(He&&I&&s),Ar=B?B.ids?Dr(B.ids):Or():[],jr=B?.ids?.length===1?r.find(e=>e.id===B.ids[0]):void 0,Mr=jr?(0,J.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,J.jsx)(H,{document:jr,chip:!0}),(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsx)(`div`,{className:`truncate text-base font-semibold`,children:F(jr).title}),(0,J.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,jr.id,` · `,jr.schema]})]})]}):(0,J.jsx)(`div`,{className:`truncate text-base font-semibold`,children:B?.ids?`${B.ids.length} documents`:`This folder`}),Nr=e=>{ft({anchor:Ie(e.currentTarget),ids:R.size>0?Array.from(R):null})},Pr=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),z(new Set),ft({anchor:qr(e),ids:null}))},Fr=e=>{if(e.defaultPrevented||Le(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Fe(e)){e.preventDefault(),t?vr(Number(t.dataset.documentId),Ie(t,`inside`)):ft({anchor:Ie(e.target,`inside`),ids:R.size>0?Array.from(R):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`&&R.size>0){e.preventDefault(),z(new Set);return}ze(e,[...Dr(Array.from(R)),...Or()])},Ir=(0,W.useCallback)(async e=>{if(!O)return!1;try{return await O(e,a)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[O,a]),Lr=e=>dr?lr.map(t=>{let n=st.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!R.has(t),0);return(0,J.jsxs)(`section`,{className:`group mb-4`,children:[(0,J.jsx)(mi,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>ut(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:L===`table`?rr:Z,loading:!1,children:(0,J.jsxs)(`div`,{tabIndex:-1,onKeyDown:Fr,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${Dn?`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:G?`${Z.length} of ${r.length}`:`${p.toLocaleString()} document${p===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:K,className:`min-w-0 truncate`,children:[`Context: `,(0,J.jsx)(`span`,{className:`font-mono`,children:a}),ge&&ye&&ge!==ye&&(0,J.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,J.jsxs)(`p`,{className:`shrink-0`,children:[R.size>0&&(0,J.jsxs)(`span`,{className:`text-info`,children:[R.size,` selected`]}),R.size>0&&(G||p>j)&&(0,J.jsx)(`span`,{className:`mx-1`,children:`·`}),G?`on this page`:p>j?`Showing ${Math.min((A-1)*j+1,p)}–${Math.min(A*j,p)}`:null]})]})]}),!K&&(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:[!K&&Ge&&(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:()=>Ge(`path`),className:`px-2.5 py-2 transition-colors ${Ue===`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:()=>Ge(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${Ue===`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)(re,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!K&&(0,J.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,J.jsx)(De,{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:An,type:`text`,placeholder:Be?kn?`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=>En(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`&&Be&&(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`}),Be&&s&&(0,J.jsx)(Ct,{workspaceId:s,inputRef:An,onChange:En}),(G||kn)&&(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)(x,{className:`h-4 w-4`})})]}),!K&&Be&&G.trim()&&!P.includes(G.trim())&&(0,J.jsxs)(N,{size:`sm`,variant:`default`,onClick:Pn,className:`shrink-0`,title:kn?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,J.jsx)(De,{className:`h-3.5 w-3.5 mr-1`}),kn?`Refine`:`Search server`]})]}),!K&&kn&&(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:`}),P.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,`"`]}),Ve&&(0,J.jsx)(`button`,{onClick:()=>Ve(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,J.jsx)(x,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),Ve&&P.length>1&&(0,J.jsx)(`button`,{onClick:()=>Ve(-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:[he&&(0,J.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,we,`Tile view`],[`card`,Ee,`Card view`]].map(([e,t,n])=>(0,J.jsx)(`button`,{type:`button`,onClick:()=>rt(e),title:n,"aria-pressed":L===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${L===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,J.jsx)(t,{className:`h-4 w-4`})},e))}),he&&L!==`table`&&!xt(I?.sortBy)&&(0,J.jsx)(`button`,{type:`button`,onClick:ot,title:it?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":it,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${it?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,J.jsx)(_,{className:`h-4 w-4`})})]}),M&&p>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:j,onChange:e=>ke?.(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:I,onChange:He})]}),(0,J.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(r.length>0||O||D)&&(0,J.jsxs)(`div`,{className:`contents`,children:[(0,J.jsxs)(N,{variant:`outline`,size:`sm`,onClick:Nr,"aria-haspopup":`menu`,"aria-label":R.size>0?`Actions (${R.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${Pe(`Shift+F10`)} or right-click)`,children:[(0,J.jsx)(me,{className:`h-4 w-4`}),(0,J.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,R.size>0?` (${R.size} selected)`:``]})]}),R.size>0&&(0,J.jsxs)(N,{variant:`ghost`,size:`sm`,onClick:()=>z(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,J.jsx)(x,{className:`h-3.5 w-3.5`}),(0,J.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),k&&k.length>0&&D&&(0,J.jsxs)(N,{variant:`outline`,size:`sm`,onClick:()=>D(a,k),className:`flex items-center gap-1.5`,title:`Paste into this folder (${Pe(`Mod+V`)})`,children:[(0,J.jsx)(l,{className:`h-4 w-4`}),`Paste (`,k.length,`)`]})]}),Ke&&Je&&(0,J.jsx)(N,{size:`sm`,variant:`outline`,onClick:Je,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)(m,{className:`h-3.5 w-3.5`})}),n]})]})]})}),M&&p>j&&(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((A-1)*j+1,p),` - `,Math.min(A*j,p),` of `,p]}),(0,J.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,J.jsx)(N,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>M(1),disabled:A===1,className:`p-1 touch-target`,children:(0,J.jsx)(d,{className:`h-4 w-4`})}),(0,J.jsx)(N,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>M(A-1),disabled:A===1,className:`p-1 touch-target`,children:(0,J.jsx)(h,{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 `}),A,(0,J.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,J.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(p/j)]}),(0,J.jsx)(N,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>M(A+1),disabled:A>=Math.ceil(p/j),className:`p-1 touch-target`,children:(0,J.jsx)(E,{className:`h-4 w-4`})}),(0,J.jsx)(N,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>M(Math.ceil(p/j)),disabled:A>=Math.ceil(p/j),className:`p-1 touch-target`,children:(0,J.jsx)(Oe,{className:`h-4 w-4`})})]})]})]}),(0,J.jsx)(er,{scope:JSON.stringify([hr,L,pr]),selected:R,onSelectionChange:Q,onContextMenu:Pr,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)(le,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:G?`No documents match your search`:`No documents found in this context`}),(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:G?(0,J.jsxs)(J.Fragment,{children:[`Search: `,(0,J.jsxs)(`span`,{className:`font-mono`,children:[`"`,G,`"`]})]}):(0,J.jsxs)(J.Fragment,{children:[`Path: `,(0,J.jsx)(`span`,{className:`font-mono`,children:a})]})}),!K&&G&&(0,J.jsx)(`button`,{onClick:q,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!G&&k&&k.length>0&&(0,J.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,Pe(`Mod+V`),` to paste `,k.length,` document(s)`]})]})}):L===`tile`?(0,J.jsxs)(`div`,{children:[(0,J.jsx)(di,{...$n}),Z.length===0&&(0,J.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Lr(e=>(0,J.jsx)(`div`,{className:`document-tiles pr-2`,"data-tile-style":et,children:e.map(e=>(0,J.jsx)(ii,{document:e,isSelected:R.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:ln,onRightClick:br,onOpenActions:yr,onDragStart:In},e.id))}))]}):L===`table`?(0,J.jsx)(`div`,{children:(0,J.jsxs)(bn,{children:[(0,J.jsx)(xn,{children:(0,J.jsxs)(gn,{children:[(0,J.jsx)(yn,{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&&R.size===Z.length,ref:e=>{e&&(e.indeterminate=R.size>0&&R.size<Z.length)},onChange:Tr,title:`Select all on this page`})}),(0,J.jsx)(vn,{label:(0,J.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:ir,onSort:or,className:`w-12`}),(0,J.jsx)(vn,{label:`Title`,sortKey:`title`,sort:ir,onSort:or,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,J.jsx)(vn,{label:`Schema`,sortKey:`schema`,sort:ir,onSort:or,className:`hidden md:table-cell`}),(0,J.jsx)(vn,{label:`ID`,sortKey:`id`,sort:ir,onSort:or,className:`hidden lg:table-cell`}),(0,J.jsx)(yn,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,J.jsx)(vn,{label:`Created`,sortKey:`created`,sort:ir,onSort:or,className:`hidden sm:table-cell`}),(0,J.jsx)(yn,{className:`w-12 md:w-auto`,children:(0,J.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,J.jsxs)(_n,{children:[Gn.map(e=>(0,J.jsx)(pi,{folder:e,onOpen:Qe,onMenu:Qn,onPasteDocuments:D,contextPath:a,treeName:o,workspaceId:s},e.path)),rr.map(e=>(0,J.jsx)(Zr,{document:e,isSelected:R.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:ln,onRightClick:br,onOpenActions:yr,onDragStart:In},e.id))]})]})}):(0,J.jsxs)(`div`,{children:[(0,J.jsx)(fi,{...$n}),Z.length===0&&(0,J.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Lr(e=>(0,J.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,J.jsx)(`div`,{children:(0,J.jsx)(Qr,{document:e,isSelected:R.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:ln,onRightClick:br,onOpenActions:yr,onDragStart:In})},e.id))}))]})}),B&&(0,J.jsx)(Ne,{anchor:B.anchor,items:Ar,onClose:()=>ft(null),label:B.ids?`Document actions`:`Folder actions`,header:Mr}),(0,J.jsx)(Wr,{isOpen:pn,onClose:()=>mn(!1),documents:r,selectedDocuments:R}),(0,J.jsx)(Gr,{isOpen:U,onClose:()=>Cn(!1),onImport:Ir}),Bt&&s&&(0,J.jsx)(nr,{modal:Ht,workspaceId:s,ids:Bt,onClose:()=>Vt(null)}),pt&&Ye&&(0,J.jsx)(qn,{label:`Link to`,onClose:()=>mt(null),children:(0,J.jsx)(Re,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:pt.length,fixedWorkspaceName:s,tabs:[`context`,`directory`,`relations`],saving:vt,relationExcludeIds:new Set(pt),onConfirm:(e,t)=>Sr(e,pt,t),onConfirmRelation:e=>xr(e,pt),onClose:()=>mt(null)})}),V&&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)(wt,{workspaceId:s,documentCount:V.ids.length,initialMode:V.mode,defaultFilename:V.ids.length===1?dt(r.find(e=>e.id===V.ids[0])??{}):``,saving:Tt,progress:kt,stopping:jt,onStop:()=>{Pt.current=!0,Mt(!0)},deleteFrom:It?{backend:It.backend,folder:It.rel}:void 0,onConfirm:Cr,onClose:()=>{Tt||St(null)}})}),window.document.body),Rt&&D&&(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)(tn,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:s,onConfirm:async e=>{await D(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:Xt?.document??null,isOpen:!!Xt,onClose:()=>Zt(null),workspaceId:s,initialEdit:Xt?.edit}),Xn&&s&&o&&Qe&&(0,J.jsx)(Hr,{x:Xn.x,y:Xn.y,workspaceName:s,treeName:o,path:Xn.path,onClose:()=>Zn(null),onOpen:Qe,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:s,treeName:o,path:e}})),pastedDocumentIds:k,onPasteDocuments:D?(e,t)=>D(e,t):void 0})]})})}function gi(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,cr.createRoot)(t);n.render((0,J.jsx)(Gr,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function _i(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,cr.createRoot)(t);n.render((0,J.jsx)(Wr,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{jn as C,Pn as S,sr as _,Pr as a,Un as b,kr as c,Tr as d,Er as f,ur as g,fr as h,Br as i,Ar as l,gr as m,Vr as n,jr as o,Dr as p,zr as r,Fr as s,hi as t,Nr as u,ar as v,Tn as w,Ln as x,qn as y};