@augmentd-labs/canvas-web 2.26.23 → 2.26.24

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 (73) hide show
  1. package/dist/assets/{FileForm-DhQhVnoi.js → FileForm-CqJpRbXv.js} +1 -1
  2. package/dist/assets/{FiltersApplet-BAe-Eq0e.js → FiltersApplet-CcYMBq-Q.js} +1 -1
  3. package/dist/assets/{HomeFab-BXSAtndH.js → HomeFab-D2pLJ9oc.js} +1 -1
  4. package/dist/assets/{IdentityFields-OPEWPlZs.js → IdentityFields-Bti7ojF3.js} +1 -1
  5. package/dist/assets/{LensApplet-DuADvEm5.js → LensApplet-DibGKbKC.js} +1 -1
  6. package/dist/assets/LinkToCard-5dg0jvSY.js +1 -0
  7. package/dist/assets/{NextShell-BIYs9fCL.js → NextShell-UX4Efo0u.js} +1 -1
  8. package/dist/assets/{NotesApplet-BmLjXx7V.js → NotesApplet-DJp9Wuwt.js} +1 -1
  9. package/dist/assets/{ObjectPropertiesCard-ChvWbOpZ.js → ObjectPropertiesCard-BIBMvx_i.js} +4 -4
  10. package/dist/assets/{PathPickerField-DBe7jykL.js → PathPickerField-fZazwxCN.js} +1 -1
  11. package/dist/assets/{PickDocumentsCard-Bo224P4q.js → PickDocumentsCard-DamtV7fN.js} +1 -1
  12. package/dist/assets/{SketchApplet-ADVOnSLI.js → SketchApplet-DDIg411i.js} +1 -1
  13. package/dist/assets/{SketchEditor-CkgRysCG.js → SketchEditor-CKPPuZt3.js} +1 -1
  14. package/dist/assets/{TerminalApplet-CkO4uaE3.js → TerminalApplet-wGJG1PPc.js} +1 -1
  15. package/dist/assets/{TextDocumentEditor-COvsHJXH.js → TextDocumentEditor-CRre32cj.js} +1 -1
  16. package/dist/assets/{TodosApplet-Bpf1OIH4.js → TodosApplet-CleBd4uU.js} +1 -1
  17. package/dist/assets/{TodosWidget-BIYqPXUp.js → TodosWidget-CxiqmDuJ.js} +1 -1
  18. package/dist/assets/{UploadProgressList-BXJr87lI.js → UploadProgressList-DRJzjy6A.js} +1 -1
  19. package/dist/assets/{_agentId_-Bquq_bl1.js → _agentId_--jQP7aTv.js} +0 -0
  20. package/dist/assets/{_contextId_-DndAgEMz.js → _contextId_-D6nNA8hC.js} +1 -1
  21. package/dist/assets/_workspaceName_-DfHnlgVg.js +1 -0
  22. package/dist/assets/{about-DpILEqyH.js → about-DVlaoa-W.js} +1 -1
  23. package/dist/assets/{add-BHkmOOkO.js → add-Bq99uA2R.js} +1 -1
  24. package/dist/assets/{agents-lo0DGGKV.js → agents-CRnO7j5E.js} +1 -1
  25. package/dist/assets/{appearance-5Vx17gl4.js → appearance-BAH_8zeF.js} +1 -1
  26. package/dist/assets/{applet-target-ChiiXVdC.js → applet-target-C_gBgU-Z.js} +1 -1
  27. package/dist/assets/{apps-Ci03cFZm.js → apps-EwUooEtp.js} +1 -1
  28. package/dist/assets/{backend-sync-progress-H4Zch25P.js → backend-sync-progress-pZrhQPk3.js} +3 -3
  29. package/dist/assets/{content-app-view-BFluU_u6.js → content-app-view-BF-k-5Y7.js} +1 -1
  30. package/dist/assets/{context-mfIOB8dN.js → context-DQoZFMDQ.js} +1 -1
  31. package/dist/assets/{contexts-CRWqFXzJ2.js → contexts-CvMtPd1N2.js} +1 -1
  32. package/dist/assets/{date-time-picker-B6mkWt-g.js → date-time-picker-DebNUTx3.js} +1 -1
  33. package/dist/assets/{document-CX543Kcz.js → document-DOp6AbOi.js} +1 -1
  34. package/dist/assets/document-list-Dsf1DVEx.js +2 -0
  35. package/dist/assets/{home-Dus2Lg1o.js → home-Dc60CSIJ.js} +1 -1
  36. package/dist/assets/{index-Tx_qtD_m.js → index-D5Q9EUVc.js} +6 -6
  37. package/dist/assets/{key-bindings-C1Zk8f6z.js → key-bindings-Bqkl5tDH.js} +1 -1
  38. package/dist/assets/{offline-CsRyFUg7.js → offline-COOUcZsG.js} +1 -1
  39. package/dist/assets/{public-share-DXxVwHKT.js → public-share-g_wBd6BW.js} +1 -1
  40. package/dist/assets/{query-debug-YfWOzM6h.js → query-debug-CrPsUwT-.js} +1 -1
  41. package/dist/assets/{registry-J0TPxyW8.js → registry-DIfZf6LB.js} +2 -2
  42. package/dist/assets/{roles-BYHLwWCD.js → roles-Bo9GZdOk.js} +1 -1
  43. package/dist/assets/{settings-DLbaI3my.js → settings-BeN2UmZL.js} +1 -1
  44. package/dist/assets/{settings-D089lyYg.js → settings-CzxxI2yw.js} +1 -1
  45. package/dist/assets/{settings-B8BgCI2q.js → settings-Dl1FnW9g.js} +1 -1
  46. package/dist/assets/settings-DqHAUBU4.js +14 -0
  47. package/dist/assets/{share-target-CMIiAOIz.js → share-target-BWFFRO5O.js} +1 -1
  48. package/dist/assets/{shared-B6YGbqUJ.js → shared-B5Pvz8wr.js} +1 -1
  49. package/dist/assets/{shared-D2uRUNdC.js → shared-BQZGA3ph.js} +1 -1
  50. package/dist/assets/{sketch-lazy-pbG2cCpW.js → sketch-lazy-C4pjV1WK.js} +2 -2
  51. package/dist/assets/{text-documents-BvDFBVnC.js → text-documents-0P9jkIpu.js} +2 -2
  52. package/dist/assets/{use-applet-docs-o5NAUFBk.js → use-applet-docs-D5eXpITp.js} +1 -1
  53. package/dist/assets/{use-applet-target-cO-FiyPQ.js → use-applet-target-gXPvZGgx.js} +1 -1
  54. package/dist/assets/use-canvas-pins-CbAxLLTU.js +3 -0
  55. package/dist/assets/{use-workspace-identity-mgaofjsD.js → use-workspace-identity-BCrrvfeE.js} +1 -1
  56. package/dist/assets/{useAddTarget-DUjaZdBQ.js → useAddTarget-CqnDU0Om.js} +1 -1
  57. package/dist/assets/{useAgentModels-Cxb5NyCI.js → useAgentModels-CYDYTjgG.js} +1 -1
  58. package/dist/assets/{useDocumentThumbnail-DYLCC63L.js → useDocumentThumbnail-DunxmU1A.js} +1 -1
  59. package/dist/assets/{useEditNoteFields-zHEWwDfB.js → useEditNoteFields-BehI0vog.js} +1 -1
  60. package/dist/assets/workspace-CrSpR4xf.js +1 -0
  61. package/dist/assets/{workspace-area-menu-Dg3hXKR3.js → workspace-area-menu-CP5OWZNX.js} +1 -1
  62. package/dist/assets/{workspace-content-gate-Be4tLYiB.js → workspace-content-gate-9okuA7J7.js} +1 -1
  63. package/dist/assets/{workspace-import-form-BRwc_oVg.js → workspace-import-form-aR-DwHf6.js} +1 -1
  64. package/dist/assets/{workspaces-BOYcqiRy.js → workspaces-B9gcHMCE.js} +1 -1
  65. package/dist/index.html +25 -25
  66. package/dist/sw.js +1 -1
  67. package/package.json +2 -2
  68. package/dist/assets/LinkToCard-nR7Lal_o.js +0 -1
  69. package/dist/assets/_workspaceName_-C_tzeHUf.js +0 -1
  70. package/dist/assets/document-list-rh4ittZx.js +0 -2
  71. package/dist/assets/settings-Ba8Od_Uj.js +0 -14
  72. package/dist/assets/use-canvas-pins-6vnfChWd.js +0 -3
  73. package/dist/assets/workspace-DvxC7pw1.js +0 -1
@@ -1 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{_t as r,yt as i}from"./react-BHzhHVTZ.js";import{Br as a,Cr as o,Hr as s,It as c,Kn as l,L as u,Un as d,Xn as f,_n as p,mt as m,yt as h,zn as g}from"./ui-Byg1cZDr.js";import{t as _}from"./utils-2pl1SbIp.js";import{t as v}from"./button-SgR3GVvV.js";import{K as y,Ot as b,Pn as x,Pt as S,Q as C,gt as w,ht as T,it as ee,q as te,t as ne}from"./workspace-DvxC7pw1.js";import{t as E}from"./useEscapeClose-DR_xKT_k.js";import{t as re}from"./useToastHelpers-CRrpIIdY.js";import{s as D}from"./layer-style-Byl5LNFR.js";import{i as O}from"./color-DFEH4BfK.js";import{t as ie}from"./DocumentIcon-x299QNu_.js";var k=e(n(),1),A=t();function j({className:e=`h-5 w-5`,...t}){return(0,A.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,A.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,A.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}var M=e(i(),1);function ae(e){let[t,n]=(0,k.useState)(null);(0,k.useEffect)(()=>{if(!e)return;let t=!1;return C(e).then(r=>{t||n({workspaceId:e,predicates:r,error:!1})},()=>{t||n({workspaceId:e,predicates:[],error:!0})}),()=>{t=!0}},[e]);let r=t?.workspaceId===e?t:null;return{predicates:r?.predicates??[],error:r?.error??!1,loading:!!e&&!r}}function N({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,k.useRef)(null),[o,s]=(0,k.useState)({x:e,y:t});return E(n),(0,k.useLayoutEffect)(()=>{let n=a.current;if(!n)return;let{width:r,height:i}=n.getBoundingClientRect();s({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})},[e,t]),(0,M.createPortal)((0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,A.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:_(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r,`bg-popover text-popover-foreground`),children:i})]}),document.body)}var P=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),F={Delete:`Del`,Backspace:`⌫`,Enter:`↵`,ArrowUp:`↑`,ArrowDown:`↓`};function I(e){let t=e.split(`+`),n=t.pop()||``,r=F[n]||(n.length===1?n.toUpperCase():n);if(P){let e={Mod:`⌘`,Shift:`⇧`,Alt:`⌥`,Ctrl:`⌃`};return[...[`Ctrl`,`Alt`,`Shift`,`Mod`].filter(e=>t.includes(e)).map(t=>e[t]),r].join(``)}return[...t.map(e=>e===`Mod`?`Ctrl`:e),r].join(`+`)}function L(e,t){let n=t.split(`+`),r=n.pop()||``;return(P?e.metaKey:e.ctrlKey)!==n.includes(`Mod`)||e.shiftKey!==n.includes(`Shift`)||e.altKey!==n.includes(`Alt`)||P&&e.ctrlKey!==n.includes(`Ctrl`)?!1:r.length===1?e.key.toLowerCase()===r.toLowerCase():e.key===r}function R(e){if(e?.closest?.(`input, textarea, select, [contenteditable="true"], [role="dialog"], [role="menu"]`))return!0;let t=typeof window<`u`?window.getSelection():null;return!!t&&!t.isCollapsed&&t.toString().length>0}function z(e,t){if(e.defaultPrevented||e.nativeEvent.isComposing||R(e.target))return!1;let n=t.find(t=>t.shortcut&&!t.disabled&&L(e,t.shortcut));return n?(e.preventDefault(),e.stopPropagation(),n.run({shiftKey:e.shiftKey}),!0):!1}function oe(e){return e.key===`ContextMenu`||e.key===`F10`&&e.shiftKey}function se(){return typeof window<`u`&&window.matchMedia(`(max-width: 767px)`).matches}function B(e,t=`below`){let n=e.getBoundingClientRect();return t===`below`?{x:n.left,y:n.bottom+4}:{x:n.left+Math.min(24,n.width/2),y:n.top+Math.min(24,n.height/2)}}function V(e){let t=[];for(let n of e){let e=t[t.length-1];e&&(e[0].group??``)===(n.group??``)?e.push(n):t.push([n])}return t}function ce(e,t,n){t(),setTimeout(()=>{e.run({shiftKey:n})},0)}function le({anchor:e,items:t,onClose:n,label:r}){let i=(0,k.useRef)(null);return(0,k.useEffect)(()=>{let e=document.activeElement;return i.current?.querySelector(`[role="menuitem"]:not([aria-disabled="true"])`)?.focus(),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[]),(0,A.jsx)(N,{x:e.x,y:e.y,onClose:n,className:`min-w-[200px] rounded-lg border bg-popover text-popover-foreground py-1 shadow-elevation-3`,children:(0,A.jsx)(`div`,{ref:i,role:`menu`,"aria-label":r,onKeyDown:e=>{let t=Array.from(i.current?.querySelectorAll(`[role="menuitem"]:not([aria-disabled="true"])`)??[]);if(t.length===0)return;let r=t.indexOf(document.activeElement),a=e=>t[(e+t.length)%t.length]?.focus();switch(e.key){case`ArrowDown`:e.preventDefault(),a(r+1);return;case`ArrowUp`:e.preventDefault(),a(r<0?-1:r-1);return;case`Home`:e.preventDefault(),a(0);return;case`End`:e.preventDefault(),a(-1);return;case`Tab`:e.preventDefault(),n();return}if(e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let n=e.key.toLowerCase(),i=[...t.slice(r+1),...t.slice(0,r+1)].find(e=>e.textContent?.trim().toLowerCase().startsWith(n));i&&(e.preventDefault(),i.focus())}},onContextMenu:e=>e.preventDefault(),children:V(t).map((e,t)=>(0,A.jsxs)(k.Fragment,{children:[t>0&&(0,A.jsx)(`div`,{role:`separator`,className:`my-1 h-px bg-border`}),e[0].groupLabel&&(0,A.jsx)(`div`,{className:`px-3 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let t=e.icon;return(0,A.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,"aria-disabled":e.disabled||void 0,title:e.hint,onClick:t=>{e.disabled||ce(e,n,t.shiftKey)},className:_(`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm outline-none`,e.disabled?`cursor-default opacity-50`:e.destructive?`text-destructive hover:bg-destructive hover:text-destructive-foreground focus:bg-destructive focus:text-destructive-foreground`:`hover:bg-muted focus:bg-muted`),children:[t?(0,A.jsx)(t,{className:`h-3.5 w-3.5 shrink-0`}):(0,A.jsx)(`span`,{className:`w-3.5 shrink-0`}),(0,A.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.shortcut&&(0,A.jsx)(`kbd`,{className:`ml-4 shrink-0 font-sans text-[11px] text-muted-foreground`,children:I(e.shortcut)})]},e.id)})]},`${e[0].group??``}:${t}`))})})}function H({items:e,onClose:t,header:n}){E(t);let r=`flex w-full items-center gap-3 rounded-xl border bg-card px-4 py-3.5 text-base font-medium transition-transform active:scale-[.98]`;return(0,M.createPortal)((0,A.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-popover text-popover-foreground animate-in slide-in-from-bottom-10 fade-in duration-normal`,onClick:t,onContextMenu:e=>e.preventDefault(),children:[(0,A.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,A.jsx)(`div`,{className:`min-w-0 flex-1`,children:n}),(0,A.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,A.jsx)(u,{className:`h-5 w-5`})})]}),(0,A.jsx)(`div`,{className:`min-h-4 flex-1`}),(0,A.jsxs)(`div`,{className:`max-h-[75vh] shrink-0 space-y-2 overflow-y-auto px-4 pt-2`,style:{paddingBottom:`calc(var(--safe-bottom) + 1.25rem)`},onClick:e=>e.stopPropagation(),children:[V(e).map((e,n)=>(0,A.jsxs)(`div`,{className:_(`space-y-2`,n>0&&`pt-2`),children:[e[0].groupLabel&&(0,A.jsx)(`div`,{className:`px-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let n=e.icon;return(0,A.jsxs)(`button`,{type:`button`,disabled:e.disabled,onClick:n=>ce(e,t,n.shiftKey),className:_(r,e.destructive&&`border-destructive/30 text-destructive`,e.disabled&&`opacity-50`),children:[n&&(0,A.jsx)(n,{className:_(`h-5 w-5 shrink-0`,!e.destructive&&`text-muted-foreground`)}),e.label]},e.id)})]},`${e[0].group??``}:${n}`)),(0,A.jsx)(`button`,{type:`button`,onClick:t,className:`${r} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function ue({anchor:e,items:t,onClose:n,label:r,header:i}){return t.length===0?null:se()?(0,A.jsx)(H,{items:t,onClose:n,header:i??(r&&(0,A.jsx)(`div`,{className:`truncate text-base font-semibold`,children:r}))}):(0,A.jsx)(le,{anchor:e,items:t,onClose:n,label:r})}function U({items:e,onNavigate:t,disabled:n,className:r,label:i=`Tree path`}){let a=(0,k.useRef)(null),o=e[e.length-1]?.path;return(0,k.useEffect)(()=>{let e=a.current;e&&(e.scrollLeft=e.scrollWidth)},[o]),(0,A.jsx)(`nav`,{"aria-label":i,className:_(`min-w-0 flex-1`,r),children:(0,A.jsx)(`ol`,{ref:a,className:`flex min-w-0 items-center gap-1 overflow-x-auto py-0.5 text-sm`,children:e.map((r,i)=>{let a=i===e.length-1,o=_(`block max-w-56 truncate rounded px-1.5 py-1`,a?`font-medium text-foreground`:`text-muted-foreground`);return(0,A.jsxs)(`li`,{className:`flex shrink-0 items-center gap-1`,children:[i>0&&(0,A.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/60`,children:`/`}),t&&!a?(0,A.jsx)(`button`,{type:`button`,title:r.path===`/`?`${r.label} (root)`:r.path,disabled:n,onClick:()=>t(r.path),className:_(o,`hover:bg-accent hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50`),children:r.label}):(0,A.jsx)(`span`,{title:r.path===`/`?r.label:r.path,"aria-current":a?`location`:void 0,className:o,children:r.label})]},r.path)})})})}function W(e,t){let n=e.split(`/`).filter(Boolean);return[{label:t,path:`/`},...n.map((e,t)=>({label:e,path:`/${n.slice(0,t+1).join(`/`)}`}))]}var de={context:(0,A.jsx)(d,{className:`h-3.5 w-3.5`}),directory:(0,A.jsx)(l,{className:`h-3.5 w-3.5`}),backends:(0,A.jsx)(g,{className:`h-3.5 w-3.5`}),relations:(0,A.jsx)(m,{className:`h-3.5 w-3.5`})},fe={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function pe(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function me(e,t){let n=(0,k.useRef)(null),r=(0,k.useRef)(!1),i=()=>{n.current&&=(clearTimeout(n.current),null)},a=e=>t=>{if(r.current){r.current=!1;return}t.detail>1||e()};return t?{guardClick:a,handlers:{onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),t({clientX:n.clientX,clientY:n.clientY,path:e})},onPointerDown:a=>{if(a.pointerType!==`touch`)return;let{clientX:o,clientY:s}=a;i(),n.current=setTimeout(()=>{r.current=!0,t({clientX:o,clientY:s,path:e})},500)},onPointerUp:i,onPointerLeave:i,onPointerMove:i}}:{handlers:{},guardClick:a}}function he(e,t,n){let r=pe(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>he(e,r,n))??!1}var G=200;function ge({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,k.useState)(``);return(0,A.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 text-sm shadow-elevation-1`,children:[(0,A.jsx)(o,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:n=>{n.key===`Enter`&&r.trim()&&e(r.trim()),n.key===`Escape`&&t()},onBlur:()=>{n||t()},placeholder:`New folder name…`,autoFocus:!0,disabled:n,className:`w-full flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),n&&(0,A.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function _e({node:e,parentPath:t,query:n,selected:i,onToggle:o,onActivate:c,onRowMenu:l,createParent:u,onCreateConfirm:d,onCreateCancel:f,creating:p}){let m=pe(t,e.name),h=!!e.children?.length,[g,v]=(0,k.useState)(!1),{handlers:y,guardClick:b}=me(m,l);if(n&&!he(e,t,n))return null;let x=u===m,S=g||n.length>0||x,C=i.has(m),w=e.type===`canvas`,T=D(e);return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:_(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,C?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:b(()=>o(m)),onDoubleClick:e=>{e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button,input,textarea,select,a,[contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),h?v(e=>!e):c?.(m))},title:m,...y,children:[(0,A.jsx)(`button`,{type:`button`,"aria-label":`${S?`Collapse`:`Expand`} ${e.label||e.name}`,"aria-expanded":h?S:void 0,disabled:!h,className:_(`shrink-0 text-muted-foreground hover:text-foreground`,!h&&`invisible`),onClick:e=>{e.stopPropagation(),e.detail<=1&&v(e=>!e)},children:S?(0,A.jsx)(s,{className:`w-4 h-4`}):(0,A.jsx)(a,{className:`w-4 h-4`})}),(0,A.jsx)(r,{icon:T.icon||(w?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:O(T.color),className:_(`shrink-0`,!O(T.color)&&(w?`text-primary`:`text-muted-foreground`))}),(0,A.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),S&&h||x?(0,A.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[x&&d&&f&&(0,A.jsx)(ge,{busy:p,onConfirm:e=>{v(!0),d(m,e)},onCancel:f}),S&&e.children?.map(e=>(0,A.jsx)(_e,{node:e,parentPath:m,query:n,selected:i,onToggle:o,onActivate:c,onRowMenu:l,createParent:u,onCreateConfirm:d,onCreateCancel:f,creating:p},e.id||e.name))]}):null]})}function ve({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,A.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=O(e.color);return(0,A.jsxs)(`div`,{onClick:()=>n(e.name),className:`group relative flex cursor-pointer items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 shadow-elevation-1 transition-all hover:bg-accent/50 hover:shadow`,style:{borderRight:`6px solid ${t||`transparent`}`},children:[(0,A.jsx)(r,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:_(`shrink-0`,!t&&`text-muted-foreground`)}),(0,A.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,A.jsx)(a,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function ye({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:o,excludeDocumentIds:c}){let[l,d]=(0,k.useState)(`folder`),[f,p]=(0,k.useState)(``),m=f.trim().toLowerCase(),[g,v]=(0,k.useState)(`/`),[b,S]=(0,k.useState)(null),[C,w]=(0,k.useState)(!1),[T,E]=(0,k.useState)([]),[re,D]=(0,k.useState)(!1),[O,j]=(0,k.useState)(``),[M,ae]=(0,k.useState)(``),[N,P]=(0,k.useState)(t),F=n?t:N,I=e=>{v(`/`),d(`folder`),j(``),ae(``),o?.(`/`),n?n(e):P(e)},[L,R]=(0,k.useState)(F);F!==L&&(R(F),v(`/`),d(`folder`)),(0,k.useEffect)(()=>{let e=setTimeout(()=>ae(O.trim()),300);return()=>clearTimeout(e)},[O]),(0,k.useEffect)(()=>{let t=!1;async function n(){w(!0);try{let n=await y(e,F);t||S(n)}catch{t||S(null)}finally{t||w(!1)}}return n(),()=>{t=!0}},[e,F]),(0,k.useEffect)(()=>{if(l!==`documents`)return;let t=!1,n=F===`directory`?`directory`:ne,r=F===`context`?`context`:`directory`;async function i(){D(!0);try{let i=M?await ee(e,g,[],{treeName:n,treeType:r,q:M,limit:G}):await te(e,g,n,{limit:G});t||E(i.payload||[])}catch{t||E([])}finally{t||D(!1)}}return i(),()=>{t=!0}},[e,F,g,l,M]);let z=e=>{v(e),o?.(e)},oe=c?.size?T.filter(e=>!c.has(e.id)):T;return l===`folder`?(0,A.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,A.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,A.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,A.jsxs)(`button`,{type:`button`,onClick:()=>I(e),className:_(`flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors`,F===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Browse the ${fe[e].toLowerCase()}`,children:[de[e],(0,A.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>d(`documents`),className:`inline-flex items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90`,children:[`Next `,(0,A.jsx)(a,{className:`h-3.5 w-3.5`})]})]}),(0,A.jsx)(U,{items:W(g,e),onNavigate:z,label:`Folder path`}),(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(h,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,placeholder:`Filter folders…`,value:f,onChange:e=>p(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})]}),(0,A.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:C?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:_(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,g===`/`?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:()=>z(`/`),onDoubleClick:()=>{z(`/`),d(`documents`)},title:`/`,children:[(0,A.jsx)(s,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,A.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,A.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:b?.children?.length?b.children.map(e=>(0,A.jsx)(_e,{node:e,parentPath:`/`,query:m,selected:new Set([g]),onToggle:z,onActivate:e=>{z(e),d(`documents`)}},e.id||e.name)):(0,A.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,A.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,A.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>d(`folder`),className:`inline-flex min-w-0 items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Back to folders`,children:[(0,A.jsx)(a,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,A.jsx)(`span`,{children:`Folders`})]}),(0,A.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,A.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground`,children:[`[`,F,`]`]}),(0,A.jsx)(U,{items:W(g,e),onNavigate:z,label:`Document folder path`})]}),(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(h,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,placeholder:`Search documents in this folder…`,value:O,onChange:e=>j(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-7 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),O&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>j(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear document search`,children:(0,A.jsx)(u,{className:`h-3.5 w-3.5`})})]})]}),(0,A.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:re?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):oe.length===0?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:M?`No documents match “${M}” here.`:`No documents in this folder.`}):oe.map(e=>{let t=x(e),n=r.has(e.id);return(0,A.jsxs)(`div`,{onClick:()=>i(e.id),className:_(`flex min-h-9 items-center gap-2 rounded-md px-3 py-1.5 cursor-pointer transition-all select-none text-sm`,n?`bg-primary/[0.08] hover:bg-primary/[0.12]`:`hover:bg-primary/[0.04]`),children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,A.jsx)(ie,{document:e,size:3.5}),(0,A.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function be({onClose:e,onConfirm:t,documentCount:n,fixedWorkspaceName:r,excludeWorkspace:i,multiple:o=!0,saving:l=!1,savingContent:d,sizeClassName:m,tabs:g=[`context`,`directory`],initialTab:x,title:C,confirmLabel:ee,backendFolderCreation:te,onConfirmRelation:D,relationWorkspaceName:O,relationPredicates:ie,relationExcludeIds:M}){let[N,P]=(0,k.useState)(r?`tree`:`workspace`),[F,I]=(0,k.useState)([]),[L,R]=(0,k.useState)(!r),[z,oe]=(0,k.useState)(r??null),se=x&&g.includes(x)?x:g.includes(`context`)||g.includes(`directory`)?`pins`:g[0]??`context`,[B,V]=(0,k.useState)(se),ce=ae(g.includes(`relations`)&&!ie?O??z:null),H=ie??ce.predicates,[ue,U]=(0,k.useState)(``),W=H.includes(ue)?ue:H[0]??``,[pe,he]=(0,k.useState)(`out`),[G,be]=(0,k.useState)(new Set),[xe,Se]=(0,k.useState)(null),[K,Ce]=(0,k.useState)(`context`),[we,Te]=(0,k.useState)(!1),Ee=B===`pins`?K:B;(0,k.useEffect)(()=>{if(!z)return;let e=!1;return b(z).then(t=>{e||Se(t)}).catch(()=>{e||Te(!0)}),()=>{e=!0}},[z]);let q=B===`relations`,[De,Oe]=(0,k.useState)(null),[ke,Ae]=(0,k.useState)(!1),[J,Y]=(0,k.useState)(new Set),[je,Me]=(0,k.useState)(``),Ne=je.trim().toLowerCase(),{showErrorToast:Pe}=re(),[X,Fe]=(0,k.useState)(null),[Ie,Z]=(0,k.useState)(null),[Q,Le]=(0,k.useState)(!1);E(e,!l&&!Q);let Re=me(`/`,e=>Fe(e)),ze=e=>!l&&(B===`backends`?te?.canCreate(e)===!0:B!==`pins`&&B!==`relations`),Be=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!z||Q||!ze(e))){Le(!0);try{let t=`${e===`/`?``:e}/${n}`,r=B===`context`?ne:B;B===`backends`?await te.create(e,n):await T(z,t,!0,r),w(z,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:z,treeName:r,cacheInvalidated:!0}}));let i=await y(z,B);Oe(i),Y(e=>o?new Set([...e,t]):new Set([t])),Me(``),Z(null)}catch(e){Pe(e instanceof Error?e.message:`Failed to create folder`)}finally{Le(!1)}}},[Ve,He]=(0,k.useState)(r);r!==Ve&&(He(r),r||R(!0)),(0,k.useEffect)(()=>{r||S().then(e=>I(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>I([])).finally(()=>R(!1))},[r,i]),(0,k.useEffect)(()=>{if(!z||B===`relations`||B===`pins`)return;let e=!1,t=0;async function n(n=!1){let r=++t;n||Ae(!0);try{let n=await y(z,B);!e&&r===t&&Oe(n)}catch{!e&&r===t&&!n&&Oe(null)}finally{!e&&r===t&&Ae(!1)}}let r=e=>{let t=e.detail;t?.workspaceName&&t.workspaceName!==z||t?.treeName&&t.treeName!==B||(t?.cacheInvalidated||w(z,B),n(!0))};return window.addEventListener(`workspace:tree:refresh`,r),n(),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,r)}},[z,B]);let Ue=e=>{e!==z&&(Se(null),Te(!1)),V(se),oe(e),Y(new Set),be(new Set),P(`tree`)},We=e=>{be(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ge=e=>{if(!o){Y(new Set([e]));return}Y(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ke=q?!!W&&G.size>0&&!!D:J.size>0,qe=async()=>{if(!(!z||l||!Ke)){if(q){await D?.({predicate:W,direction:pe,targetIds:Array.from(G)},{workspaceName:O??z});return}await t(Array.from(J),{workspaceName:z,treeName:Ee===`context`?ne:Ee,treeType:Ee===`context`?`context`:`directory`})}},$=n??1;return l&&d?(0,A.jsx)(`div`,{className:_(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,m||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:d}):(0,A.jsxs)(`div`,{className:_(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,m||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,A.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,A.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,A.jsx)(p,{className:`h-4 w-4`}),C??(N===`workspace`?`Link to…`:q?`Relate ${$} document${$===1?``:`s`} to…`:`Link ${$} document${$===1?``:`s`} to…`)]}),(0,A.jsx)(`button`,{type:`button`,onClick:e,disabled:l||Q,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,A.jsx)(u,{className:`h-4 w-4`})})]}),(0,A.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,A.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-normal`,style:{transform:N===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,A.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,A.jsx)(ve,{workspaces:F,loading:L,onPick:Ue})}),(0,A.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,A.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,A.jsx)(`button`,{type:`button`,disabled:Q,onClick:()=>P(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,A.jsx)(a,{className:`h-4 w-4 rotate-180`})}),(g.includes(`context`)||g.includes(`directory`))&&(0,A.jsxs)(`button`,{type:`button`,disabled:Q,onClick:()=>{V(`pins`),Y(new Set),Z(null)},className:_(`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2 text-xs`,B===`pins`?`border-primary`:`border-transparent text-muted-foreground`),children:[(0,A.jsx)(c,{className:`h-3.5 w-3.5`}),`Pins`]}),g.map(e=>(0,A.jsxs)(`button`,{type:`button`,disabled:Q,onClick:()=>{V(e),Y(new Set),Z(null)},className:_(`flex shrink-0 items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,B===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[de[e],fe[e]]},e))]}),!q&&(0,A.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(h,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:je,onChange:e=>Me(e.target.value),className:`w-full rounded-md border border-input bg-background py-2 pl-9 pr-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})}),q&&(0,A.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,A.jsx)(`select`,{id:`relation-predicate`,value:W,onChange:e=>U(e.target.value),className:`min-w-0 flex-1 rounded-md border border-input bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,children:H.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})]}),(0,A.jsx)(`div`,{className:`flex items-center gap-1`,children:[{dir:`out`,label:`This → picked`,hint:`the ${$===1?`document`:`documents`} you started from ${W} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${W} the ${$===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,A.jsx)(`button`,{type:`button`,title:n,onClick:()=>he(e),className:_(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,pe===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!q&&o&&(0,A.jsxs)(`div`,{className:`flex h-10 shrink-0 items-center gap-1.5 overflow-x-auto border-b bg-primary/[0.04] px-3`,children:[!J.size&&(0,A.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Selected folders appear here`}),Array.from(J).map(e=>(0,A.jsxs)(`span`,{className:`inline-flex max-w-full shrink-0 items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground`,children:[(0,A.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>Ge(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,A.jsx)(u,{className:`h-3 w-3`})})]},e))]}),q&&(O??z)&&(0,A.jsx)(ye,{workspaceName:O??z,treeTab:`context`,selectedDocIds:G,onToggleDoc:We,excludeDocumentIds:M}),B===`pins`&&(0,A.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!xe&&!we&&(0,A.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),we&&(0,A.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!we&&xe?.length===0&&(0,A.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),xe?.filter(e=>e.resolvable!==!1&&g.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(Ne)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,A.jsxs)(`button`,{type:`button`,"aria-pressed":K===t&&J.has(e.path),className:_(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,K===t&&J.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{K===t?Ge(e.path):(Ce(t),Y(new Set([e.path])))},children:[(0,A.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(c,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,A.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,A.jsx)(`div`,{className:_(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(q||B===`pins`)&&`hidden`),children:ke?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:_(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,J.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:Re.guardClick(()=>Ge(`/`)),title:`/`,...ze(`/`)?Re.handlers:{},children:[(0,A.jsx)(s,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,A.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,A.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[Ie===`/`&&(0,A.jsx)(ge,{busy:Q,onConfirm:e=>Be(`/`,e),onCancel:()=>Z(null)}),De?.children?.length?De.children.map(e=>(0,A.jsx)(_e,{node:e,parentPath:`/`,query:Ne,selected:J,onToggle:Ge,onRowMenu:e=>{ze(e.path)&&Fe(e)},createParent:Ie,onCreateConfirm:Be,onCreateCancel:()=>Z(null),creating:Q},e.id||e.name)):Ie===`/`?null:(0,A.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),N===`tree`&&(0,A.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,A.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:q?`${G.size} document${G.size===1?``:`s`} selected`:`${J.size} path${J.size===1?``:`s`} selected`}),(0,A.jsx)(v,{size:`sm`,onClick:qe,disabled:!Ke||l||Q,children:l?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(j,{className:`mr-1.5 h-3.5 w-3.5`}),q?`Relating…`:`Linking…`]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(p,{className:`mr-1 h-3.5 w-3.5`}),q?`Relate`:ee??`Link`]})})]}),X&&(0,A.jsx)(le,{anchor:{x:X.clientX,y:X.clientY},onClose:()=>Fe(null),items:[{id:`new-folder`,label:`New folder in ${X.path}`,icon:f,run:()=>Z(X.path)}]})]})}export{j as _,fe as a,ue as c,I as d,oe as f,ae as g,N as h,de as i,B as l,L as m,ye as n,W as o,R as p,ve as r,U as s,be as t,z as u};
@@ -1 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{_ as r,g as i,h as a}from"./chunk-62JRHF6Z-vspAGgtK.js";import{Br as o,Hr as s,L as c,fn as l}from"./ui-Byg1cZDr.js";import{t as u}from"./utils-2pl1SbIp.js";import{t as d}from"./button-SgR3GVvV.js";import{c as f,t as p}from"./api-CA6WiiYM.js";import{t as m}from"./socket-CtH3EU9m.js";import{n as h}from"./use-toast-BlLDqSUO.js";import{$t as g,En as _,K as ee,Nt as te,O as ne,Qt as re,S as v,T as ie,Ut as y,Vt as b,Z as ae,at as oe,b as se,bt as ce,d as le,dn as ue,dt as de,gt as fe,it as pe,o as me,q as x,v as he,vt as ge,yn as S}from"./workspace-DvxC7pw1.js";import{n as _e,r as ve}from"./use-canvas-pins-6vnfChWd.js";import{u as ye}from"./ObjectPropertiesCard-ChvWbOpZ.js";import{h as be,i as C,r as xe}from"./document-list-rh4ittZx.js";import{n as Se}from"./use-toolbox-Ck_cLGgf.js";import{i as Ce}from"./color-DFEH4BfK.js";import{t as we}from"./geo-CZfs0E-x.js";import{c as Te}from"./backend-sync-progress-H4Zch25P.js";import{a as Ee,i as De,n as Oe,o as ke}from"./workspace-BydSRtST.js";import{n as Ae,r as je,t as Me}from"./url-params-n7kU_WZ-.js";import{i as Ne}from"./use-menu-BiJ8N7sS.js";import{n as Pe}from"./last-path-BbXWC3b3.js";import{t as Fe}from"./workspace-area-menu-Dg3hXKR3.js";import{t as Ie}from"./workspace-content-gate-Be4tLYiB.js";import{t as Le}from"./form-panel-C34lByEH.js";import{a as Re,i as ze,n as Be,o as Ve,r as He,s as Ue,t as We}from"./content-app-view-BFluU_u6.js";import{i as Ge,o as Ke,r as qe}from"./query-debug-YfWOzM6h.js";var w=`session.open`,Je=`session.set`,Ye=`session.ids`,Xe=`session.materialize`,Ze=`session.close`,T=`session.delta`,E=e(n(),1),D=t();function Qe({workspaceId:e,workspaceName:t}){let[n,r]=(0,E.useState)([]),[i,a]=(0,E.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,E.useEffect)(()=>{let t=!1,n=!1,i=!1,a=0,o=new Map,s=new Map,c=(e,t)=>{let n=e.filter(e=>e.address!==t.backend);if(!t.resyncing)return n;let r=e.find(e=>e.address===t.backend)||s.get(t.backend);return[...n,{address:t.backend,config:r?.config,resyncStartedAt:r?.resyncStartedAt||new Date().toISOString(),progress:t.progress??r?.progress}]},l=async()=>{if(n){i=!0;return}n=!0;let u=a;try{let n=await ce(e);if(!t){s=new Map(n.map(e=>[e.address,e]));let e=n.filter(e=>e.resyncing);for(let t of o.values())t.version>u&&(e=c(e,t.event));r(e)}}catch{}finally{n=!1,i&&!t&&(i=!1,l())}},u=t=>{t.workspaceId!==e||!t.backend||typeof t.resyncing!=`boolean`||(o.set(t.backend,{version:++a,event:t}),r(e=>c(e,t)))},d=t=>{t.workspaceId===e&&l()};l();let f=m.on(`connect`,l);return m.on(`backend.resync.changed`,u),m.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),m.off(`backend.resync.changed`,u),m.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,D.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,D.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,D.jsx)(l,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,D.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,D.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,D.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,D.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,D.jsx)(c,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,D.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,D.jsxs)(`div`,{children:[(0,D.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,D.jsx)(`span`,{className:`truncate`,children:i}),(0,D.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,D.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,D.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}var $e=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function et(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function tt(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>tt(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:et(e)}];let r=$e(e);if(!r)return[];let i=r.tree??r.treeId,a=typeof i==`string`?n.get(i)??null:null;return[].concat(r.paths??r.path??`/`).filter(e=>typeof e==`string`).map(e=>({tree:a,kind:t,path:et(e)}))}function O(e){let t=[],n=e=>{let n=Number(e);Number.isSafeInteger(n)&&n>0&&t.push(n)};return Array.isArray(e.ids)&&e.ids.forEach(n),Array.isArray(e.documentIds)&&e.documentIds.forEach(n),e.id!=null&&n(e.id),e.documentId!=null&&n(e.documentId),t}function nt(e){let t=new Map;for(let n of e)t.set(n.id,n.name),t.set(n.name,n.name);return t}function rt(e,t,n=new Map){let r=$e(t);if(!r)return{targets:[],ids:[],unknown:!0};if(e.startsWith(`tree.`)){let e=typeof r.treeName==`string`?r.treeName:null,t=r.treeType===`directory`||r.treeType===`context`?r.treeType:null,n=r.contextSpec??r.path;return typeof n==`string`?{targets:[{tree:e,kind:t,path:et(n)}],ids:O(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...tt(r.context,`context`,n),...tt(r.directory,`directory`,n)],a=$e(r.changed);a&&i.push(...tt(a.context,`context`,n),...tt(a.directory,`directory`,n));let o=O(r);if(i.length)return{targets:i,ids:o,unknown:!1};let s=r.reason===`content`||r.reason===`relations`;return e.startsWith(`document.updated`)&&s&&o.length?{targets:[],ids:o,unknown:!1}:{targets:[],ids:o,unknown:!0}}function k(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function it(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>et(e).split(`/`).filter(Boolean).map(e=>e.normalize(`NFKC`).trim().replace(/\s+/g,` `).replace(/[^\p{L}\p{N}\p{M} .+_@-]/gu,`_`).replace(/_+/g,`_`).toLowerCase()||`_`),r=new Set(n(e.path)),i=n(t.path);return r.size===0||i.length===0||i.some(e=>r.has(e))}return k(e.path,t.path)}function at(e){return rt(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function ot(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>it(e,t))))return!0;if(e.ids.length&&n){let t=n instanceof Set?n:new Set(n);if(e.ids.some(e=>t.has(e)))return!0}return!1}function st(e,t,n={}){return m.request(w,{workspace:e,specs:t,opts:n})}function ct(e,t,n){return m.request(Je,{sessionId:e,label:t,spec:n})}function lt(e){return m.request(Ye,{sessionId:e})}function A(e,t={}){return m.request(Xe,{sessionId:e,...t})}function ut(e){return m.request(Ze,{sessionId:e})}function dt(e){return m.on(T,e)}var ft=100;function pt({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,E.useState)([]),[o,s]=(0,E.useState)(0),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(null),f=(0,E.useRef)([]),p=(0,E.useRef)(new Map),h=(0,E.useRef)(null),g=(0,E.useRef)(null),_=(0,E.useRef)(null),ee=(0,E.useRef)({}),te=(0,E.useRef)(null),ne=(0,E.useMemo)(()=>JSON.stringify(t),[t]),re=(0,E.useMemo)(()=>JSON.stringify(n??{}),[n]),v=(0,E.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),ie=(0,E.useCallback)(async e=>{let t=g.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=ft){let i=e.slice(r,r+ft),a=await pe(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),y=(0,E.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),v(),r.length===0)return;let a=await ie(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}v()},[ie,v]),b=(0,E.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await y(a,[],t)},[y]);(0,E.useEffect)(()=>{if(g.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await st(e,JSON.parse(ne),JSON.parse(re));if(t){ut(r.sessionId).catch(()=>{});return}n=r.sessionId,h.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await b(r.ids,r.count)}catch(e){if(t)return;d(e instanceof Error?e.message:`Failed to open query session`),l(null),h.current=null}};i();let o=m.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??h.current;e&&ut(e).catch(()=>{}),h.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,ne,re,r]),(0,E.useEffect)(()=>{if(!c)return;let e=dt(e=>{if(e.sessionId===c){if(_.current!==null){te.current?.(_.current,ee.current);return}e.ids===void 0?y(e.added??[],e.removed??[],e.count):b(e.ids,e.count)}});return()=>{e?.()}},[c,y,b]);let ae=(0,E.useCallback)(async()=>{let e=h.current;if(e)try{let t=await lt(e);await b(t.ids,t.count)}catch{}},[b]),oe=(0,E.useCallback)(async(e,t)=>{let n=h.current;if(!n)throw Error(`No open query session`);let r=await ct(n,e,t);if(_.current!==null){await te.current?.(_.current,ee.current);return}await b(r.ids,r.count)},[b]),se=(0,E.useCallback)(async(e,t={})=>{let n=h.current;if(!n)throw Error(`No open query session`);if(_.current=e,ee.current=t,e===null){await ae();return}let r=await A(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),v()},[v,ae]);(0,E.useEffect)(()=>{te.current=se},[se]);let ce=(0,E.useCallback)(async(e,t,n={})=>{let r=h.current;if(!r)throw Error(`No open query session`);let i=await A(r,{match:t,limit:n.limit??100,...n.mode?{mode:n.mode}:{}});for(let e of i.documents)p.current.set(e.id,e);let a=await ct(r,e,{ids:i.ids});return await b(a.ids,a.count),i.ids},[b]);return{documents:i,count:o,ready:c!==null,error:u,setCue:oe,resync:ae,rank:se,rankAndPin:ce}}function mt({data:e,className:t}){let[n,r]=(0,E.useState)(!0),{rows:i,gapIndex:a,span:c}=(0,E.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,D.jsxs)(`div`,{className:u(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let l=a>0?i[a].distance:null;return(0,D.jsxs)(`div`,{className:u(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,D.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,D.jsx)(s,{className:`h-3.5 w-3.5`}):(0,D.jsx)(o,{className:`h-3.5 w-3.5`}),`Query debug`,(0,D.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,D.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,D.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,l===null?(0,D.jsxs)(D.Fragment,{children:[` `,(0,D.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,c.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,D.jsxs)(D.Fragment,{children:[` A jump at `,(0,D.jsx)(`span`,{className:`font-mono`,children:l.toFixed(4)}),` (Δ`,c.biggest.toFixed(4),`, vs typical Δ`,c.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,D.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,D.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,D.jsx)(`tbody`,{children:i.map((e,t)=>(0,D.jsxs)(`tr`,{className:u(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,D.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,D.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,D.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,D.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,D.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,c.first.toFixed(4),` – `,c.last.toFixed(4),` (spread `,(c.last-c.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}function ht(e,t){if(!e)return[];let n=t.split(`/`).filter(Boolean),r=e;for(let e of n)if(r=r?.children?.find(t=>t.name===e)??null,!r)return[];let i=n.length?`/${n.join(`/`)}`:``,a=(r.children??[]).filter(e=>e.type!==`canvas`).map(e=>({name:e.name,path:`${i}/${e.name}`,label:e.label,color:e.color,childCount:e.children?.length??0})).sort((e,t)=>(e.label||e.name).localeCompare(t.label||t.name,void 0,{numeric:!0,sensitivity:`base`}));return n.length>0&&a.unshift({name:`..`,path:n.length>1?`/${n.slice(0,-1).join(`/`)}`:`/`,isParent:!0}),a}var gt=new Map;function _t(e,t,n){return`${e}\0${t}\0${n}`}function vt(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${_t(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function j(e,t,n){let r=_t(e,t,n);for(let e of gt.keys())e.startsWith(r)&&gt.delete(e)}function yt(e,t){let n=`${e}\0`;for(let[e,r]of gt){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);ot(t,{tree:i,kind:S(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&gt.delete(e)}}function bt(e,t){yt(t?.workspaceName??e,at(t))}function xt(){let{workspaceName:e}=r();return e?(0,D.jsx)(Ie,{workspaceName:e,children:(0,D.jsx)(M,{})}):null}function M(){let{workspaceName:e,treeName:t}=r(),n=a(),o=i(),{showToast:s,showProgress:c}=h(),l=new URLSearchParams(n.search),Ie=(()=>{let e=l.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(l.get(`search`)||``).trim();return t?[t]:[]})(),[w,Je]=(0,E.useState)(null),[Ye,Xe]=(0,E.useState)(!0),[Ze,T]=(0,E.useState)([]),[$e,et]=(0,E.useState)(!1),[tt,O]=(0,E.useState)(0),k=qe(),[it,st]=(0,E.useState)(null),[ct,lt]=(0,E.useState)(k);ct!==k&&(lt(k),k||st(null));let[A,ut]=(0,E.useState)(`path`),[dt,ft]=(0,E.useState)(!1),[_t,xt]=(0,E.useState)(null),[M,St]=(0,E.useState)(null),[wt,Tt]=(0,E.useState)(``),[Et,Dt]=(0,E.useState)(!1),[Ot,kt]=(0,E.useState)(!1),[At,jt]=(0,E.useState)(!1),[N,Mt]=(0,E.useState)(null),[P,F]=(0,E.useState)(1),[I,Nt]=(0,E.useState)(50),[L,Pt]=(0,E.useState)(Ie),[Ft,It]=(0,E.useState)(null),{state:R,saveFilters:Lt,setSort:Rt,setAccentColor:zt,setMapDocuments:Bt}=Se(),Vt=R.filters.features.allOf,z=R.filters.features.anyOf,Ht=R.filters.features.noneOf,Ut=De(R.filters.timeline),Wt=Ee(R.filters.geo),Gt=ke(R.filters.lens,R.filters.geo.includeUnlocated),B=R.filters.lens.ids,Kt=[...Ut,...Wt,...Gt],qt=R.filters.sort??Oe,Jt=JSON.stringify({a:Vt,b:z,c:Ht,d:Kt,i:B,s:qt}),Yt=JSON.stringify({a:Vt,b:z,c:Ht,d:Kt,s:qt}),V=Ae(n.pathname).path,H=t??`context`,U=H===`backends`,[Xt,Zt]=(0,E.useState)([]);(0,E.useEffect)(()=>{!U||!e||ce(e).then(Zt).catch(()=>Zt([]))},[U,e]);let Qt=U?me(V,Xt):null,[$t,en]=(0,E.useState)(!1),tn=`${H}\0${V}`,[nn,rn]=(0,E.useState)(tn);nn!==tn&&(rn(tn),en(!1));let W=l.get(`layer`)===`1`,G=l.get(`layerId`)||null,[K,an]=(0,E.useState)(null),[q,on]=(0,E.useState)(null),sn=(0,E.useRef)(null);(0,E.useEffect)(()=>{sn.current=q},[q]);let[cn,ln]=(0,E.useState)(`left`),[un,dn]=(0,E.useState)([]),{openM1Drawer:fn,openM2Drawer:pn,goBack:mn}=Ne(),[hn,gn]=(0,E.useState)([]),J=(0,E.useMemo)(()=>{if(!K||V===`/`||W)return null;let e=V.split(`/`).filter(Boolean),t=K;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[K,V,W]),Y=J?.type===`canvas`?`canvas`:null,_n=(0,E.useRef)(null);(0,E.useEffect)(()=>{!e||!K||W||_n.current===`${e}/${H}`&&(V!==`/`&&!J||Pe(e,H,V))},[e,K,W,V,J,H]);let vn=(0,E.useMemo)(()=>W||A===`workspace`||L.length>0||S(H)!==`directory`?[]:ht(K,V),[K,V,H,W,A,L]),yn=W?null:V===`/`?K:J,X=be(),bn=`${H}\0${V}`,[xn,Sn]=(0,E.useState)(null),Cn=xn?.key===bn?xn.views:Ve(yn?.metadata),wn=X?.pinned&&X.view?[X.view,...Cn.filter(e=>e.id!==X.view.id)]:Cn,Tn=X?.pinned&&X.view?X.view.id:xn?.key===bn?xn.activeId:wn[0]?.id??ze.id,Z=wn.find(e=>e.id===Tn)??wn[0]??ze;(0,E.useEffect)(()=>{X?.selectView(Z)},[Z,X]);let En=U?void 0:X?.schema??Re(Z),Dn=En?[...Vt,En]:Vt,On=e=>{let t=wn.find(t=>t.id===e);t&&X?.selectView(t),F(1),dn([]),Sn({key:bn,views:wn,activeId:e})},kn=(t,n)=>{n&&n!==Tn&&(F(1),dn([]));let r=t.find(e=>e.id===(n??Tn));r&&X?.selectView(r),Sn({key:bn,views:t,activeId:n??Tn}),_(e,V,{metadata:{...yn?.metadata??{},views:t}},H).catch(()=>{s({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},An=Y===`canvas`&&typeof J?.querySpec?.query==`string`?J.querySpec.query:``,jn=Y===`canvas`?{label:J?.label,description:J?.description,color:J?.color}:null,{isPinned:Mn,pin:Nn,unpin:Pn,pins:Fn}=_e(),In=w?.name,Q=(0,E.useMemo)(()=>In&&Y===`canvas`&&!W?{workspaceName:In,treeName:H,path:V}:null,[In,Y,W,H,V]),Ln=Q?Mn(Q):!1,Rn=J?.id,zn=J?.label,Bn=(0,E.useCallback)(async()=>{if(Q)try{let e=Fn.find(e=>e.workspaceName===Q.workspaceName&&e.treeName===Q.treeName&&e.path===Q.path);e?await Pn(e.id):await Nn({...Q,layerId:Rn,label:zn})}catch(e){console.error(`Failed to update home pins:`,e)}},[Q,Fn,Nn,Pn,Rn,zn]),Vn=e?`${e}://${V===`/`?``:V.replace(/^\//,``)}`:``,Hn=Ce(w?.color)||null;(0,E.useEffect)(()=>(zt(Hn),()=>zt(null)),[Hn,zt]);let Un=(0,E.useCallback)(async t=>{let n=B;if(t?.anyOf?.length&&z.length&&(n=((await x(e,V,H,{limit:0,anyOf:z,ids:B,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await x(e,V,H,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...Vt,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:z,noneOf:Ht,filters:Kt,ids:n,queries:[...L,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,V,H,Jt,L]);(0,E.useEffect)(()=>{e&&(async()=>{Xe(!0);try{let t=await p.get(`${f.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,Je(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;s({title:`Error`,description:n,variant:`destructive`}),Je(null)}finally{Xe(!1)}})()},[e,s]),(0,E.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&Je(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let Wn=(B?.length??0)>0&&!W&&!($t&&Qt)&&L.length<=1,{documents:Gn,count:Kn,ready:qn,setCue:Jn,resync:Yn,rank:Xn}=pt({workspaceRef:e,specs:(0,E.useMemo)(()=>{let e={features:{allOf:Dn,anyOf:z,noneOf:Ht},filters:Kt};return A!==`workspace`&&(S(H)===`directory`?e.directory={tree:H,path:V}:e.context=V),[{label:`scope`,spec:e}]},[Yt,V,H,A,En]),opts:(0,E.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:Wn}),Zn=Wn&&qn,Qn=(0,E.useRef)(!1);(0,E.useEffect)(()=>{Qn.current=Zn},[Zn]);let $n=L.length===1?L[0].trim():``;(0,E.useEffect)(()=>{qn&&Xn($n?{text:$n}:null,{limit:I,offset:(P-1)*I}).catch(()=>{})},[qn,$n,I,P,Xn]);let er=(B??[]).join(`,`);(0,E.useEffect)(()=>{qn&&Jn(`lens`,{ids:B??[]}).catch(()=>{})},[qn,er,Jn,B]);let tr=Zn?Gn:Ze,nr=Zn?Kn:tt,rr=(0,E.useRef)(new Set);(0,E.useEffect)(()=>{rr.current=new Set(tr.map(e=>Number(e.id)))},[tr]);let ir=R.geoSelection;(0,E.useEffect)(()=>{Bt(tr,w?.name??null)},[tr,w?.name,Bt]),(0,E.useEffect)(()=>()=>Bt([]),[Bt]);let ar=(0,E.useMemo)(()=>ir?tr.filter(e=>we(e,ir,R.filters.geo.includeUnlocated)):tr,[tr,ir,R.filters.geo.includeUnlocated]),or=le(V,Dn,{treeName:H,treeType:S(H),scope:A,queries:L,anyOf:z,noneOf:Ht,filters:Kt,ids:B,layerId:W&&G?G:void 0}),sr=JSON.stringify([e,or]),[cr,lr]=(0,E.useState)(``),[ur,dr]=(0,E.useState)(!1),fr=(0,E.useRef)(!1),pr=$e||ur||cr!==sr||Zn||!!ir,mr=(0,E.useRef)(0),hr=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>{mr.current++,hr.current=null},[]);let gr=(0,E.useRef)(``),$=(0,E.useCallback)(async t=>{if(!e)return;if(Te(H,V)){mr.current++,hr.current=null,gr.current=``,T([]),O(0),et(!1);return}if(Qn.current)return;let n=`${$t&&Qt?`${A}:unfiled`:A}:${En??``}`,r=(B?.length??0)>0,i=vt(e,H,V,P,I,L.join(`␟`),Yt,W&&G?G:``,n),a=r&&i===gr.current;gr.current=i;let o=vt(e,H,V,P,I,L.join(`␟`),Jt,W&&G?G:``,n),c=`${o}\0${k}`;if(t?.silent&&hr.current?.key===c){hr.current.refreshPending=!0;return}let l=++mr.current,u=t?.silent||r||k?void 0:gt.get(o);u&&(T(u.documents),O(u.totalCount),lr(sr),et(!1)),(t?.silent??(a||!!u))||et(!0);let d={key:c,refreshPending:!1};hr.current=d;try{let t;t=$t&&Qt?await ge(e,Qt.driver,Qt.address,{linked:!1,limit:I,offset:(P-1)*I}):W&&G&&A!==`workspace`?await oe(e,H,G,{limit:I,page:P,queries:L,allOf:Dn,anyOf:z,noneOf:Ht,filters:Kt,ids:B,sortBy:qt.sortBy||void 0,order:qt.order}):await pe(e,V,Dn,{limit:I,page:P,treeName:H,treeType:H===`directory`||H===`backends`?`directory`:`context`,queries:L,anyOf:z,noneOf:Ht,filters:Kt,ids:B,sortBy:qt.sortBy||void 0,order:qt.order,scope:A,debug:k&&L.length>0,debugLimit:200});let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&gt.set(o,{documents:n,totalCount:i}),l!==mr.current)return;let s=t.debug,c=s?.imageDistances??s?.distances??null;st(c?{query:L[L.length-1]??``,distances:c}:null),T(a?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),O(i),lr(sr)}catch(e){if(l!==mr.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;s({title:`Error`,description:t,variant:`destructive`}),T([]),O(0)}finally{hr.current===d&&(hr.current=null),l===mr.current&&et(!1),l===mr.current&&d.refreshPending&&$({silent:!0})}},[e,V,H,G,W,P,I,w?.status,L,Jt,A,$t,k,En]);(0,E.useEffect)(()=>{$()},[$]),(0,E.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(on({treeName:n.treeName||`context`,path:je(n.path||`/`)}),ln(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,H,V]),(0,E.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&bt(e,n),ot(at(n),{tree:H,kind:S(H),path:V,wholeWorkspace:A===`workspace`}))){if(e&&j(e,H,V),Qn.current){Yn();return}$({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[$,e,V,H,A,Yn]);let _r=w?.name,vr=w?.id;(0,E.useEffect)(()=>{if(!e||!_r&&!vr)return;let t=[_r,vr].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>m.emit(`subscribe`,{channel:e}));n();let r=m.on(`connect`,n),i=new Map,a=!1,o=()=>{te(e).then(e=>{a||(i=nt(e))}).catch(()=>{})};o();let s=null,c=0,l=!1,u=null,d=()=>{if(s=null,c=Date.now(),u){let{treeName:t,path:n}=u;u=null,window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}if(l){if(l=!1,Qn.current){Yn();return}$({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=rt(t,n,i);yt(e,r);let a={tree:H,kind:S(H),path:V,wholeWorkspace:A===`workspace`},f=sn.current;f&&ot(r,{tree:f.treeName,kind:S(f.treeName),path:f.path})&&(u=f),ot(r,a,rr.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.inserted.batch`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>m.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>m.off(e,t))}},[e,vr,_r,H,V,A,$,Yn]);let yr=`${V}\0${H}\0${G??``}\0${A}`,[br,xr]=(0,E.useState)(yr);br!==yr&&(xr(yr),F(1),It(null));let Sr=`${V}\0${H}\0${G??``}`,[Cr,wr]=(0,E.useState)(Sr);Cr!==Sr&&(wr(Sr),ut(`path`));let Tr=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;Tt(n),St({parentPath:e,captureView:t})},Er=l.get(`createCanvas`)===`1`,[Dr,Or]=(0,E.useState)(!1);Dr!==Er&&(Or(Er),Er&&Tr(V,!1)),(0,E.useEffect)(()=>{if(!Er)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();o(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[Er,V]);let kr=(0,E.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let r=t.toString();o(`${n.pathname}${r?`?${r}`:``}${n.hash}`)},[n.pathname,n.search,n.hash,o]),Ar=JSON.stringify([l.has(`q`),...Ie]),[jr,Mr]=(0,E.useState)(Ar);jr!==Ar&&(Mr(Ar),Pt(Ie),F(1));let Nr=`${Ar}\0${Y??``}\0${An}\0${V}\0${Ft??``}`,[Pr,Fr]=(0,E.useState)(Nr);Pr!==Nr&&(Fr(Nr),l.has(`q`)||Ie.length>0||Y!==`canvas`||Ft===V||(Pt(An?[An]:[]),F(1)));let Ir=(0,E.useCallback)(e=>{let t=e.trim();t&&(It(null),Pt(e=>{if(e.includes(t))return e;let n=[...e,t];return kr(n),F(1),n}))},[kr,It,Pt,F]),Lr=(0,E.useCallback)(e=>{Pt(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&It(V),kr(n),F(1),n})},[kr,V,It,Pt,F]),Rr=L.join(` `).trim(),zr=!!R.activeContextType&&(R.isDirty||Rr!==(Y===`canvas`?An:R.savedSearchQuery||``));!e&&K!==null&&an(null),(0,E.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&fe(e,H),ee(e,H).then(i=>{!t&&a===n&&(r=!0,_n.current=`${e}/${H}`,an(i))}).catch(()=>{!t&&a===n&&!r&&an(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==H||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=C(e,vr);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,H,vr]),!(e&&Y===`canvas`&&!W)&&N!==null&&Mt(null),(0,E.useEffect)(()=>{let t=!1;if(!(!e||Y!==`canvas`||W))return ae(e,V,H).then(e=>{t||Mt(e)}).catch(()=>{t||Mt(null)}),()=>{t=!0}},[e,V,H,Y,W]);let Br=async()=>{if(w){ft(!0);try{let t=await ue(e||w.id);Je(t),s({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;s({title:`Error`,description:t,variant:`destructive`})}finally{ft(!1)}}},Vr=async t=>{if(!w)return;let n=c({title:`Removing…`,description:`Document from "${V}"`});try{await re(e||w.id,[t],V,[],H,Yr,{trashIfOrphaned:!0}),j(e||w.id,H,V),T(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document removed from workspace path.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Hr=async t=>{if(!w)return;let n=c({title:`Deleting…`,description:`Document from "${V}"`});try{await ie(e||w.id,[t],V,[],H,Yr),j(e||w.id,H,V),T(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Ur=async t=>{if(!w)return;let n=c({title:`Removing…`,description:`${t.length} document(s) from "${V}"`});try{await re(e||w.id,t,V,[],H,Yr,{trashIfOrphaned:!0}),j(e||w.id,H,V),T(e=>e.filter(e=>!t.includes(e.id))),O(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Wr=async t=>{if(!w)return;let n=c({title:`Deleting…`,description:`${t.length} document(s)`});try{await ie(e||w.id,t,V,[],H,Yr),j(e||w.id,H,V),T(e=>e.filter(e=>!t.includes(e.id))),O(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Gr=async t=>{if(!w)return;let n=c({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await ne(e||w.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}T(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},Kr=async t=>{if(!w)return;let n=c({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await ne(e||w.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);T(e=>e.filter(e=>!i.has(e.id))),O(e=>Math.max(0,e-i.size));let a=[r.successful?.length?`${r.successful.length} destroyed`:null,r.failed?.length?`${r.failed.length} failed`:null].filter(Boolean).join(`, `);r.failed?.length?n.fail({title:`Destroy incomplete`,description:a,variant:`destructive`}):n.done({title:`Destroyed`,description:a||`No documents destroyed`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},qr=e=>{xt({documentIds:e,operation:`copy`,sourcePath:V,sourceTreeName:H}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),s({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Jr=e=>{xt({documentIds:e,operation:`cut`,sourcePath:V,sourceTreeName:H}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),s({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Yr=S(H),Xr=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??H,a=r.targetTreeType??Yr,o=r.move??_t?.operation===`cut`,s=c({title:o?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let c=await b(e,t,n,i,a);if(c){j(e,i,t);let a=r.sourceTreeName||_t?.sourceTreeName,c=r.sourcePath||_t?.sourcePath;if((r.move??_t?.operation===`cut`)&&c&&a){let t=S(a);await re(e,n,c,[],a,t),j(e,a,c),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:c,treeName:a}}))}s.done({title:`Success`,description:`${n.length} document(s) ${o?`moved`:`pasted`} to "${t}"`}),xt(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await $(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else s.done();return c}catch(e){return s.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Zr=async(t,n)=>{if(!e)return!1;try{let r=(await de(e,n,t,H,Yr)).length>0;return r&&(xe(e,H,n),s({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return s({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},Qr=async()=>{if(!w||nr===0||pr||fr.current||window.prompt(`Type PURGE to permanently delete all ${nr} matching documents across all pages.`)!==`PURGE`)return;fr.current=!0,dr(!0);let t=c({title:`Purging…`,description:`${nr} matching document(s)`});try{let n=await y(e||w.id,or,nr);n.deleted===n.requested?t.done({title:`Success`,description:`${n.deleted} document(s) purged.`}):t.fail({title:`Purge incomplete`,description:`${n.deleted} of ${n.requested} document(s) purged. Refresh and review the remaining results before retrying.`})}catch(e){t.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}finally{j(e||w.id,H,V),await $({silent:!0}),fr.current=!1,dr(!1)}},$r=()=>Tr(V,!0),ei=async()=>{if(!(!e||!M||!wt.trim())){Dt(!0);try{let t=wt.trim(),n=M.parentPath,r=n===`/`?`/${t}`:`${n}/${t}`,i={...R.filters,features:{...R.filters.features,allOf:Dn}};await se(e,r,H,M.captureView?{metadata:{toolbox:i},querySpec:{features:i.features,filters:[...De(R.filters.timeline),...Ee(R.filters.geo)],query:Rr||void 0,sort:R.filters.sort?.sortBy?R.filters.sort:null}}:{}),St(null),fe(e,H);try{let t=await ee(e,H,{force:!0});an(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),o(Me(e,r,H))}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{Dt(!1)}}},ti=async()=>{if(!(!e||Y!==`canvas`)){kt(!0);try{let t=N||await he(e,V,H);Mt(t);let n=`${window.location.origin}${t.url}`;await navigator.clipboard?.writeText(n),s({title:`Public canvas link copied`,description:n})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to share canvas`,variant:`destructive`})}finally{kt(!1)}}},ni=async()=>{if(N){kt(!0);try{await v(N.code),Mt(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:H}})),s({title:`Canvas unshared`,description:`The public link no longer works.`})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to unshare canvas`,variant:`destructive`})}finally{kt(!1)}}},ri=async()=>{if(!e||Y!==`canvas`||V===`/`)return;let t=jn?.label||V.split(`/`).pop()||`canvas`,n=N?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){jt(!0);try{if(N)await v(N.code),Mt(null);else if(J?.locked){s({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await g(e,V,!1,H);let n=V.split(`/`).filter(Boolean);n.pop();let r=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:H}})),o(Me(e,r,H)),s({title:`Canvas deleted`,description:`"${t}" was removed.`})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to delete canvas`,variant:`destructive`})}finally{jt(!1)}}},ii=(0,E.useCallback)(async t=>{if(!e||!q)return;let n={treeName:H,path:V},r=cn===`left`?n:q,i=cn===`left`?q:n,a=cn===`left`?un:hn;if(a.length===0){s({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let o=S(i.treeName),l=c({title:t?`Moving…`:`Copying…`,description:`${a.length} document(s) → "${i.path}"`});try{if(!await b(e,i.path,a,i.treeName,o)){l.done();return}if(j(e,i.treeName,i.path),t){let t=S(r.treeName);await re(e,a,r.path,[],r.treeName,t),j(e,r.treeName,r.path)}[r,i].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),l.done({title:t?`Moved`:`Copied`,description:`${a.length} document(s) → "${i.path}"`})}catch(e){l.fail({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,q,cn,H,V,un,hn,s,c]);if((0,E.useEffect)(()=>{if(!q)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),ii(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[q,ii]),Ye)return(0,D.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,D.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,D.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,D.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!w)return(0,D.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let ai=Y===`canvas`&&!W&&!!J,oi=!ai&&!U&&yn?(0,D.jsx)(He,{views:wn,activeId:Tn,onSelect:On,onSave:kn,accentColor:Ce(w.color),onOpenToSide:e=>{on({treeName:H,path:V,viewId:e}),ln(`right`)}}):void 0,si=Qt||w.status!==`active`?(0,D.jsxs)(D.Fragment,{children:[Qt&&(0,D.jsx)(`button`,{type:`button`,onClick:()=>{en(!$t),F(1)},"aria-pressed":$t,className:u(`min-h-10 rounded-md border px-2 text-xs`,$t&&`bg-warning/15 text-warning`),children:`Unfiled only`}),w.status!==`active`&&(0,D.jsx)(`button`,{type:`button`,onClick:Br,disabled:dt,className:`min-h-10 rounded-md border px-2 text-xs`,children:dt?`Starting…`:`Start`})]}):void 0,ci=Te(H,V)?V===`/Trash`?(0,D.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,D.jsx)(Ge,{workspaceName:e||w.id})}):(0,D.jsx)(Ke,{workspace:e||w.id,path:V,onNavigate:t=>o(Me(e,t,`backends`))},e):(0,D.jsx)(Ue,{navigationTabs:oi,navigationActions:si,onBack:mn,accentColor:Ce(w.color),urlType:W?S(H)===`directory`?`${H}-layer`:`context-layer`:Y===`canvas`?`canvas`:S(H)===`directory`?H:`context`,urlDisplay:Vn,contextPath:V,treeName:H,workspaceId:e||w.id,workspaceLabel:w.label||w.name,workspaceIcon:w.icon,documentSchema:En,documents:ar,isLoading:$e,totalCount:nr,currentPage:P,pageSize:I,onPageChange:F,onPageSizeChange:e=>{Nt(e),F(1)},onRemoveDocument:V===`/`?void 0:Vr,onDeleteDocument:Hr,onDestroyDocument:Gr,onRemoveDocuments:V===`/`?void 0:Ur,onDeleteDocuments:Wr,onDestroyDocuments:Kr,onCopyDocuments:qr,onCutDocuments:Jr,onPasteDocuments:U?void 0:Xr,onImportDocuments:U?void 0:Zr,onSelectionChange:dn,onBrowseTree:()=>pn(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>fn(`workspaces`),onNavigatePath:t=>o(Me(e,t,H)),folders:vn,onOpenFolder:t=>o(Me(e,je(t),H)),scope:A,onScopeChange:ut,pastedDocumentIds:_t?.documentIds,linkTree:K,onPurgeDocuments:U?void 0:Qr,disablePurgeDocuments:pr,canvasInfo:jn??void 0,isCanvasPinned:Ln,onTogglePinCanvas:Q?Bn:void 0,onSaveAsCanvas:K&&Y!==`canvas`&&!W&&!U?$r:void 0,onShareCanvas:Y===`canvas`&&!W?ti:void 0,onUnshareCanvas:N?ni:void 0,onDeleteCanvas:Y===`canvas`&&!W?ri:void 0,isSharingCanvas:Ot,isDeletingCanvas:At,isCanvasShared:!!N,isCanvasLocked:!!J?.locked,backendSearchQueries:L,onBackendSearch:Ir,serverSort:R.filters.sort,onServerSortChange:Rt,onRemoveBackendQuery:Lr,canSaveChanges:zr,isSavingChanges:R.isSaving,onSaveChanges:Lt,contentBanner:k&&it?(0,D.jsx)(mt,{data:it,className:`mb-3`}):null,children:ai&&J?(0,D.jsx)(ve,{workspaceId:e||w.id,treeName:H,path:V,layerId:J.id,querySpec:J.querySpec,metadata:J.metadata,isLocked:!!J.locked,fetchDocuments:R.isDirty?Un:void 0}):!U&&Z.kind===`columns`?(0,D.jsx)(Be,{documents:ar,workspaceId:e||w.id,columns:Z.columns??[],onColumnsChange:e=>kn(wn.map(t=>t.id===Z.id?{...t,columns:e}:t))}):!U&&Z.kind===`app`&&Z.app&&Z.app!==`notes`?(0,D.jsx)(We,{app:Z.app,workspaceId:e||w.id,treeName:H,path:V}):null});return(0,D.jsxs)(Fe,{workspaceId:e||w.id,treeName:H,path:V,headerOnly:!0,className:`relative flex flex-col h-full min-h-0`,children:[(0,D.jsx)(Qe,{workspaceId:w.id,workspaceName:w.label||w.name},w.id),Te(H,V)&&(0,D.jsx)(ye,{workspace:w.label||w.name,workspaceIcon:w.icon,tree:H,path:V,onBack:mn,onBrowseTree:()=>pn(`workspaces`,`detail`,e||w.id),onBrowseWorkspaces:()=>fn(`workspaces`),onNavigatePath:t=>o(Me(e,t,H)),accentColor:Ce(w.color)}),M&&(0,D.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,D.jsx)(Le,{title:`New canvas`,onClose:()=>St(null),children:(0,D.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),ei()},className:`space-y-4`,children:[(0,D.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,D.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:wt,onChange:e=>Tt(e.target.value),onKeyDown:e=>{e.key===`Escape`&&St(null)},autoFocus:!0})]}),(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,D.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:M.parentPath===`/`?`/`:M.parentPath})]})]}),(0,D.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,D.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:M.captureView,onChange:e=>St({...M,captureView:e.target.checked})}),(0,D.jsxs)(`span`,{children:[`Capture the current view`,(0,D.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,D.jsxs)(`div`,{className:`flex gap-2`,children:[(0,D.jsx)(d,{type:`submit`,disabled:!wt.trim()||Et,children:Et?`Creating…`:`Create canvas`}),(0,D.jsx)(d,{type:`button`,variant:`outline`,onClick:()=>St(null),children:`Cancel`})]})]})})}),(0,D.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,D.jsx)(`div`,{"data-canvas-pane":!0,className:u(`flex-1 min-w-0 bg-background overflow-hidden`,q&&(cn===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||ln(`left`)},children:ci}),q&&e&&(0,D.jsx)(Ct,{workspaceName:e,workspaceLabel:w.label||w.name,workspaceIcon:w.icon,pane:q,isFocused:cn===`right`,clipboard:_t,setClipboard:xt,onFocus:()=>ln(`right`),onSelectionChange:gn,onNavigate:e=>on(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{on(null),ln(`left`),gn([])}})]})]})}function St(e,t){if(!e||t===`/`)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)return null;return n}function Ct({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:d}){let{openM1Drawer:f,openM2Drawer:p}=Ne(),{showToast:m,showProgress:g}=h(),[_,te]=(0,E.useState)(null),[v,y]=(0,E.useState)([]),[ae,oe]=(0,E.useState)(!1),[se,ce]=(0,E.useState)(0),[le,ue]=(0,E.useState)(1),[de,me]=(0,E.useState)(50),x=S(r.treeName),he=St(_,r.path),ge=he?.type===`canvas`,_e=(0,E.useMemo)(()=>x===`directory`?ht(_,r.path):[],[_,r.path,x]),ve=r.viewId?Ve(he?.metadata).find(e=>e.id===r.viewId)??null:null,ye=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,be=Re(ve),C=(0,E.useCallback)(async()=>{if(Te(r.treeName,r.path)){y([]),ce(0),oe(!1);return}let t=vt(e,r.treeName,r.path,le,de,``,be??``),n=gt.get(t);if(n){y(n.documents),ce(n.totalCount);return}oe(!0);try{let n=await pe(e,r.path,be?[be]:[],{limit:de,page:le,treeName:r.treeName,treeType:x}),i=n.payload||[],a=n.totalCount||n.count||0;y(i),ce(a),gt.set(t,{documents:i,totalCount:a})}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),y([]),ce(0)}finally{oe(!1)}},[e,r.path,r.treeName,x,de,le,m,be]);(0,E.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&fe(e,r.treeName),ee(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,te(e))}).catch(()=>{!t&&o===n&&!i&&te(null)})};a(!1);let o=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==r.treeName||a(!n?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{t=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,r.treeName]),(0,E.useEffect)(()=>{C()},[C]),(0,E.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(bt(e,n),ot(at(n),{tree:r.treeName,kind:S(r.treeName),path:r.path})&&(j(e,r.treeName,r.path),C()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[C,e,r.treeName,r.path]);let xe=(0,E.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??x,l=i.move??a?.operation===`cut`,u=g({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await b(e,t,n,s,c);if(r){j(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=S(c);await re(e,n,r,[],c,t),j(e,c,r),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:r,treeName:c}}))}u.done({title:`Success`,description:`${n.length} document(s) ${l?`moved`:`pasted`} to "${t}"`}),o(null),await C(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:s}}))}else u.done();return r}catch(e){return u.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,r.treeName,x,C,g,a,o]),Se=(0,E.useCallback)(()=>{j(e,r.treeName,r.path),C()},[e,r.treeName,r.path,C]),Ce=(0,E.useCallback)(async t=>{let n=g({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await re(e,t,r.path,[],r.treeName,x),Se(),n.done({title:`Removed`,description:`${t.length} document(s) removed from "${r.path}"`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,r.path,r.treeName,x,Se,g]),we=(0,E.useCallback)(async t=>{let n=g({title:`Deleting…`,description:`${t.length} document(s)`});try{await ie(e,t,r.path,[],r.treeName,x),Se(),n.done({title:`Deleted`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,r.path,r.treeName,x,Se,g]),Ee=(0,E.useCallback)(async t=>{let n=g({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await ne(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}Se();let i=`${r.successful?.length??0} document(s) destroyed${r.failed?.length?` · ${r.failed.length} failed`:``}.`;r.failed?.length?n.fail({title:`Destroy incomplete`,description:i,variant:`destructive`}):n.done({title:`Destroyed`,description:i})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,Se,g]);return(0,D.jsxs)(`div`,{className:u(`relative flex-1 min-w-0 rounded-(--sheet-radius) border bg-background overflow-hidden`,i?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||s()},children:[d&&(0,D.jsx)(`button`,{type:`button`,onClick:d,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),Te(r.treeName,r.path)?r.path===`/Trash`?(0,D.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,D.jsx)(Ge,{workspaceName:e})}):(0,D.jsx)(Ke,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,D.jsx)(Ue,{frameContent:!1,onBrowseWorkspaces:()=>f(`workspaces`),onBrowseTree:()=>p(`workspaces`,`detail`,e),urlType:ge?`canvas`:x===`directory`?r.treeName:`context`,urlDisplay:ye,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:be,documents:v,isLoading:ae,totalCount:se,currentPage:le,pageSize:de,onPageChange:ue,onPageSizeChange:e=>{me(e),ue(1)},onRemoveDocument:r.path===`/`?void 0:e=>Ce([e]),onRemoveDocuments:r.path===`/`?void 0:Ce,onDeleteDocument:e=>we([e]),onDeleteDocuments:we,onDestroyDocument:e=>Ee([e]),onDestroyDocuments:Ee,onCopyDocuments:e=>{o({documentIds:e,operation:`copy`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{o({documentIds:e,operation:`cut`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:r.treeName===`backends`?void 0:xe,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:_,folders:_e,onOpenFolder:l,onNavigatePath:l,canvasInfo:ge?{label:he?.label,description:he?.description,color:he?.color}:void 0,children:ve?.kind===`columns`?(0,D.jsx)(Be,{documents:v,workspaceId:e,columns:ve.columns??[],onColumnsChange:()=>{},readOnly:!0}):ve?.kind===`app`&&ve.app&&ve.app!==`notes`?(0,D.jsx)(We,{app:ve.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}export{xt as default};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/subtree-transfer-dialog-ChBI5llU.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BOIngd5F.js","assets/react-BHzhHVTZ.js","assets/ui-Byg1cZDr.js","assets/button-SgR3GVvV.js","assets/utils-BxVxyehK.js","assets/utils-2pl1SbIp.js","assets/input-BOtCd4HP.js","assets/api-CA6WiiYM.js","assets/alert-dialog-izlVMXfa.js"])))=>i.map(i=>d[i]);
2
- import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{l as n,u as r}from"./code-editor-BOIngd5F.js";import{vt as i,yt as a}from"./react-BHzhHVTZ.js";import{t as o}from"./preload-helper-Czpn1I53.js";import{g as s}from"./chunk-62JRHF6Z-vspAGgtK.js";import{$ as c,Br as l,Bt as u,Ct as d,Ft as f,Gn as p,Gr as m,Hn as h,It as g,Kr as _,L as v,Lt as y,Nt as b,Rn as x,Rr as S,Sr as C,Tt as ee,Ut as te,Vr as ne,W as w,X as T,Zn as E,Zt as D,_n as re,_r as ie,bn as ae,cr as oe,dr as se,fn as O,gn as ce,gr as le,hr as ue,in as de,ir as fe,kr as pe,oi as me,ot as he,pi as ge,pr as _e,qt as ve,rt as ye,sn as k,sr as be,st as xe,tt as A,ui as Se,vn as Ce,wr as we,xt as Te,yt as Ee,zn as De,zr as Oe,zt as ke}from"./ui-Byg1cZDr.js";import{t as j}from"./utils-2pl1SbIp.js";import{t as M}from"./button-SgR3GVvV.js";import{t as Ae}from"./socket-CtH3EU9m.js";import{n as je}from"./use-toast-BlLDqSUO.js";import{c as Me,d as Ne,f as Pe,h as Fe,l as Ie,p as Le,t as Re,u as ze}from"./LinkToCard-nR7Lal_o.js";import{$ as Be,$t as Ve,En as N,Fn as P,Ft as F,Ht as He,In as Ue,It as We,Jt as Ge,Kn as Ke,Lt as qe,On as Je,Ot as Ye,P as Xe,Pn as I,Vt as Ze,_ as Qe,bn as $e,bt as et,dt as tt,en as nt,gt as rt,h as L,ht as it,i as at,it as ot,jn as st,jt as ct,k as lt,kn as ut,l as dt,m as ft,mn as R,nt as z,o as B,pn as pt,s as mt,vn as ht,wn as gt,xn as _t,yn as vt,zt as yt}from"./workspace-DvxC7pw1.js";import{a as bt,b as xt,c as St,f as Ct,l as wt,o as Tt,s as V,t as Et,v as Dt}from"./ObjectPropertiesCard-ChvWbOpZ.js";import{i as Ot,n as kt,s as At}from"./document-open-mode-DoImW-xs.js";import{t as jt}from"./use-mobile-Db-vWu9Y.js";import{c as Mt,s as Nt}from"./IdentityFields-OPEWPlZs.js";import{i as Pt}from"./public-share-DXxVwHKT.js";import{o as Ft,s as It}from"./text-documents-BvDFBVnC.js";import{t as H}from"./useDocumentThumbnail-DYLCC63L.js";import{t as Lt}from"./markdown-view-BBBZtNSR.js";import{n as Rt}from"./tags-YamdPoBK.js";import{r as zt}from"./use-toolbox-Ck_cLGgf.js";import{C as Bt,S as Vt,T as Ht,g as Ut,h as Wt,m as Gt,t as Kt,u as qt,y as Jt}from"./context-mfIOB8dN.js";import{n as Yt}from"./relation-events-CKio19hE.js";import{n as Xt,t as Zt}from"./PickDocumentsCard-Bo224P4q.js";import{t as U}from"./useEscapeClose-DR_xKT_k.js";import{t as Qt}from"./useToastHelpers-CRrpIIdY.js";import{u as $t}from"./layer-style-Byl5LNFR.js";import{t as W}from"./DocumentIcon-x299QNu_.js";import{n as en,t as tn}from"./LinkToSidePanel-eCy3nW4R.js";import{C as nn,W as rn,c as an,d as on,i as sn,k as cn,s as ln,t as un,z as dn}from"./backend-sync-progress-H4Zch25P.js";import{t as fn}from"./workspace-access-C9nZlBBZ.js";import{t as pn}from"./search-COMZIxA7.js";import{a as G,c as mn,i as hn,n as gn,o as _n,r as vn,s as yn,t as bn}from"./use-sortable-data-BW_0sXBs.js";import{n as xn}from"./workspace-BydSRtST.js";var K=e(r(),1),Sn=(0,K.createContext)(null),Cn=()=>(0,K.useContext)(Sn),wn=`canvas:readerWidth`,q=320,Tn=1600;function En(){try{let e=Number(sessionStorage.getItem(wn));return Number.isFinite(e)&&e>=q&&e<=Tn?e:null}catch{return null}}var Dn=En(),On=new Set;function kn(e){return On.add(e),()=>{On.delete(e)}}function An(e){Dn=e===null?null:Math.round(Math.max(q,Math.min(Tn,e)));try{Dn===null?sessionStorage.removeItem(wn):sessionStorage.setItem(wn,String(Dn))}catch{}On.forEach(e=>e())}function jn(){return(0,K.useSyncExternalStore)(kn,()=>Dn,()=>null)}function Mn(e,t){let[n,r]=(0,K.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,K.useState)(a);a!==o&&(s(a),r(null));let c=(0,K.useRef)(a),l=(0,K.useRef)(0);(0,K.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,K.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}z(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}var J=n();function Nn(e){return e.schema===`data/schema/note`?A:e.schema===`data/schema/tab`?ce:e.schema===`data/schema/file`?fe:e.schema===`data/schema/message/email`?k:oe}function Pn({entry:e,onClose:t,frame:n}={}){let r=Tt(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=Mn(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,J.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,J.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between border-b-[3px] bg-muted pl-4 pr-2`,children:[(0,J.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,J.jsx)(`button`,{type:`button`,onClick:a,className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent`,"aria-label":`Close`,children:(0,J.jsx)(v,{className:`h-4 w-4`})})]}),(0,J.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,J.jsx)(`button`,{type:`button`,className:`ml-2 underline`,onClick:r.retry,children:`Retry`})]})]}):null;let{workspaceId:c}=i,l=t=>{s(t),t&&t.id!==i.document.id&&!e&&r.replace?.(t,c)};return(0,J.jsx)(Xt,{title:I(o).title,icon:Nn(o),onClose:r.alwaysOn?void 0:a,onSave:async e=>(await Ze(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:Ct(o)===Dt,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)(Et,{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,K.useRef)(null),r=e===`left`?-1:1;return(0,J.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":Fn,"aria-valuemax":In,"aria-valuenow":t??420,tabIndex:0,title:`Drag to resize; arrow keys adjust width; double-click to reset`,className:`absolute inset-y-0 ${e===`left`?`left-0`:`right-0`} z-20 hidden w-2 touch-none cursor-col-resize select-none hover:bg-primary/20 focus-visible:bg-primary/20 focus-visible:outline-none md:block`,onPointerDown:t=>{if(t.button!==0)return;t.preventDefault(),t.stopPropagation();let r=t.currentTarget.closest(`[data-reader-pane]`),i=e===`left`?(r.parentElement?.clientWidth??window.innerWidth)-248:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(Fn,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&An(Math.min(n.current.max,n.current.width+r*(e.clientX-n.current.x)))},onPointerUp:e=>{n.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{n.current=null},onLostPointerCapture:()=>{n.current=null},onDoubleClick:()=>An(null),onKeyDown:e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`&&e.key!==`Home`)return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.closest(`[data-reader-pane]`);e.key===`Home`?An(null):An(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function Rn(e){let t=Cn(),n=Ot(),r=jt(),i=Tt();return!e.enabled||!e.workspaceId||!n||r||t?.compact||i.location?e.children:(0,J.jsx)(zn,{...e,workspaceId:e.workspaceId},e.scope)}function zn({workspaceId:e,scope:t,documents:n,loading:r,children:i}){let a=jn(),o=`canvas:readerSelection:${t}`,[s,c]=(0,K.useState)(()=>{try{return Number(sessionStorage.getItem(o))||null}catch{return null}}),l=r?null:n.find(e=>e.id===s)??n[0]??null,u=(0,K.useCallback)((t,n)=>{if(n===e){c(t.id);try{sessionStorage.setItem(o,String(t.id))}catch{}}},[e,o]),d=(0,K.useMemo)(()=>({entry:l?{document:l,workspaceId:e}:null,alwaysOn:!0,open:u,preview:u,replace:u,close:()=>{}}),[l,e,u]);return(0,J.jsx)(bt.Provider,{value:d,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}),(0,J.jsxs)(`aside`,{"data-reader-pane":!0,"aria-label":`Document reading pane`,style:{width:a?`${a}px`:`50vw`,maxWidth:`calc(100% - 240px)`},className:`relative flex min-h-0 min-w-0 shrink-0 overflow-hidden border-l bg-card`,children:[(0,J.jsx)(Ln,{edge:`left`}),l?(0,J.jsx)(Pn,{},`${e}:${l.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,K.useState)(Hn);return(0,K.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 U(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,K.useState)(null),[a,o]=(0,K.useState)(``),[s,c]=(0,K.useState)(``);U(n),(0,K.useEffect)(()=>{let n=!1;return(async()=>{let r=await Be(e);if(!fn(r))throw Error(`Only workspace administrators can create rules.`);let a=await z(e,t.id);n||i(a)})().catch(e=>{n||o(e instanceof Error?e.message:`Could not load document`)}),()=>{n=!0}},[e,t.id]);let l=(0,K.useMemo)(()=>r?Gn(r):[],[r]),u=l.find(e=>e.id===s)||l[0],d=(0,K.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:I(t).title})]}),(0,J.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`rounded-md p-2 hover:bg-accent`,children:(0,J.jsx)(v,{className:`h-4 w-4`})})]}),a?(0,J.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}):r?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`mb-4 block space-y-2 text-sm font-medium`,children:[(0,J.jsx)(`span`,{children:`Start with`}),(0,J.jsx)(`select`,{className:`h-10 w-full rounded-md border bg-background px-3`,value:u?.id,onChange:e=>c(e.target.value),children:l.map(e=>(0,J.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,J.jsx)(on,{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,K.useRef)(null),o=(0,K.useRef)({selected:t,onSelectionChange:n});return(0,K.useLayoutEffect)(()=>{o.current={selected:t,onSelectionChange:n}},[t,n]),(0,K.useLayoutEffect)(()=>{if(a.current)return $n(a.current,{getSelection:()=>o.current.selected,onSelectionChange:e=>o.current.onSelectionChange(e)})},[e]),(0,J.jsx)(`div`,{ref:a,tabIndex:-1,"data-document-selection-area":``,onContextMenu:r,className:`relative isolate min-h-0 min-w-0 flex-1 overflow-auto p-2 outline-none`,children:i})}function tr(e){let t=2166136261;for(let e of localStorage.getItem(`authToken`)||``)t=Math.imul(t^e.charCodeAt(0),16777619);return`canvas:workspace-copy:${t>>>0}:${e}`}function nr({workspaceId:e,ids:t,onClose:n,modal:r=!1}){let{showProgress:i}=je();U(n,r);let[a]=(0,K.useState)(()=>{try{return tr(e)}catch{return``}}),[o,s]=(0,K.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,K.useState)(!1),[u,d]=(0,K.useState)(``),f=(0,K.useRef)(!1),p=(0,K.useRef)(!1);(0,K.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 ft(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`:tn,y=(0,J.jsx)(J.Fragment,{children:o?(0,J.jsxs)(`section`,{role:`dialog`,"aria-label":`Copy to workspace`,className:`${v} flex flex-col rounded-(--panel-radius) border bg-card p-4 shadow-elevation-4`,children:[(0,J.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,J.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[o.target.workspaceName,`: `,o.paths.join(`, `)]}),(0,J.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[o.index,` of `,o.ids.length,` copied`,_?`.`:c?`…`:` — paused.`]}),u&&(0,J.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:u}),(0,J.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:`Files go to workspace:data. Destination rules handle storage placement. Relationships and sharing permissions are not copied. Source documents stay unchanged.`}),!_&&(0,J.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Closing lets the current item finish and pauses the rest. Reopen Copy to workspace to resume, including after reconnecting.`}),(0,J.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!_&&!c&&(0,J.jsx)(M,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(a)}catch{}s(null),d(``)},children:`Discard remaining`}),!_&&!c&&(0,J.jsx)(M,{onClick:()=>void h(o),children:`Resume copy`}),(0,J.jsx)(M,{variant:_?`default`:`outline`,onClick:g,children:_?`Done`:c?`Pause & close`:`Close`})]})]}):(0,J.jsx)(Re,{title:`Copy to workspace…`,confirmLabel:`Copy documents`,excludeWorkspace:e,documentCount:t.length,sizeClassName:v,onClose:g,onConfirm:(e,n)=>h({ids:t,target:n,paths:e,index:0,id:crypto.randomUUID()})})});return r?(0,J.jsx)(qn,{label:`Copy to workspace`,onClose:g,children:y}):(0,J.jsx)(en,{onClose:g,children:y})}function rr(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...Rt(e.data?.tags??[]),...Rt(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,K.useState)([]),[a,o]=(0,K.useState)(null),[s,c]=(0,K.useState)(`keep`),[l,u]=(0,K.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,K.useState)(t),[m,h]=(0,K.useState)(!1),[g,_]=(0,K.useState)(``);return U(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)(Nt,{tags:r,onChange:i,suggestions:[]})]}),(0,J.jsx)(V,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,J.jsxs)(`div`,{className:`space-y-2`,children:[(0,J.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,J.jsxs)(`select`,{id:`bulk-comment-mode`,value:s,onChange:e=>c(e.target.value),className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm`,children:[(0,J.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,J.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,J.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,J.jsx)(`textarea`,{id:`bulk-comment`,rows:3,value:l,onChange:e=>u(e.target.value),placeholder:`Comment for all selected documents…`,className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`}),(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,J.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,J.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,J.jsx)(M,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,J.jsx)(M,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await z(e,n);await gt(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=kt(),n=(0,K.useContext)(bt),{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,K.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,K.useState)(!1),c=zt(),{document:l,refresh:u}=Mn(r,e);if(U(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,Kn.createPortal)((0,J.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:j(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,J.jsxs)(`div`,{className:j(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-(--panel-radius) md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-(--panel-radius)`),onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:I(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=P(l);return e?(0,J.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,J.jsx)(_e,{className:`h-4 w-4`})}):null})(),(0,J.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,J.jsx)(D,{className:`h-4 w-4`}):(0,J.jsx)(de,{className:`h-4 w-4`})}),(0,J.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,J.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,J.jsx)(Mt.Provider,{value:()=>s(e=>!e),children:(0,J.jsx)(Et,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var fr=xn,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,K.useState)([]);return(0,K.useEffect)(()=>{let t=!1;return ct(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,K.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:mr(e)})),[t])}function gr({workspaceId:e,value:t,onChange:n}){let r=hr(e);return(0,J.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,J.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value,order:[`alphabetical`,`type`].includes(e.target.value)?`asc`:t.order}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by`,"aria-label":`Sort by`,children:[t.sortBy!==`crud:deleted`&&!r.some(e=>e.value===t.sortBy)&&(0,J.jsx)(`option`,{value:t.sortBy,children:mr(t.sortBy)}),r.map(e=>(0,J.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending`:`Descending`,"aria-label":t.order===`asc`?`Ascending`:`Descending`,className:`flex h-7 w-7 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent hover:text-foreground touch-target`,children:t.order===`asc`?(0,J.jsx)(me,{className:`h-3.5 w-3.5`}):(0,J.jsx)(ge,{className:`h-3.5 w-3.5`})})]})}function _r(e,t){let n=t?.replace(/^t:/,``)||`crud:created`,r=(n===`crud:created`?[e.createdAt]:n===`crud:updated`?[e.updatedAt]:(e.timelines??[]).filter(e=>(e.timeline||e.name)===n).map(e=>e.start)).map(e=>Date.parse(e??``)).filter(Number.isFinite);if(r.length)return Math.min(...r);let i=n===`content`?Date.parse(e.createdAt??``):NaN;return Number.isFinite(i)?i:null}var Q={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},$=e=>e*1e6;function vr(){try{let e=new Intl.Locale(navigator.language),t=(typeof e.getWeekInfo==`function`?e.getWeekInfo():e.weekInfo)?.firstDay;if(typeof t==`number`&&t>=1&&t<=7)return t}catch{}return 1}function yr(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function br(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=yr(e);return r.setDate(r.getDate()-n),r}var xr=864e5;function Sr(e){let t=vr(),n=yr(e),r=br(e,t);return{today:n.getTime(),yesterday:n.getTime()-xr,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*xr,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function Cr(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:$(Q.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:$(Q.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:$(Q.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:$(Q.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:$(Q.lastWeek)};let n=new Date(e),r=n.getFullYear()*12+n.getMonth();if(r===t.month)return{key:`this-month`,label:`Earlier this month`,rank:$(Q.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:$(Q.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:$(Q.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:$(Q.year)+i}}function wr(e,t,n=`desc`,r=new Date){let i=Sr(r),a=new Map;for(let n of e){let e=Cr(t(n),i),r=a.get(e.key);r?r.items.push(n):a.set(e.key,{...e,items:[n]})}let o=[...a.values()].sort((e,t)=>n===`asc`?e.rank-t.rank:t.rank-e.rank),s=o.filter(e=>e.key===`unknown`);return s.length?[...o.filter(e=>e.key!==`unknown`),...s]:o}function Tr(){let{showProgress:e}=je();return(0,K.useCallback)(async(t,n,r,i)=>{let a=e({title:t,description:n});try{let e=await i();if(e===!1)throw Error(`The operation could not be completed.`);return a.done({title:r,description:n}),e}catch(e){throw a.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}},[e])}var Er=[`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.path.locked`,`tree.path.unlocked`,`tree.layer.updated`,`tree.layer.converted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`,`context.path.changed`,`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`],Dr=new Map;function Or(e,t,n){rt(e,t),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t,cacheInvalidated:!0}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}function kr(e,t){let n=Dr.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=Er.map(n=>{let a=(a={})=>{if(n===`backend.resync.changed`&&a.resyncing!==!1)return;let o=typeof a.workspaceId==`string`?a.workspaceId:null,s=typeof a.workspaceName==`string`?a.workspaceName:null;if(o&&!t.has(o)||!o&&s&&s!==e)return;let c=typeof a.treeName==`string`?a.treeName:void 0;n===`tree.renamed`?c=void 0:n===`context.path.changed`?c??=`context`:[`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`].includes(n)&&(c??=`backends`),r.add(c),!i&&(i=setTimeout(()=>{i=void 0;let t=r.has(void 0)?[void 0]:[...r];r.clear();for(let n of t)rt(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return Ae.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)rt(e,t);a.forEach(([e,t])=>Ae.off(e,t))}},Dr.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),Dr.delete(e))}}function Ar({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=Tr(),{showProgress:a}=je(),s=n||`context`,c=s===`directory`,[l,u]=(0,K.useState)([]);(0,K.useEffect)(()=>{let e=!1,n=()=>{t&&cn(t).then(t=>{e||u(t)}).catch(()=>{})};return n(),window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[t,s]);let d=(0,K.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,K.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),p=(0,K.useCallback)(async(n,r=!0)=>{let i;if(e)i=await qt(e,n,r);else if(t)i=await it(t,n,r,s);else return!1;let a=$t(n);if(i&&a)try{e?await Ht(e,n,a):t&&await N(t,n,a,s)}catch{}return f(),i},[e,t,s,f]),m=(0,K.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 Jt(e,n,r):t?await Ve(t,n,r,s,a,o):!1}finally{f()}}),[e,t,s,f,i]),h=(0,K.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await Ut(e,n,t.join(`/`),!1)}else if(t)i=await N(t,n,{name:r},s);else return!1;return f(),i},[e,t,s,f]),g=(0,K.useCallback)(async(n,r,a=!1,o=s,c=s,l={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await Ut(e,n,r,a,l);else if(t)i=await yt(t,n,r,a,o,c,l);else return!1;return f(),i}),[e,t,s,f,i]),_=(0,K.useCallback)(async n=>{let r;if(e)r=await Wt(e,n);else if(t)r=await We(t,n,s);else return null;return f(),r},[e,t,s,f]),v=(0,K.useCallback)(async n=>{let r;if(e)r=await Bt(e,n);else if(t)r=await pt(t,n,s);else return null;return f(),r},[e,t,s,f]),y=(0,K.useCallback)(async(n,r,a=!1,o=s,c=s)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await Kt(e,n,r,a);else if(t)i=await L(t,n,r,a,o,c);else return!1;return f(),i}),[e,t,s,f,i]),b=(0,K.useCallback)(async(n,r)=>e?await Ht(e,n,r):t?await N(t,n,r,s):!1,[e,t,s]),x=(0,K.useCallback)(async(n,r)=>{let i;if(e)i=await Gt(e,n,r);else if(t)i=await qe(t,n,r,s);else return null;return f(),i},[e,t,s,f]),S=(0,K.useCallback)(async(n,r)=>{let i;if(e)i=await Vt(e,n,r);else if(t)i=await R(t,n,r,s);else return null;return f(),i},[e,t,s,f]),C=(0,K.useCallback)(async e=>{if(!t)return!1;let n=await F(t,e,t,s);return f(300),n},[t,s,f]),ee=(0,K.useCallback)(async(e,n)=>{if(!t)return!1;try{await $e(t,e,n??t,s)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return f(300),!0},[t,s,f]),te=(0,K.useCallback)(async e=>{if(!t)return!1;let n=await lt(t,e,s);return f(),n},[t,s,f]),ne=(0,K.useCallback)(async e=>{if(!t)return!1;let n=await et(t).catch(()=>[]),r=d(e);for(let e of r){let r=B(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 un(a,t,r.driver,r.address,void 0,o?.name)}return f(300),r.length>0},[t,f,a,d]),w=(0,K.useCallback)(async(e,n)=>{if(!t)return!1;let r=await et(t).catch(()=>[]),i=mt(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await at(t,i.driver,i.address,[a]),f(200),!0},[t,f]),T=(0,K.useCallback)(async(e,n)=>{if(!t)return!1;let r=await et(t).catch(()=>[]),i=mt(e,r);return!i||!i.key?!1:(await nt(t,i.driver,i.address,i.key,n),f(200),!0)},[t,f]),E=(0,K.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await et(t),r=dt(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await Ge(t,r.driver,r.address,r.key),!0}finally{f(200)}}):!1,[t,f,i]),D=(0,K.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await o(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-ChBI5llU.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));r({mode:e,path:n,workspaceId:t,treeName:s,onImported:()=>{Or(t,s),f()}})},[t,s,f]),re=(0,K.useCallback)(async(e,n)=>{if(!t)return;let r=await o(()=>Promise.resolve().then(()=>Mr),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await tt(t,n,e,s,vt(s))).length!==e.length)throw Error(`Some documents could not be imported`);return Or(t,s),f(),!0});else{let e=[];for(let r=0;;){let i=await ot(t,n,[],{treeName:s,treeType:vt(s),limit:500,offset:r,order:`asc`}),a=i.payload||[];if(e.push(...a),r+=a.length,!a.length||r>=(i.totalCount??i.count??1/0))break}r.showDocumentExport(e)}},[t,s,f]);return{onImportDocuments:t&&s!==`backends`?e=>re(`import`,e):void 0,onExportDocuments:t?e=>re(`export`,e):void 0,onInsertPath:p,onRemovePath:m,onRenamePath:h,onMovePath:g,onCopyPath:y,onExportSubtree:t?e=>D(`export`,e):void 0,onImportSubtree:t&&s!==`backends`?e=>D(`import`,e):void 0,onUpdateNode:b,onMergeLayer:x,onSubtractLayer:S,onMergeDown:c?void 0:_,onSubtractDown:c?void 0:v,onLockLayer:t?C:void 0,onUnlockLayer:t?ee:void 0,onDestroyLayer:t&&!c?te:void 0,canResyncBackend:e=>d(e).length>0,onResyncBackend:t?ne:void 0,onCreateBackendFolder:t?w:void 0,onRenameBackendFolder:t?T:void 0,onDeleteBackendFolder:t?E:void 0}}function jr({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:c,pastedDocumentIds:l,onPasteDocuments:d}){let f=s(),p=Ar({workspaceId:n,treeName:r}),m=r===`backends`,h=m?mt(i):null,[_,v]=(0,K.useState)([]);(0,K.useEffect)(()=>{if(!m)return;let e=!1;return et(n).then(t=>{e||v(t)}).catch(()=>{}),()=>{e=!0}},[n,m]);let x=m?dt(i,_):null,S=i.split(`/`).filter(Boolean).pop()||i,[C,te]=(0,K.useState)(void 0);(0,K.useEffect)(()=>{let e=!1;return Ye(n).then(t=>{e||te(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||te(null)}),()=>{e=!0}},[n,r,i]);let ne=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},w=(e,t,n,r=!1)=>(0,J.jsxs)(`button`,{type:`button`,className:j(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>ne(n),children:[e,t]}),D=(0,J.jsx)(`div`,{className:`my-1 h-px bg-border`}),re=e=>{let t=m?(()=>{let t=rn(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:nn(i)};f(`/workspaces/${n}/settings/hooks?${dn(t).toString()}`)},ae=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},oe=an(r,i);return oe?(0,J.jsxs)(Fe,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[w((0,J.jsx)(T,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),oe.backend&&w((0,J.jsx)(ee,{className:`h-3 w-3`}),`Restore original paths`,()=>ln(n,i)),oe.backend&&w((0,J.jsx)(T,{className:`h-3 w-3`}),`Empty Trash`,()=>sn(n,i),!0)]}):(0,J.jsxs)(Fe,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[w((0,J.jsx)(E,{className:`w-3 h-3`}),`Open`,()=>o(i)),c&&w((0,J.jsx)(se,{className:`w-3 h-3`}),`Open to the side`,()=>c(i)),D,m?h&&(0,J.jsxs)(J.Fragment,{children:[w((0,J.jsx)(b,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=ae(`New folder name:`);e&&await p.onCreateBackendFolder?.(i,e)}),h.key&&w((0,J.jsx)(u,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=ae(`New folder name:`,S);e&&await p.onRenameBackendFolder?.(i,e)}),w((0,J.jsx)(De,{className:`w-3 h-3`}),`Create storage rule…`,()=>re(`store`))]}):(0,J.jsxs)(J.Fragment,{children:[w((0,J.jsx)(b,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=ae(`New folder name:`);e&&await p.onInsertPath(`${i===`/`?``:i}/${e}`)}),w((0,J.jsx)(u,{className:`w-3 h-3`}),`Rename`,async()=>{let e=ae(`New name:`,S);e&&await p.onRenamePath(i,e)}),w((0,J.jsx)(De,{className:`w-3 h-3`}),`Create rule…`,()=>re(`store`)),w((0,J.jsx)(ie,{className:`w-3 h-3`}),`Create download rule…`,()=>re(`download`))]}),C!==void 0&&w(C?(0,J.jsx)(y,{className:`w-3 h-3`}):(0,J.jsx)(g,{className:`w-3 h-3`}),C?`Unpin`:`Pin`,async()=>{C?await _t(n,C.id):await He(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),D,p.onImportDocuments&&w((0,J.jsx)(b,{className:`w-3 h-3`}),`Import documents…`,()=>p.onImportDocuments(i)),p.onExportDocuments&&w((0,J.jsx)(ie,{className:`w-3 h-3`}),`Export documents…`,()=>p.onExportDocuments(i)),w((0,J.jsx)(we,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!m&&d&&l&&l.length>0&&w((0,J.jsx)(pe,{className:`w-3 h-3`}),`Paste ${l.length} document(s)`,()=>d(i,l)),m?x&&(0,J.jsxs)(J.Fragment,{children:[D,w((0,J.jsx)(T,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${S}" and its contents from the backend?`)&&await p.onDeleteBackendFolder?.(i)},!0)]}):(0,J.jsxs)(J.Fragment,{children:[D,w((0,J.jsx)(T,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await p.onRemovePath(i,!0)},!0)]})]})}var Mr=t({DocumentList:()=>ii,default:()=>ii,showDocumentExport:()=>oi,showDocumentImport:()=>ai});function Nr({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,K.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map(lr),l=JSON.stringify(c,null,2),u=async()=>{try{await navigator.clipboard.writeText(l),a(`copied`),setTimeout(()=>a(`idle`),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e),a(`error`),setTimeout(()=>a(`idle`),2e3)}};return(0,J.jsx)(qn,{label:`Export Documents`,onClose:o,children:(0,J.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,J.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,J.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,J.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,J.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,J.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,J.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,J.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,J.jsxs)(M,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,J.jsx)(we,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,J.jsx)(`textarea`,{className:`w-full min-h-24 flex-1 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&u()}},onFocus:e=>e.target.select()})]})}),(0,J.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-end gap-2`,children:[(0,J.jsx)(M,{variant:`outline`,onClick:()=>{let e=URL.createObjectURL(new Blob([l],{type:`application/json`})),t=window.document.createElement(`a`);t.href=e,t.download=`canvas-documents.json`,t.click(),setTimeout(()=>URL.revokeObjectURL(e),1e3)},children:`Download JSON`}),(0,J.jsx)(M,{onClick:o,children:`Close`})]})]})})}function Pr({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,K.useState)(``),[a,o]=(0,K.useState)(!1),[s,c]=(0,K.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e||typeof e!=`object`||!e.schema||!e.data){c(`Each document must have "schema" and "data" fields`);return}o(!0),await n(a)?(i(``),t()):c(`Failed to import documents`)}catch(e){c(e instanceof Error?e.message:`Import failed`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,Kn.createPortal)((0,J.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,J.jsx)(`div`,{className:`bg-background border rounded-(--panel-radius) max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,J.jsxs)(`div`,{className:`p-6`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,J.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data or choose a document export file`})]}),(0,J.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,J.jsxs)(`div`,{className:`space-y-4`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,J.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),className:`w-full h-64 p-3 border rounded-lg font-mono text-sm`,placeholder:`[{"schema": "data/schema/tab", "schemaVersion": "2.0", "data": {...}, "metadata": {...}}]`,disabled:a,autoFocus:!0})]}),s&&(0,J.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,J.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,J.jsxs)(`p`,{children:[(0,J.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,J.jsxs)(`p`,{children:[(0,J.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,J.jsxs)(`label`,{className:`mt-4 block text-sm`,children:[`Import JSON file`,(0,J.jsx)(`input`,{type:`file`,accept:`.json,application/json`,disabled:a,className:`mt-2 block w-full text-sm`,onChange:e=>{let t=e.target.files?.[0];t&&t.text().then(e=>{i(e),c(null)}).catch(e=>c(String(e)))}})]}),(0,J.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,J.jsx)(M,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,J.jsx)(M,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function Fr({document:e}){let{replicating:t,label:n}=Je(e);return t?(0,J.jsxs)(`span`,{role:`status`,className:`inline-flex shrink-0 items-center gap-1 rounded-full border bg-muted/60 px-2 py-0.5 text-[11px] font-normal text-muted-foreground`,children:[(0,J.jsx)(O,{className:`h-3 w-3 animate-spin`}),n]}):null}function Ir(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Ie(e.currentTarget,`inside`)}function Lr({documentId:e,onOpenActions:t,className:n}){return t?(0,J.jsx)(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),t(n.currentTarget,e)},className:`rounded-sm p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground ${n??``}`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,J.jsx)(le,{className:`h-4 w-4`})}):null}function Rr(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function zr({document:e}){let t=P(e);return t?(0,J.jsx)(`a`,{href:t,target:`_blank`,rel:`noopener noreferrer`,title:`Open original in browser`,"aria-label":`Open original in browser`,className:`shrink-0 rounded p-1 text-muted-foreground hover:text-foreground`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:(0,J.jsx)(_e,{className:`h-3.5 w-3.5`})}):null}function Br({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Tt(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=Un(),[u,d]=(0,K.useState)(!1),{replicating:f}=Je(e),p=I(e),m=Hr(e),h=m||Wr(e),{blobUrl:g}=H(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)(mn,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>Rr(n,()=>d(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:text-accent-foreground cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring transition-opacity ${f?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:b,onMouseDown:x,...l,onContextMenu:S,draggable:!0,onDragStart:_,children:[(0,J.jsx)(G,{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)(G,{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)(W,{document:e,chip:!0})}),(0,J.jsx)(G,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,J.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),(0,J.jsx)(zr,{document:e}),(0,J.jsx)(Fr,{document:e})]}),p.subtitle&&(0,J.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,J.jsx)(G,{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)(G,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,J.jsx)(G,{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)(G,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,J.jsx)(G,{className:`w-12 text-right`,children:(0,J.jsx)(Lr,{documentId:e.id,onOpenActions:a})})]}),(0,J.jsx)(ur,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function Vr({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Tt(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=Un(),[u,d]=(0,K.useState)(!1),p=e.schema===`data/schema/tab`,{replicating:h}=Je(e),g=I(e),_=Hr(e),v=Ur(e),y=_||Wr(e)||v,{blobUrl:b,loading:S}=H(n??``,e.id,512,{enabled:y,blobFallback:_,version:e.checksumArray?.[0]??null}),C=t=>{o?.(t,e.id)},ee=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),te=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),ne=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||d(!0)},w=e=>{e.shiftKey&&e.preventDefault()},T=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>Rr(n,()=>d(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:border-primary border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${h?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${p&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:ne,onMouseDown:w,...l,onContextMenu:T,draggable:!0,onDragStart:C,children:(0,J.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[y&&(0,J.jsxs)(`div`,{className:`relative h-32 w-40 max-w-[40%] sm:h-40 sm:w-56 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:[b?(0,J.jsx)(`img`,{src:b,alt:g.title,loading:`lazy`,className:`h-full w-full object-cover`}):v&&n&&!S?(0,J.jsx)(Gr,{workspaceId:n,documentId:e.id,fallback:(0,J.jsx)(W,{document:e})}):S?(0,J.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,J.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,J.jsx)(W,{document:e})}),v&&(0,J.jsx)(f,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`})]}),(0,J.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,J.jsx)(W,{document:e,chip:!0}),(0,J.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:g.title,children:g.title}),(0,J.jsx)(zr,{document:e}),(0,J.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:g.schemaLabel}),(0,J.jsx)(Fr,{document:e})]}),g.subtitle&&(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:g.subtitle,children:g.subtitle}),g.preview&&(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:g.preview}),(0,J.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,J.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),te&&(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(x,{className:`h-3 w-3`}),(0,J.jsx)(`span`,{className:`font-mono`,title:`${te.algo} checksum`,children:te.hash})]}),(0,J.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,J.jsx)(m,{className:`h-3 w-3`}),(0,J.jsx)(`span`,{title:`Created: ${ee(e.createdAt)}`,children:ee(e.createdAt)})]})]})]}),(0,J.jsx)(Lr,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,J.jsx)(ur,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function Hr(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Ur(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function Wr(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Gr({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=It(e,t),[a,o]=(0,K.useState)(!1);return i||a?(0,J.jsx)(J.Fragment,{children:n}):r?(0,J.jsxs)(`div`,{className:`relative h-full w-full`,children:[(0,J.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-full w-full object-cover`}),(0,J.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,J.jsx)(f,{className:`h-3.5 w-3.5`})})]}):(0,J.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function Kr({document:e,workspaceId:t,markdown:n}){let r=(0,K.useRef)(null),[i,a]=(0,K.useState)(()=>typeof IntersectionObserver>`u`);(0,K.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}=Ft(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)(Lt,{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)(W,{document:e,size:10,chip:!0}),i&&s&&(0,J.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function qr({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let[c,l]=(0,K.useState)(null),u=e.metadata?.dimensions,d=c??(u?.width&&u?.height?Math.max(.2,Math.min(5,u.width/u.height)):1),p=Tt(),m=p.alwaysOn&&p.entry?.workspaceId===n&&p.entry?.document.id===e.id,h=Un(),[g,_]=(0,K.useState)(!1),v=Hr(e),y=Ur(e),b=v||Wr(e)||y,x=I(e),S=Ke(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||Ue(e)),C=e.schema===`data/schema/file`&&(S===`markdown`||S===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,ee=!b&&e.schema!==`data/schema/file`&&!!(x.preview||x.subtitle),{replicating:ne}=Je(e),{blobUrl:w,loading:T}=H(n??``,e.id,768,{enabled:b,blobFallback:v,version:e.checksumArray?.[0]??null}),E=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&r(e.id,!i||!t,i),i||_(!0)},D=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,style:{flexGrow:d,flexBasis:`${d*220}px`,"--tile-ratio":d},"data-reading":m||void 0,"aria-selected":!!t,onKeyDown:n=>Rr(n,()=>_(!0),()=>r?.(e.id,!t,!0)),className:`document-tile data-[reading=true]:bg-accent data-[reading=true]:border-primary group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-(--card-radius) border transition cursor-pointer outline-none hover:shadow-elevation-2 focus-visible:ring-2 focus-visible:ring-ring ${ne?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:E,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...h,onContextMenu:D,draggable:!0,onDragStart:t=>s?.(t,e.id),title:x.title,children:[(0,J.jsx)(`input`,{type:`checkbox`,className:`absolute left-2 top-2 z-10 h-4 w-4 cursor-pointer accent-primary ${t?``:`reveal-on-hover`}`,checked:t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}}),(0,J.jsxs)(`div`,{className:`document-tile-media relative w-full bg-muted/40 ${b&&w||ee||C&&n||y&&n?``:`aspect-square`}`,children:[b&&T&&(0,J.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),b&&w?(0,J.jsx)(`img`,{src:w,alt:x.title,loading:`lazy`,className:`block h-auto w-full`,onLoad:e=>{let t=e.currentTarget;t.naturalHeight&&l(t.naturalWidth/t.naturalHeight)}}):y&&n&&!T?(0,J.jsx)(Gr,{workspaceId:n,documentId:e.id,fallback:(0,J.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,J.jsx)(W,{document:e,size:10,chip:!0})})}):C&&n?(0,J.jsx)(Kr,{document:e,workspaceId:n,markdown:S===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):ee?(0,J.jsxs)(`div`,{className:`flex min-h-28 w-full flex-col gap-1.5 overflow-hidden bg-card p-3 pt-7 text-left`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,J.jsx)(W,{document:e}),(0,J.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:x.schemaLabel}),(0,J.jsx)(zr,{document:e})]}),(0,J.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:x.title}),x.subtitle&&(0,J.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:x.subtitle}),(0,J.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:x.preview})]}):(0,J.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,J.jsx)(W,{document:e,size:10,chip:!0})}),y&&w&&(0,J.jsx)(f,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`}),(0,J.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,J.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Open to the side`,children:(0,J.jsx)(te,{className:`h-3.5 w-3.5`})}),o&&(0,J.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(t.currentTarget,e.id)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,J.jsx)(le,{className:`h-3.5 w-3.5`})})]})]}),!ee&&(0,J.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,J.jsx)(`span`,{className:`truncate text-xs font-medium`,title:x.title,children:x.title}),(0,J.jsx)(zr,{document:e})]})]}),(0,J.jsx)(ur,{document:e,isOpen:g,onClose:()=>_(!1),workspaceId:n})]})}function Jr(e,t,n,r,i){let[a,o]=(0,K.useState)(!1),s=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:a,onDragOver:e=>{!t||!s(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,a||o(!0))},onDragLeave:()=>o(!1),onDrop:async a=>{if(o(!1),!t||!s(a))return;a.preventDefault(),a.stopPropagation();let c=null;try{c=JSON.parse(a.dataTransfer.getData(`application/json`))}catch{c=null}if(!(c?.type!==`document`||!Array.isArray(c.documentIds)||c.documentIds.length===0)&&!sr(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function Yr(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function Xr({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,J.jsx)(C,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,J.jsx)(p,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var Zr=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function Qr({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Jr(e,r,i,a,o);return(0,J.jsxs)(`button`,{type:`button`,title:Zr(e),onClick:()=>t?.(e.path),onContextMenu:t=>Yr(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 max-w-full items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm transition-colors hover:bg-accent ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,J.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,J.jsx)(Xr,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,J.jsx)(C,{className:`hidden h-4 w-4 group-hover:block`}):(0,J.jsx)(E,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,J.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,J.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function $r({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Jr(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,J.jsxs)(`button`,{type:`button`,title:Zr(e),onClick:()=>t?.(e.path),onContextMenu:t=>Yr(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-(--card-radius) border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,J.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,J.jsx)(C,{className:`h-10 w-10`,strokeWidth:1.5}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(p,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,J.jsx)(E,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c})]})}),(0,J.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,J.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function ei({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,J.jsx)(`div`,{className:`mb-4 grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,J.jsx)($r,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function ti({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,J.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,J.jsx)(Qr,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function ni({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Jr(e,r,i,a,o);return(0,J.jsxs)(mn,{"data-selection-ignore":``,className:`cursor-pointer ${s.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:t=>Yr(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:Zr(e),children:[(0,J.jsx)(G,{className:`w-10`}),(0,J.jsx)(G,{className:`w-12`,children:(0,J.jsx)(Xr,{folder:e})}),(0,J.jsx)(G,{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)(G,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,J.jsx)(G,{className:`hidden lg:table-cell`}),(0,J.jsx)(G,{className:`hidden lg:table-cell`}),(0,J.jsx)(G,{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)(G,{className:`w-12 md:w-auto`})]})}function ri({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,J.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-1 mb-2 flex items-center gap-2 bg-background/95 px-1 py-1.5 backdrop-blur-sm`,children:[(0,J.jsx)(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 cursor-pointer accent-primary ${r||i?``:`reveal-on-hover`}`,checked:r,ref:e=>{e&&(e.indeterminate=i&&!r)},onChange:e=>o(e.target.checked),title:`Select everything in "${e}"`,onClick:e=>e.stopPropagation()}),(0,J.jsxs)(`button`,{type:`button`,onClick:a,"aria-expanded":!n,className:`flex min-w-0 items-center gap-1.5 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,J.jsx)(l,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,J.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,J.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,J.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function ii({readingPane:e=!1,externalSearchQuery:t,toolbarActions:n,documents:r,isLoading:i,contextPath:a,treeName:o,workspaceId:s,totalCount:u,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:g,onDeleteDocuments:y,onDestroyDocuments:x,onCopyDocuments:C,onCutDocuments:ee,onPasteDocuments:E,onImportDocuments:D,onSelectionChange:oe,pastedDocumentIds:O,viewMode:le=`card`,allowViewToggle:de=!1,activeContextUrl:me,currentContextUrl:ge,currentPage:k=1,pageSize:A=50,onPageChange:j,onPageSizeChange:Ae,onPurgeDocuments:Fe,disablePurgeDocuments:Be=!1,backendSearchQueries:Ve=[],onBackendSearch:N,onRemoveBackendQuery:P,serverSort:F,onServerSortChange:He,scope:We=`path`,onScopeChange:Ge,canSaveChanges:Ke=!1,isSavingChanges:qe=!1,onSaveChanges:Je,linkTree:Ye,folders:Ze,onOpenFolder:$e}){let et=Cn(),tt=At(),[nt,rt]=(0,K.useState)(()=>{if(!de)return le;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return le}),L=de?et?.documentLayout??nt:le,it=(0,K.useCallback)(e=>{et?.selectDocumentLayout(e),rt(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[et]),[at,ot]=(0,K.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),ct=(0,K.useCallback)(()=>{ot(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[lt,dt]=(0,K.useState)(new Set),ft=(0,K.useCallback)(e=>{dt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[R,z]=(0,K.useState)(new Set),[B,pt]=(0,K.useState)(null),[mt,gt]=(0,K.useState)(null),_t=zt(),vt=!!(_t&&s),yt=(0,K.useCallback)((e,t=!1)=>{if(!_t||!s)return;let n=e.map(e=>r.find(t=>t.id===e)).filter(e=>!!e);n.length!==0&&_t.openAddRelated({workspaceName:s,documents:n},t)},[_t,s,r]),[bt,Ct]=(0,K.useState)(!1),[V,Et]=(0,K.useState)(null),[Dt,Ot]=(0,K.useState)(!1),[kt,jt]=(0,K.useState)(null),[Mt,Nt]=(0,K.useState)(!1),Ft=(0,K.useRef)(!1),It=(0,K.useRef)(!1),H=o===`backends`&&We===`path`?rn(a):null;(0,K.useEffect)(()=>()=>{Ft.current=!0},[]);let[Lt,Rt]=(0,K.useState)(!1),[Bt,Vt]=(0,K.useState)(null),[Ht,Ut]=(0,K.useState)(!1),[Wt,Gt]=(0,K.useState)(null),Kt=Pt()==null&&!!s,[qt,Jt]=(0,K.useState)(null),[Xt,U]=(0,K.useState)(null),$t=!!(Ye&&E),en=!!s,{showSuccessToast:tn,showErrorToast:nn}=Qt(),{showProgress:an}=je(),on=Tt(),sn=s?e=>on.open(e,s):void 0,cn=We===`workspace`,ln=cn?void 0:f,un=cn?void 0:g,[dn,fn]=(0,K.useState)(!1),[G,xn]=(0,K.useState)(!1),[Sn,wn]=(0,K.useState)(``),q=t??Sn,Tn=t!==void 0,[En,Dn]=(0,K.useState)(!1),On=Ve.length>0,kn=(0,K.useRef)(null),An=(0,K.useCallback)(()=>{wn(``),kn.current&&(kn.current.value=``)},[]);(0,K.useEffect)(()=>{if(!de||window.matchMedia(`(max-width: 767px)`).matches)return;let e=kn.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[de]);let jn=JSON.stringify([s,o,a]),[Mn,Nn]=(0,K.useState)(jn);jn!==Mn&&(Nn(jn),z(new Set),Et(null),gt(null),pt(null)),(0,K.useEffect)(()=>{oe?.(Array.from(R))},[R,oe]);let Pn=(0,K.useCallback)(()=>{if(!N)return;let e=q.trim();e&&(N(e),An())},[N,q,An]),Fn=(0,K.useCallback)(()=>{An(),P&&Ve.length>0&&P(-1)},[P,Ve.length,An]),In=(0,K.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:We===`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,We]),Ln=(0,K.useCallback)(async e=>{if(!E)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let n=null;try{n=JSON.parse(t)}catch{return}n?.type!==`document`||!Array.isArray(n.documentIds)||n.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),Dn(!1),!sr(n,s,o,a)&&(await E(a,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),z(new Set)))},[a,o,s,E]),zn=(0,K.useCallback)(e=>{E&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,Dn(!0))},[E]),Hn=(0,K.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||Dn(!1)},[]),Un=(0,K.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,K.useMemo)(()=>r.length===0?null:new pn(r,Un),[r,Un]),X=(0,K.useDeferredValue)(q),Z=(0,K.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,K.useMemo)(()=>{if(!Ze||Ze.length===0||X.trim())return[];let e=F?.order===`desc`?-1:1;return[...Ze].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)},[Ze,X,F?.order]),Yn=Gn.length>0,[Xn,Zn]=(0,K.useState)(null),Qn=(0,K.useMemo)(()=>s&&o&&$e?(e,t)=>Zn({x:t.clientX,y:t.clientY,path:e}):void 0,[s,o,$e]),$n={folders:Gn,onOpen:$e,onMenu:Qn,onPasteDocuments:E,contextPath:a,treeName:o,workspaceId:s},tr=(0,K.useMemo)(()=>({title:e=>I(e).title?.toLowerCase()??``,schema:e=>I(e).schemaLabel??``,type:ut,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[]),{sorted:rr,sort:ir,toggleSort:or}=bn(Z,tr),cr=(0,K.useCallback)(e=>_r(e,F?.sortBy),[F?.sortBy]),lr=(0,K.useMemo)(()=>wr(Z,cr,F?.order===`asc`?`asc`:`desc`),[Z,cr,F?.order]),dr=at&&!st(F?.sortBy)&&lr.length>1,fr=(0,K.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,K.useMemo)(()=>(L===`table`?rr:dr?lr.filter(e=>!lt.has(e.key)).flatMap(e=>e.items):Z).map(e=>e.id),[L,rr,dr,lr,lt,Z]),mr=(0,K.useRef)(null),hr=JSON.stringify([s,a,o,k]),Q=(0,K.useCallback)(e=>{mr.current=null,z(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),$=(0,K.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,K.useCallback)((e,t)=>{let n;R.has(e)?n=Array.from(R):(n=[e],z(new Set([e]))),pt({anchor:t,ids:n})},[R]),yr=(0,K.useCallback)((e,t)=>{vr(t,Ie(e))},[vr]),br=(0,K.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),vr(t,Ir(e)))},[vr]),xr=(0,K.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){Ct(!0);try{for(let n of t)await Qe(s,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;tn(`Created ${n} relation${n===1?``:`s`}`),Yt(),gt(null)}catch(e){nn(e instanceof Error?e.message:`Failed to create relations`)}finally{Ct(!1)}}},[s,tn,nn]),Sr=(0,K.useCallback)(async(e,t,n)=>{if(E){for(let r of e)await E(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});z(new Set)}},[E]),Cr=(0,K.useCallback)(async(e,t,n)=>{if(!s||!V||It.current)return;It.current=!0,Ft.current=!1,Nt(!1),Ot(!0);let i=an({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${V.ids.length} document(s) · ${e.join(`, `)}`});try{let a=r=>ht(s,r,{to:e,mode:t,keepDocument:n.keepDocument,...t===`delete`&&H?{deleteFrom:{backend:H.backend,folder:H.rel}}:{},folder:n.folder,filename:n.filename,onConflict:n.onConflict}),o=t===`delete`?await Bn(V.ids,a,{shouldStop:()=>Ft.current,onProgress:(t,n)=>{jt({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}. ${wt(o.failed,new Map(r.map(e=>[e.id,I(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];Et(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{It.current=!1,Ot(!1),jt(null)}},[s,V,H,r,an]),Tr=(0,K.useCallback)(()=>{R.size===Z.length?z(new Set):z(new Set(Z.map(e=>e.id)))},[R.size,Z]),Er=(0,K.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=[],u=e=>{e&&l.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;u({id:`view`,group:`open`,label:`View details`,icon:se,run:()=>U({document:i})}),u(Kt&&{id:`edit`,group:`open`,label:`Edit`,icon:ke,run:()=>U({document:i,edit:!0})}),u(Kt&&i.schema===`data/schema/file`&&{id:`rename`,group:`open`,label:`Rename…`,icon:ke,run:()=>U({document:i,edit:!0})});let t=i.data?.url||i.data?.uri;u(Kt&&s&&i.schema!==`data/schema/file`&&typeof t==`string`&&/^https?:\/\//i.test(t)&&{id:`download-link`,group:`open`,label:`Download to workspace`,icon:ie,run:async()=>{let e=an({title:`Downloading file…`});try{await Xe(s,i.id),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),e.done({title:`File saved to workspace`})}catch(t){e.fail({title:`Download failed`,description:t instanceof Error?t.message:String(t),variant:`destructive`})}}}),u(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:_e,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),u(sn&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:te,run:()=>sn(i)})}return u(C&&{id:`copy`,group:`clipboard`,label:`Copy${n}`,icon:we,shortcut:`Mod+C`,run:()=>C(e)}),u(ee&&{id:`cut`,group:`clipboard`,label:`Cut${n}`,icon:Te,shortcut:`Mod+X`,run:()=>ee(e)}),u(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:ce,run:()=>Er(String(i.id))}),u(i&&Kt&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:xe,run:()=>Jt(i)}),u($t&&{id:`link-to`,group:`organize`,label:`Link to…${n}`,icon:re,run:()=>gt(e)}),u(vt&&{id:`add-related`,group:`organize`,label:`Add related document…${n}`,icon:b,run:t=>yt(e,t?.shiftKey)}),u(Kt&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${n}`,icon:ke,run:()=>Gt(e)}),u(Kt&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:we,run:t=>{Ut(!!t?.shiftKey),Vt(e)}}),u({id:`export`,group:`organize`,label:`Export…${n}`,icon:ie,run:()=>fn(!0)}),u(o!==`backends`&&(ln||un)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${n}`,icon:ve,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&ln?ln(e[0]):un?.(e),a()}}),u(o!==`backends`&&(p||y)&&{id:`delete`,group:`remove`,label:`Delete from index${n}`,icon:T,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&p?p(e[0]):y?.(e),a()}}),c&&en?(u({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${n}`,icon:De,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Et({ids:e,mode:`copy`})}),u({id:`backend-move`,group:`backends`,label:`Move to backend…${n}`,icon:Se,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Et({ids:e,mode:`move`})}),u({id:`backend-delete`,group:`backends`,label:`Delete from backend…${n}`,icon:T,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Et({ids:e,mode:`delete`})})):c&&(m||x)&&u({id:`destroy`,group:`backends`,label:`Delete from backend(s)${n}`,icon:T,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&m?m(e[0]):x?.(e),a()}}),l},Or=()=>{let e=[],t=t=>{t&&e.push(t)},n=O??[];return t(E&&n.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${n.length})`,icon:pe,shortcut:`Mod+V`,run:async()=>{try{await E(a,n)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(Z.length>0&&{id:`select-all`,group:`select`,label:q?`Select all matches (${Z.length})`:`Select all on this page`,icon:he,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:ye,run:()=>z(new Set)}),t(E&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:be,hint:`Browse and add existing documents to this folder`,run:()=>Rt(!0)}),t(D&&{id:`import`,group:`add`,label:`Import…`,icon:w,run:()=>xn(!0)}),t(r.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:ie,run:()=>{z(new Set),fn(!0)}}),t(Fe&&u>0&&{id:`purge`,group:`purge`,label:`Purge all (${u})`,icon:T,destructive:!0,disabled:Be||!!q,hint:q?`Purge is disabled while local search is active`:Be?`Purge requires loaded server results with no browser-only or live selection`:`Delete all documents matching the current server-side filters across all pages`,run:Fe}),e},kr=!!(He&&F&&s),Ar=B?B.ids?Dr(B.ids):Or():[],Mr=B?.ids?.length===1?r.find(e=>e.id===B.ids[0]):void 0,Fr=Mr?(0,J.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,J.jsx)(W,{document:Mr,chip:!0}),(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsx)(`div`,{className:`truncate text-base font-semibold`,children:I(Mr).title}),(0,J.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Mr.id,` · `,Mr.schema]})]})]}):(0,J.jsx)(`div`,{className:`truncate text-base font-semibold`,children:B?.ids?`${B.ids.length} documents`:`This folder`}),Lr=e=>{pt({anchor:Ie(e.currentTarget),ids:R.size>0?Array.from(R):null})},Rr=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),z(new Set),pt({anchor:Ir(e),ids:null}))},zr=e=>{if(e.defaultPrevented||Le(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Pe(e)){e.preventDefault(),t?vr(Number(t.dataset.documentId),Ie(t,`inside`)):pt({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()])},Hr=(0,K.useCallback)(async e=>{if(!D)return!1;try{return await D(e,a)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[D,a]),Ur=e=>dr?lr.map(t=>{let n=lt.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)(ri,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>ft(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:zr,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${En?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:zn,onDragLeave:Hn,onDrop:Ln,children:[(0,J.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,J.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,J.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,J.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,J.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:q?`${Z.length} of ${r.length}`:`${u.toLocaleString()} document${u===1?``:`s`}`})]}),(0,J.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,J.jsxs)(`p`,{hidden:Tn,className:`min-w-0 truncate`,children:[`Context: `,(0,J.jsx)(`span`,{className:`font-mono`,children:a}),me&&ge&&me!==ge&&(0,J.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,J.jsxs)(`p`,{className:`shrink-0`,children:[R.size>0&&(0,J.jsxs)(`span`,{className:`text-info`,children:[R.size,` selected`]}),R.size>0&&(q||u>A)&&(0,J.jsx)(`span`,{className:`mx-1`,children:`·`}),q?`on this page`:u>A?`Showing ${Math.min((k-1)*A+1,u)}–${Math.min(k*A,u)}`:null]})]})]}),!Tn&&(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:[!Tn&&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 ${We===`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 ${We===`workspace`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List every document in the workspace (staging excluded)`,children:[(0,J.jsx)(h,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!Tn&&(0,J.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,J.jsx)(Ee,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,J.jsx)(`input`,{ref:kn,type:`text`,placeholder:N?On?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,title:`Search text or an exact document ID, e.g. @id:101140. Press Enter to search the server.`,defaultValue:``,onChange:e=>wn(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`&&N&&(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`}),N&&s&&(0,J.jsx)(xt,{workspaceId:s,inputRef:kn,onChange:wn}),(q||On)&&(0,J.jsx)(`button`,{onClick:Fn,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,J.jsx)(v,{className:`h-4 w-4`})})]}),!Tn&&N&&q.trim()&&!Ve.includes(q.trim())&&(0,J.jsxs)(M,{size:`sm`,variant:`default`,onClick:Pn,className:`shrink-0`,title:On?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,J.jsx)(Ee,{className:`h-3.5 w-3.5 mr-1`}),On?`Refine`:`Search server`]})]}),!Tn&&On&&(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,J.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),Ve.map((e,t)=>(0,J.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,J.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,J.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,J.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),P&&(0,J.jsx)(`button`,{onClick:()=>P(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,J.jsx)(v,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),P&&Ve.length>1&&(0,J.jsx)(`button`,{onClick:()=>P(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,J.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,J.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,J.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,J.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[de&&(0,J.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,ae,`Tile view`],[`card`,Ce,`Card view`]].map(([e,t,n])=>(0,J.jsx)(`button`,{type:`button`,onClick:()=>it(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))}),de&&L!==`table`&&!st(F?.sortBy)&&(0,J.jsx)(`button`,{type:`button`,onClick:ct,title:at?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":at,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${at?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,J.jsx)(_,{className:`h-4 w-4`})})]}),j&&u>0&&(0,J.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,J.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,J.jsxs)(`select`,{value:A,onChange:e=>Ae?.(Number(e.target.value)),className:`h-control-sm rounded-(--input-radius) border-(length:--input-border-width) border-input bg-background px-2 text-sm focus-ring`,"aria-label":`Documents per page`,children:[(0,J.jsx)(`option`,{value:25,children:`25`}),(0,J.jsx)(`option`,{value:50,children:`50`}),(0,J.jsx)(`option`,{value:100,children:`100`}),(0,J.jsx)(`option`,{value:200,children:`200`})]}),(0,J.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,J.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[kr&&(0,J.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,J.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,J.jsx)(gr,{workspaceId:s,value:F,onChange:He})]}),(0,J.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(r.length>0||D||E)&&(0,J.jsxs)(`div`,{className:`contents`,children:[(0,J.jsxs)(M,{variant:`outline`,size:`sm`,onClick:Lr,"aria-haspopup":`menu`,"aria-label":R.size>0?`Actions (${R.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${Ne(`Shift+F10`)} or right-click)`,children:[(0,J.jsx)(ue,{className:`h-4 w-4`}),(0,J.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,R.size>0?` (${R.size} selected)`:``]})]}),R.size>0&&(0,J.jsxs)(M,{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)(v,{className:`h-3.5 w-3.5`}),(0,J.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),O&&O.length>0&&E&&(0,J.jsxs)(M,{variant:`outline`,size:`sm`,onClick:()=>E(a,O),className:`flex items-center gap-1.5`,title:`Paste into this folder (${Ne(`Mod+V`)})`,children:[(0,J.jsx)(pe,{className:`h-4 w-4`}),`Paste (`,O.length,`)`]})]}),Ke&&Je&&(0,J.jsx)(M,{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)(d,{className:`h-3.5 w-3.5`})}),n]})]})]})}),j&&u>A&&(0,J.jsxs)(`div`,{className:`document-pagination mt-3 flex min-w-0 flex-wrap items-center justify-end gap-2 border-t pt-3 max-sm:gap-0.5`,children:[(0,J.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((k-1)*A+1,u),` - `,Math.min(k*A,u),` of `,u]}),(0,J.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>j(1),disabled:k===1,className:`p-1 touch-target`,children:(0,J.jsx)(Oe,{className:`h-4 w-4`})}),(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>j(k-1),disabled:k===1,className:`p-1 touch-target`,children:(0,J.jsx)(ne,{className:`h-4 w-4`})}),(0,J.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,J.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),k,(0,J.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,J.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(u/A)]}),(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>j(k+1),disabled:k>=Math.ceil(u/A),className:`p-1 touch-target`,children:(0,J.jsx)(l,{className:`h-4 w-4`})}),(0,J.jsx)(M,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>j(Math.ceil(u/A)),disabled:k>=Math.ceil(u/A),className:`p-1 touch-target`,children:(0,J.jsx)(S,{className:`h-4 w-4`})})]})]})]}),(0,J.jsx)(er,{scope:JSON.stringify([hr,L,pr]),selected:R,onSelectionChange:Q,onContextMenu:Rr,children:Z.length===0&&!Yn?(0,J.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,J.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,J.jsx)(fe,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:q?`No documents match your search`:`No documents found in this context`}),(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:q?(0,J.jsxs)(J.Fragment,{children:[`Search: `,(0,J.jsxs)(`span`,{className:`font-mono`,children:[`"`,q,`"`]})]}):(0,J.jsxs)(J.Fragment,{children:[`Path: `,(0,J.jsx)(`span`,{className:`font-mono`,children:a})]})}),!Tn&&q&&(0,J.jsx)(`button`,{onClick:An,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!q&&O&&O.length>0&&(0,J.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,Ne(`Mod+V`),` to paste `,O.length,` document(s)`]})]})}):L===`tile`?(0,J.jsxs)(`div`,{children:[(0,J.jsx)(ei,{...$n}),Z.length===0&&(0,J.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Ur(e=>(0,J.jsx)(`div`,{className:`document-tiles pr-2`,"data-tile-style":tt,children:e.map(e=>(0,J.jsx)(qr,{document:e,isSelected:R.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:sn,onRightClick:br,onOpenActions:yr,onDragStart:In},e.id))}))]}):L===`table`?(0,J.jsx)(`div`,{children:(0,J.jsxs)(vn,{children:[(0,J.jsx)(yn,{children:(0,J.jsxs)(mn,{children:[(0,J.jsx)(_n,{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)(gn,{label:(0,J.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:ir,onSort:or,className:`w-12`}),(0,J.jsx)(gn,{label:`Title`,sortKey:`title`,sort:ir,onSort:or,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,J.jsx)(gn,{label:`Schema`,sortKey:`schema`,sort:ir,onSort:or,className:`hidden md:table-cell`}),(0,J.jsx)(gn,{label:`ID`,sortKey:`id`,sort:ir,onSort:or,className:`hidden lg:table-cell`}),(0,J.jsx)(_n,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,J.jsx)(gn,{label:`Created`,sortKey:`created`,sort:ir,onSort:or,className:`hidden sm:table-cell`}),(0,J.jsx)(_n,{className:`w-12 md:w-auto`,children:(0,J.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,J.jsxs)(hn,{children:[Gn.map(e=>(0,J.jsx)(ni,{folder:e,onOpen:$e,onMenu:Qn,onPasteDocuments:E,contextPath:a,treeName:o,workspaceId:s},e.path)),rr.map(e=>(0,J.jsx)(Br,{document:e,isSelected:R.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:sn,onRightClick:br,onOpenActions:yr,onDragStart:In},e.id))]})]})}):(0,J.jsxs)(`div`,{children:[(0,J.jsx)(ti,{...$n}),Z.length===0&&(0,J.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Ur(e=>(0,J.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,J.jsx)(`div`,{children:(0,J.jsx)(Vr,{document:e,isSelected:R.has(e.id),workspaceId:s,onSelect:$,onOpenToSide:sn,onRightClick:br,onOpenActions:yr,onDragStart:In})},e.id))}))]})}),B&&(0,J.jsx)(Me,{anchor:B.anchor,items:Ar,onClose:()=>pt(null),label:B.ids?`Document actions`:`Folder actions`,header:Fr}),(0,J.jsx)(Nr,{isOpen:dn,onClose:()=>fn(!1),documents:r,selectedDocuments:R}),(0,J.jsx)(Pr,{isOpen:G,onClose:()=>xn(!1),onImport:Hr}),Bt&&s&&(0,J.jsx)(nr,{modal:Ht,workspaceId:s,ids:Bt,onClose:()=>Vt(null)}),mt&&Ye&&(0,J.jsx)(qn,{label:`Link to`,onClose:()=>gt(null),children:(0,J.jsx)(Re,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:mt.length,fixedWorkspaceName:s,tabs:[`context`,`directory`,`relations`],saving:bt,relationExcludeIds:new Set(mt),onConfirm:(e,t)=>Sr(e,mt,t),onConfirmRelation:e=>xr(e,mt),onClose:()=>gt(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)(St,{workspaceId:s,documentCount:V.ids.length,initialMode:V.mode,defaultFilename:V.ids.length===1?Ue(r.find(e=>e.id===V.ids[0])??{}):``,saving:Dt,progress:kt,stopping:Mt,onStop:()=>{Ft.current=!0,Nt(!0)},deleteFrom:H?{backend:H.backend,folder:H.rel}:void 0,onConfirm:Cr,onClose:()=>{Dt||Et(null)}})}),window.document.body),Lt&&E&&(0,Kn.createPortal)((0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>Rt(!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)(Zt,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:s,onConfirm:async e=>{await E(a,e),Rt(!1)},onClose:()=>Rt(!1)})})]}),window.document.body),qt&&s&&(0,J.jsx)(Jn,{workspaceId:s,document:qt,onClose:()=>Jt(null)},`${s}:${qt.id}`),Wt&&s&&(0,J.jsx)(ar,{workspaceId:s,documentIds:Wt,onClose:()=>Gt(null)}),(0,J.jsx)(ur,{document:Xt?.document??null,isOpen:!!Xt,onClose:()=>U(null),workspaceId:s,initialEdit:Xt?.edit}),Xn&&s&&o&&$e&&(0,J.jsx)(jr,{x:Xn.x,y:Xn.y,workspaceName:s,treeName:o,path:Xn.path,onClose:()=>Zn(null),onOpen:$e,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:s,treeName:o,path:e}})),pastedDocumentIds:O,onPasteDocuments:E?(e,t)=>E(e,t):void 0})]})})}function ai(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,cr.createRoot)(t);n.render((0,J.jsx)(Pr,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function oi(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,cr.createRoot)(t);n.render((0,J.jsx)(Nr,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{gr as a,sr as c,Un as d,Ln as f,Cn as h,kr as i,ar as l,jn as m,Ar as n,fr as o,Pn as p,Or as r,ur as s,ii as t,qn as u};