@augmentd-labs/canvas-web 2.26.8 → 2.26.9
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.
|
@@ -15,5 +15,5 @@ Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})
|
|
|
15
15
|
</head><body>${t}</body></html>`;return{url:URL.createObjectURL(new Blob([i],{type:`text/html;charset=utf-8`})),remoteCount:r}}finally{cr.removeHook(`afterSanitizeAttributes`)}}function Ld(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function Rd(e){return(0,Y.jsx)(zd,{...e},`${e.workspaceId}:${e.document.id}`)}function zd({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=zn(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],{body:s,bodyHtml:c,loading:l,error:u}=Md(e,t),[d,f]=(0,q.useState)(null),[p,m]=(0,q.useState)(!1),[h,g]=(0,q.useState)(!1),[_,v]=(0,q.useState)(0),[y,b]=(0,q.useState)(null);(0,q.useEffect)(()=>{if(!c||p)return;let e=!1,n=[],i=o.filter(e=>e.contentId&&e.url);return Promise.all(i.slice(0,20).map(async e=>{try{let{blob:n}=await r(t.id,{url:e.url}),i=await Ld(n);return[String(e.contentId).replace(/^<|>$/g,``),i]}catch{return null}})).then(t=>{if(e)return;let r=new Map(t.filter(Boolean)),{url:i,remoteCount:a}=Id(c,r,h);n.push(i),f(i),v(a)}).catch(t=>{e||b(String(t instanceof Error?t.message:t))}),()=>{e=!0,n.forEach(e=>URL.revokeObjectURL(e)),f(null)}},[e,t.id,c,p,h]);let x=typeof a.date==`string`?new Date(a.date).toLocaleString():null,S=o.filter(e=>!e.isInline||!e.contentId),C=async e=>{if(e.url)try{await i(t.id,e.filename||`attachment`,{url:e.url})}catch(e){b(e instanceof Error?e.message:String(e))}};return(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 min-w-0 flex-col gap-3 ${n}`,children:[(0,Y.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-2 text-sm sm:p-3`,children:(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2 sm:gap-3`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 basis-64 space-y-1`,children:[(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,Y.jsxs)(`details`,{className:`sm:hidden`,children:[(0,Y.jsxs)(`summary`,{className:`cursor-pointer text-xs`,children:[(0,Y.jsx)(`span`,{className:`inline-block max-w-[85%] truncate align-bottom`,children:typeof a.from==`object`&&a.from?a.from.name||a.from.address:String(a.from||`Unknown sender`)}),(0,Y.jsx)(`span`,{className:`ml-2 text-muted-foreground`,children:`Details`})]}),(0,Y.jsxs)(`div`,{className:`mt-2 space-y-1 break-words text-xs`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Nd(a.from)]}),Pd(a.to)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Pd(a.to)]}),Pd(a.cc)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Pd(a.cc)]}),x&&(0,Y.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:x})]})]}),(0,Y.jsxs)(`div`,{className:`hidden space-y-1 break-words sm:block`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Nd(a.from)]}),Pd(a.to)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Pd(a.to)]}),Pd(a.cc)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Pd(a.cc)]}),x&&(0,Y.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:x})]})]}),c&&(0,Y.jsxs)(`div`,{className:`flex max-w-full flex-wrap gap-2`,children:[(0,Y.jsxs)(W,{size:`sm`,variant:`outline`,onClick:()=>m(!p),children:[p?(0,Y.jsx)(ae,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Y.jsx)(Le,{className:`mr-1.5 h-3.5 w-3.5`}),p?`HTML`:`Plain text`]}),!p&&_>0&&(0,Y.jsxs)(W,{size:`sm`,variant:h?`secondary`:`outline`,onClick:()=>g(!h),title:`Remote images can reveal your IP/read status to the sender`,children:[h?(0,Y.jsx)(Re,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Y.jsx)(Be,{className:`mr-1.5 h-3.5 w-3.5`}),h?`Hide remote images`:`Show remote images (${_})`]})]})]})}),(y||u)&&(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:y||u}),l?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading message…`}):u?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:String(a.bodyPreview||`Message content could not be loaded.`)}):!p&&c?d?(0,Y.jsx)(`iframe`,{src:d,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,Y.jsx)(`pre`,{className:`min-h-[12rem] flex-1 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-sm`,children:s||`(empty body)`}),S.length>0&&(0,Y.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,Y.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,S.length,`)`]}),S.map((e,t)=>(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(Le,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,Y.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:Fd(e.size)})]}),e.url&&(0,Y.jsxs)(`button`,{onClick:()=>C(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Y.jsx)(Me,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}function Bd({attachment:e,workspaceId:t,document:n}){let{download:r}=zn(t),i=e.mimeType||e.contentType||``,a=e.name||e.filename||`Attachment`,o=i.startsWith(`audio/`)||i.startsWith(`video/`),{blobUrl:s,error:c,loading:l}=Rn(t,n.id,{url:e.url,typeHint:i,enabled:!o&&!!e.url}),{src:u,error:d,loading:f}=Un(t,n.id,{url:e.url,enabled:o&&!!e.url}),[p,m]=(0,q.useState)(!1),[h,g]=(0,q.useState)(``),_=o?d:c;return(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border p-2`,children:[_&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:_}),(o?f:l)&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading attachment…`}),!o&&s&&i.startsWith(`image/`)&&(0,Y.jsx)(`img`,{src:s,alt:a,className:`max-h-96 max-w-full rounded object-contain`}),o&&u&&(i.startsWith(`video/`)?(0,Y.jsx)(`video`,{controls:!0,playsInline:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`max-h-96 w-full rounded`},u):(0,Y.jsx)(`audio`,{controls:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`w-full`},u)),p&&(0,Y.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:`This media could not be played in your browser. Download it to play in another app.`}),h&&(0,Y.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:h}),e.url&&(0,Y.jsxs)(`button`,{className:`text-sm text-primary underline`,onClick:()=>{r(n.id,a,{url:e.url}).catch(()=>g(`Attachment could not be downloaded.`))},children:[`Download `,a]})]})}function Vd(e){let t=e.document.data,n=t.sender,r=t.channel,i=Array.isArray(t.attachments)?t.attachments:[],a=t.timestamp?new Date(String(t.timestamp)):null;return(0,Y.jsxs)(`article`,{className:`space-y-4 p-3 ${e.className||``}`,children:[(0,Y.jsxs)(`header`,{className:`space-y-1 border-b pb-3`,children:[(0,Y.jsx)(`p`,{className:`font-medium`,children:n?.name||n?.displayName||n?.username||n?.id||`Unknown sender`}),(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:[r?.name||r?.id,String(t.platform||``),a&&!Number.isNaN(a.getTime())?a.toLocaleString():``].filter(Boolean).join(` · `)})]}),(0,Y.jsx)(`p`,{className:`whitespace-pre-wrap break-words text-sm`,children:String(t.text||`(No text)`)}),!!t.mediaError&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:String(t.mediaError)}),i.map((t,n)=>(0,Y.jsx)(Bd,{...e,attachment:t},t.url||n))]})}var Hd={email:z,phone:x,sms:be,chat:be,slack:be,matrix:be,web:F,url:F},Ud={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Wd=e=>Array.isArray(e)?e:[];function Gd(e,t){return t?e===`email`?`mailto:${t}`:e===`phone`||e===`sms`?`tel:${t.replace(/[^\d+]/g,``)}`:/^https?:\/\//i.test(t)?t:null:null}function Kd({title:e,count:t,children:n}){return t===0?null:(0,Y.jsxs)(`div`,{className:`space-y-1`,children:[(0,Y.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,Y.jsx)(`div`,{className:`space-y-1`,children:n})]})}function qd({icon:e,primary:t,children:n,title:r}){return(0,Y.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 rounded-md border bg-card px-2.5 py-1.5 text-sm`,title:r,children:[(0,Y.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,Y.jsx)(Ye,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function Jd({document:e,className:t}){let n=e.data??{},r=Wd(n.identifiers),i=Wd(n.channels),a=Wd(n.organizations),o=Wd(n.links),s=Wd(n.tags),c=String(n.displayName||``).trim(),l=Cn(e.schema,Xt),u=String(n.primaryEmail||``).trim(),d=n.name&&typeof n.name==`object`?n.name:{},f=[d.prefix,d.given,d.middle,d.family,d.suffix].map(e=>String(e||``).trim()).filter(Boolean).join(` `),p=i.some(e=>e.kind===`email`&&e.value===u);return(0,Y.jsxs)(`div`,{className:V(`space-y-4`,t),children:[(0,Y.jsxs)(`div`,{className:`space-y-1`,children:[(0,Y.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,Y.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:Ud[l]||l}),f&&f!==c&&(0,Y.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,Y.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,Y.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,Y.jsx)(Kd,{title:`Primary email`,count:1,children:(0,Y.jsx)(qd,{icon:z,primary:!0,children:(0,Y.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,Y.jsx)(Kd,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=Gd(n,r),a=Hd[n]||be;return(0,Y.jsxs)(qd,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,Y.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,Y.jsx)(Kd,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,Y.jsxs)(qd,{icon:st,primary:e.primary,children:[(0,Y.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,Y.jsx)(Kd,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,Y.jsxs)(qd,{icon:et,children:[e.name,e.role&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,Y.jsx)(Kd,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,Y.jsxs)(qd,{icon:We,children:[(0,Y.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,Y.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,Y.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function Yd({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,Y.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,Y.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function Xd(e){let t=e.schema;if(t===`data/schema/note`)return ad;if(t===`data/schema/drawing`)return Qu;if(t===`data/schema/task`)return jd;if(t===`data/schema/message/email`)return Rd;if(t===`data/schema/message`)return Vd;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return Jd;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return Rt(t)?od:cd(t)?sd:ud}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(Vt(n,Ft(e))){case`image`:return Qu;case`audio`:return $u;case`video`:return ed;case`pdf`:return td;case`markdown`:return ad;case`text`:return id;default:return Yd}}function Zd({workspaceId:e,document:t,className:n}){let r=Xd(t);return r?(0,Y.jsx)(r,{workspaceId:e,document:t,className:n}):(0,Y.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var Qd=new lr({html:!1});function $d(e){let t=e=>{let n=[];return e.map(e=>{if(e.children)return t(e.children);switch(e.type){case`strong_open`:case`strong_close`:return`*`;case`em_open`:case`em_close`:return`_`;case`s_open`:case`s_close`:return`~`;case`code_inline`:return`\`${e.content}\``;case`fence`:case`code_block`:return`\`\`\`\n${e.content}\`\`\`\n`;case`text`:return e.content;case`softbreak`:case`hardbreak`:return`
|
|
16
16
|
`;case`paragraph_close`:case`heading_close`:return`
|
|
17
17
|
|
|
18
|
-
`;case`list_item_open`:return`- `;case`link_open`:return n.push(String(e.attrGet(`href`)||``)),``;case`link_close`:return` (${n.pop()||``})`;case`image`:return e.content;default:return``}}).join(``)};return t(Qd.parse(e,{})).trim()}function ef(e,t,n=!1){let r=2166136261;try{for(let e of localStorage.getItem(`authToken`)||``)r=Math.imul(r^e.charCodeAt(0),16777619)}catch{}return`canvas:message-draft:${r>>>0}:${e}:${t||`new`}${n?`:fwd`:``}`}var tf={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function nf({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${ef(e)}:smtp-test:${i?.address}`:ef(e,t,s),l=()=>({requestId:crypto.randomUUID(),text:a?`This is a test email sent from Canvas to check the SMTP configuration.`:``,replyToDocumentId:t,...i,...a?{subject:`Canvas SMTP test`}:{},...s?{forward:!0}:t?{replyAll:n===`replyAll`,quote:!0}:{}}),[u,d]=(0,q.useState)(()=>{try{let e=localStorage.getItem(c);if(e){let r=JSON.parse(e),i=r.draft||r;if(s||!t||r.attempted)return i;let a=n===`replyAll`;return{...i,replyAll:a,...!!i.replyAll===a?{}:{to:void 0,cc:void 0}}}}catch{}return l()}),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)([]),[g,_]=(0,q.useState)(navigator.onLine);(0,q.useEffect)(()=>{let e=()=>_(navigator.onLine);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]);let v=(0,q.useRef)(!1),[y,b]=(0,q.useState)(!1),[x,S]=(0,q.useState)(!1),[C,w]=(0,q.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,q.useState)(``),[D,O]=(0,q.useState)(null);(0,q.useEffect)(()=>{let n=!0;return Promise.all([Ss(e),t?Cs(e,t):Promise.resolve(null)]).then(([e,r])=>{n&&(p(r),h(e.filter(e=>e.canSend&&(!r||e.driver===r.driver&&e.address===r.address))),t&&!r&&E(`This message has no supported reply account.`),r&&d(e=>{let t=e.replyAll?r.allRecipients:r.recipients;return{...e,driver:r.driver,address:r.address,...!s&&t&&!C?{to:e.to?.some(e=>e.trim())?e.to:t.to,cc:e.cc?.some(e=>e.trim())?e.cc:t.cc}:{}}}))}).catch(e=>{n&&E(e.message)}),()=>{n=!1}},[e,t,s,C]),(0,q.useEffect)(()=>{try{D?.status===`accepted`?localStorage.removeItem(c):localStorage.setItem(c,JSON.stringify({draft:u,attempted:C}))}catch{}},[c,u,C,D]);let k=m.find(e=>e.driver===u.driver&&e.address===u.address),ee=k?.driver===`imap`,A=k?.driver===`whatsapp`,te=!!u.images?.length,j=!!u.text.trim(),M=e=>d(t=>({...t,...e})),ne=async()=>{S(!0),E(``),w(!0);let t=ee?j?u:{...u,html:void 0}:{...u,text:A?$d(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await Es(e,u.requestId).catch(n=>{if(n.statusCode===404)return ws(e,t);throw n}):await ws(e,t);if(O(n),n.status===`accepted`){try{localStorage.removeItem(c)}catch{}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}}))}}catch(e){let t=e;E(t.message),!C&&t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==409&&w(!1)}finally{S(!1)}},re=async e=>{if(P||v.current)return;let t=e.filter(e=>[`image/png`,`image/jpeg`,`image/webp`,`image/gif`].includes(e.type));if(t.length){if((u.images?.length||0)+t.length>(A?1:8)){E(A?`One picture per WhatsApp reply.`:`Up to 8 pictures per email.`);return}if((u.images||[]).reduce((e,t)=>e+t.base64.length*3/4,0)+t.reduce((e,t)=>e+t.size,0)>8388608){E(`Pictures must total at most 8 MB.`);return}v.current=!0,b(!0);try{let e=await Promise.all(t.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>n(Error(`Could not read picture`)),r.onload=()=>t({name:e.name,mimeType:e.type,base64:String(r.result).split(`,`)[1]}),r.readAsDataURL(e)})));d(t=>({...t,images:[...t.images||[],...e]})),E(``)}catch(e){E(e instanceof Error?e.message:`Could not read picture`)}finally{v.current=!1,b(!1)}}},N=u.replyAll?f?.allRecipients:f?.recipients,P=x||C||y,ie=a?`Send test email`:t?s?tf.forward:tf[u.replyAll?`replyAll`:`reply`]:`New message`,ae=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Y.jsxs)(`section`,{onPasteCapture:e=>{if(!(ee||A))return;let t=Array.from(e.clipboardData.files);t.some(e=>e.type.startsWith(`image/`))&&(e.preventDefault(),e.stopPropagation(),re(t))},className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${ie} to message`:`New message`,children:[(0,Y.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Y.jsx)(`strong`,{className:`text-sm`,children:ie}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,Y.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:k?`${k.driver}:${k.address}`:``,disabled:P||!!t||!!i,onChange:e=>{let t=m.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&M({driver:t.driver,address:t.address,to:[],cc:[],bcc:[],subject:void 0,target:void 0,images:void 0,replyAll:!1})},children:[(0,Y.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,Y.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses the saved SMTP settings. Enter a recipient you control, then click Send. This sends a real email; provider acceptance does not guarantee inbox delivery.`}),!m.length&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Enable sending in the account’s workspace settings. Your draft stays on this device.`}),ee?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,Y.jsx)(H,{"aria-label":`To`,disabled:P,value:u.to?.join(`, `)||``,onChange:e=>M({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&N&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,N.to.join(`, `),N.cc.length?` · Cc: ${N.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Y.jsx)(H,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:P,value:u[e]?.join(`, `)||``,onChange:t=>M({[e]:[t.target.value]})})]},e)),(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Y.jsx)(H,{"aria-label":`Subject`,disabled:P,value:u.subject||``,placeholder:ae,onChange:e=>M({subject:e.target.value||void 0})})]}),t&&!s&&(0,Y.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Y.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,disabled:P,checked:u.replyAll||!1,onChange:e=>{let t=e.target.checked?f?.allRecipients:f?.recipients;M({replyAll:e.target.checked,...t?{to:t.to,cc:t.cc}:{}})}}),`Reply all`]}),(0,Y.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,disabled:P,checked:u.quote||!1,onChange:e=>M({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,Y.jsx)(Ln,{format:`html`,editable:!P,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>M({html:e,text:t.slice(0,32e3)})})]}):(0,Y.jsxs)(Y.Fragment,{children:[!t&&(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,Y.jsx)(H,{"aria-label":`Conversation`,disabled:P,value:u.target||``,onChange:e=>M({target:e.target.value})})]}),A?(0,Y.jsx)(Ln,{format:`markdown`,editable:!P,value:u.text,placeholder:`Write a message…`,onChange:e=>M({text:e.slice(0,32e3)})}):(0,Y.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:P,value:u.text,onChange:e=>M({text:e.target.value}),placeholder:`Write a message…`})]}),(ee||A)&&(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,Y.jsx)(`input`,{"aria-label":`Attach pictures`,className:`block`,type:`file`,accept:`image/png,image/jpeg,image/webp,image/gif`,multiple:!A,disabled:P,onChange:e=>{re(Array.from(e.target.files||[])),e.target.value=``}})]}),u.images?.map((e,t)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,Y.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,disabled:P,onClick:()=>M({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),A&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,Y.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[D.status===`accepted`?`Accepted by the provider.`:D.message,` `,D.warnings?.join(` `),` `,D.rejected?.length?`Not accepted for: ${D.rejected.join(`, `)}`:``]}),D?.status!==`accepted`&&(0,Y.jsx)(W,{size:`sm`,disabled:x||y||!C&&(!k||!j&&!te&&!(ee&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void ne(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,disabled:x,onClick:()=>{window.confirm(C?`This message may already have been sent. Discard this draft only after checking the conversation.`:`Discard this draft?`)&&(d({...l(),driver:u.driver,address:u.address}),w(!1),O(null),E(``))},children:`Discard draft`}),C&&D?.status!==`accepted`&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Do not start another send until you have checked the conversation. The same request will not be delivered twice by Canvas.`})]})}function rf(e){let t=(0,q.useRef)(null),n=(0,q.useRef)(e.onClose);return(0,q.useEffect)(()=>{n.current=e.onClose}),(0,q.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,Y.jsx)(`dialog`,{ref:t,"aria-label":e.replyToDocumentId?`${e.mode===`forward`?`Forward`:e.mode===`replyAll`?`Reply all`:`Reply`} message`:`Send test email`,className:`m-auto w-[calc(100%-2rem)] max-w-3xl max-h-[90dvh] overflow-y-auto rounded-(--panel-radius) border bg-card p-0 text-foreground shadow-elevation-4 backdrop:bg-black/40`,onKeyDown:e=>e.stopPropagation(),onCancel:e=>{e.preventDefault(),e.stopPropagation(),n.current()},children:(0,Y.jsx)(nf,{...e})})}function af({workspaceId:e,documentId:t}){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(``),[o,s]=(0,q.useState)({}),[c,l]=(0,q.useState)(null),u=(0,q.useCallback)(async()=>{try{let n=await Os(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,q.useEffect)(()=>{let n=!0;Os(e,t).then(e=>{n&&(r(e),a(``))}).catch(e=>{n&&a(e instanceof Error?e.message:`Could not load thread`)});let i=()=>{u()};return window.addEventListener(`workspace:documents:refresh`,i),window.addEventListener(mu,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(mu,i)}},[e,t,u]),i?(0,Y.jsxs)(`div`,{className:`p-3`,children:[(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,Y.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,Y.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Y.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,Y.jsx)(W,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No linked replies have been indexed. Other messages in this conversation are separate from this reply thread.`}),n.truncated&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Showing up to 200 linked messages.`}),n.documents.map(r=>{let i=Gt(r),a=r.schema===`data/schema/message/email`,c=a||[`slack`,`whatsapp`].includes(String(r.data.platform)),u=r.data.timestamp||r.data.date,d=u?new Date(String(u)):null,f=(n.parents[r.id]||[]).flatMap(e=>{let t=n.documents.find(t=>Number(t.id)===e);return t?[Gt(t).title]:[]}),p=o[Number(r.id)]??Number(r.id)===t;return(0,Y.jsxs)(`details`,{open:p,onToggle:e=>{let t=e.currentTarget.open;s(e=>e[Number(r.id)]===t?e:{...e,[Number(r.id)]:t})},className:`rounded-lg border bg-card`,children:[(0,Y.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,Y.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,Y.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,Y.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,Y.jsx)(W,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,Y.jsx)(Zd,{workspaceId:e,document:r})]},r.id)}),c&&(0,Y.jsx)(rf,{workspaceId:e,replyToDocumentId:Number(c.document.id),mode:c.mode,originalSubject:typeof c.document.data.subject==`string`?c.document.data.subject:void 0,onClose:()=>l(null)},`${c.document.id}:${c.mode}`)]})}var of=15,sf=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function cf(e){return String(e).padStart(2,`0`)}function lf(e){let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(e||``);return t?{date:`${t[1]}-${t[2]}-${t[3]}`,time:`${t[4]}:${t[5]}`}:null}function uf(e){return`${e.getFullYear()}-${cf(e.getMonth()+1)}-${cf(e.getDate())}`}function df(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function ff(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/of)*of),`${cf(e.getHours())}:${cf(e.getMinutes())}`}function pf(){let e=[];for(let t=0;t<1440;t+=of)e.push(`${cf(Math.floor(t/60))}:${cf(t%60)}`);return e}var mf=pf();function hf(e){let t=new Date(e.getFullYear(),e.getMonth(),1),n=(t.getDay()+6)%7,r=new Date(t);return r.setDate(t.getDate()-n),Array.from({length:42},(e,t)=>{let n=new Date(r);return n.setDate(r.getDate()+t),n})}function gf(e){let[t,n]=e.split(`:`).map(Number);return new Date(2e3,0,1,t,n).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function _f(e){let t=lf(e);if(!t)return``;let[n,r,i]=t.date.split(`-`).map(Number),[a,o]=t.time.split(`:`).map(Number);return new Date(n,r-1,i,a,o).toLocaleString(void 0,{weekday:`short`,day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}function vf({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,q.useState)(!1),u=(0,q.useRef)(null),d=lf(e),f=d?_f(e):``;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:V(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,Y.jsx)(w,{className:V(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Y.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Y.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Y.jsx)(T,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Y.jsx)(yf,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function yf({anchorRef:e,value:t,onChange:n,onClose:r}){let i=lf(t),a=i?.date??uf(new Date),o=i?.time??null,[s,c]=(0,q.useState)(()=>{let e=df(a);return new Date(e.getFullYear(),e.getMonth(),1)}),u=(0,q.useRef)(null),d=(0,q.useRef)(null),[f,p]=(0,q.useState)(null);(0,q.useLayoutEffect)(()=>{let t=u.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));p({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let m=(0,q.useMemo)(()=>!o||mf.includes(o)?mf:[...mf,o].sort(),[o]);(0,q.useEffect)(()=>{let e=d.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let h=(e,t)=>n(`${e}T${t}`),g=e=>{let t=o??ff();h(uf(e),t),e.getMonth()!==s.getMonth()&&c(new Date(e.getFullYear(),e.getMonth(),1))},_=e=>{h(a,e),r()},v=e=>{let t=new Date;t.setDate(t.getDate()+e);let n=o??ff();h(uf(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},y=uf(new Date),b=hf(s);return(0,lo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Y.jsxs)(`div`,{ref:u,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:f?.x??-9999,top:f?.y??-9999,visibility:f?`visible`:`hidden`},children:[(0,Y.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Y.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Y.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Y.jsx)(l,{className:`h-4 w-4`})}),(0,Y.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Y.jsx)(vt,{className:`h-4 w-4`})})]}),(0,Y.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:sf.map(e=>(0,Y.jsx)(`span`,{children:e},e))}),(0,Y.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:b.map(e=>{let t=uf(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Y.jsx)(`button`,{type:`button`,onClick:()=>g(e),"aria-pressed":r,className:V(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===y&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,Y.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Y.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,Y.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Y.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&h(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,Y.jsx)(`div`,{ref:d,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:m.map(e=>{let t=e===o;return(0,Y.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>_(e),"aria-pressed":t,className:V(`block w-full rounded px-2 py-1 text-left text-xs tabular-nums transition-colors`,t?`bg-primary text-primary-foreground`:`hover:bg-muted`),children:gf(e)},e)})})]})]})]}),document.body)}var bf={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},xf=`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,Sf=`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Cf({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-title`,children:`Title`}),(0,Y.jsx)(H,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-desc`,children:`Description`}),(0,Y.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:Sf})]}),(0,Y.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-due`,children:`Due`}),(0,Y.jsx)(vf,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Y.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:xf,children:[(0,Y.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Y.jsx)(`option`,{value:e,children:bf[e]},e))]})]})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-status`,children:`Status`}),(0,Y.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:xf,children:_d.map(e=>(0,Y.jsx)(`option`,{value:e,children:vd[e]},e))})]})]})}var wf=`3.0`,Tf=[`person`,`organization`,`service`,`bot`],Ef={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Df=[`email`,`phone`,`sms`,`chat`,`web`],Of=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function kf(e){let t=e.primaryEmail.trim().toLowerCase(),n=e.channels.map(e=>({...e,kind:e.kind.trim(),value:e.value.trim(),label:e.label?.trim()||void 0})).filter(e=>e.kind&&e.value);if(t&&!n.some(e=>e.kind===`email`&&e.value===t)){for(let e of n)e.kind===`email`&&(e.primary=!1);n.push({kind:`email`,value:t,label:void 0,primary:!0})}let r=e.given.trim(),i=e.family.trim();return{displayName:e.displayName.trim(),...t?{primaryEmail:t}:{},...r||i?{name:{...r?{given:r}:{},...i?{family:i}:{}}}:{},channels:n,identifiers:e.identifiers.map(e=>({...e,type:e.type.trim(),identifier:e.identifier.trim(),provider:e.provider?.trim()||void 0})).filter(e=>e.type&&e.identifier),organizations:e.organizations.map(({identityId:e,...t})=>({...t,name:t.name.trim(),role:t.role?.trim()||void 0,...e?{metadata:{identityId:e}}:{}})).filter(e=>e.name)}}function Af(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Cn(String(e?.schema||``),Xt);return{displayName:String(t.displayName||``),type:Tf.includes(i)?i:`person`,primaryEmail:String(t.primaryEmail||``),given:String(n.given||``),family:String(n.family||``),channels:r(t.channels),identifiers:r(t.identifiers),organizations:r(t.organizations).map(e=>({name:String(e.name||``),role:e.role?String(e.role):void 0,identityId:Number(e.metadata?.identityId)||void 0}))}}async function jf(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await On(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function Mf(e){let[t,n]=(0,q.useState)(e?.displayName??``),[r,i]=(0,q.useState)(e?.type??`person`),[a,o]=(0,q.useState)(e?.primaryEmail??``),[s,c]=(0,q.useState)(e?.given??``),[l,u]=(0,q.useState)(e?.family??``),[d,f]=(0,q.useState)(e?.channels??[]),[p,m]=(0,q.useState)(e?.identifiers??[]),[h,g]=(0,q.useState)(e?.organizations??[]),[_,v]=(0,q.useState)([]),[y,b]=(0,q.useState)(``),[x,S]=(0,q.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${Xt}/${C.type}`,schemaVersion:wf,data:kf(C),...t?{comment:t}:{},metadata:{features:Jn(_)}},r=await ar(e,[n]);return await jf(e,r[0],h),r}finally{S(!1)}}return{displayName:t,setDisplayName:n,type:r,setType:i,primaryEmail:a,setPrimaryEmail:o,given:s,setGiven:c,family:l,setFamily:u,channels:d,setChannels:f,identifiers:p,setIdentifiers:m,organizations:h,setOrganizations:g,tags:_,setTags:v,comment:y,setComment:b,values:C,saving:x,canSave:T,emailValid:w,save:E}}var Nf=`h-9 shrink-0 rounded-md border border-input bg-transparent px-2 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Pf({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Y.jsx)(uo,{children:e}),(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Y.jsx)(ze,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Y.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,Y.jsx)(L,{className:`h-3.5 w-3.5`})})]},i))})]})}function Ff(e,t){let n=e[t].kind,r=e[t].primary;return e.map((e,i)=>e.kind===n?{...e,primary:!r&&i===t}:e)}function If(e){let[t,n]=(0,q.useState)([]);return(0,q.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Jt(e,`organization`);t||n(r.map(e=>({id:e.id,name:Gt(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function Lf({idPrefix:e,workspaceName:t,displayName:n,setDisplayName:r,type:i,setType:a,primaryEmail:o,setPrimaryEmail:s,given:c,setGiven:l,family:u,setFamily:d,channels:f,setChannels:p,identifiers:m,setIdentifiers:h,organizations:g,setOrganizations:_,emailValid:v=!0}){let y=If(t);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Y.jsx)(H,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-type`,children:`Type`}),(0,Y.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:V(Nf,`w-full`),children:Tf.map(e=>(0,Y.jsx)(`option`,{value:e,children:Ef[e]},e))})]}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Y.jsx)(H,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-given`,children:`Given name`}),(0,Y.jsx)(H,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-family`,children:`Family name`}),(0,Y.jsx)(H,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Y.jsx)(Pf,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:V(Nf,`w-24`),children:[Df.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Df.includes(e.kind)&&(0,Y.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Y.jsx)(H,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>p(Ff(f,f.indexOf(e))),className:V(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,Y.jsx)(Ye,{className:V(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Y.jsx)(Pf,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:V(Nf,`w-24`),children:[Of.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Of.includes(e.type)&&(0,Y.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Y.jsx)(H,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,Y.jsx)(Pf,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[y.length>0?(0,Y.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:V(Nf,`min-w-0 flex-1`),children:[(0,Y.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Y.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Y.jsx)(H,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Y.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Y.jsx)(Ne,{className:`h-3.5 w-3.5`})}),(0,Y.jsx)(H,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function Rf(e){return e===`data/schema/note`||e===`data/schema/link`||e===`data/schema/tab`||e===`data/schema/task`||e===`data/schema/drawing`||e===`data/schema/identity`||e.startsWith(`data/schema/identity/`)}function zf(e){return Rf(e.schema)||Bn(e)}function Bf(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function Vf(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await Qt(e,t,{resolve:!1}),a=new Set(i.outgoing.filter(e=>e.p===`member-of`).map(e=>e.to));for(let n of r)a.has(n)||await On(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await en(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function Hf({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),a=Rf(e.schema),o=e.schema===Yt,s=Bn(e),c=Wn(e)??`markdown`,l=s&&Fn(e),u=e.schema===Nt,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=Bf(e.schema),[m,h]=(0,q.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,q.useState)(String(e.data?.[p]??``)),[v,y]=(0,q.useState)(String(e.data?.content??``)),[b,x]=(0,q.useState)(String(e.data?.description??``)),[S,C]=(0,q.useState)(e.data?.status??`pending`),[w,T]=(0,q.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,q.useState)(e.data?.dueDate?xd(String(e.data.dueDate)):Cd()),O=Mf(Af(e)),[k,ee]=(0,q.useState)(String(e.comment??``)),A=e.metadata?.geo??null,[te,j]=(0,q.useState)(A),M=e.features??e.metadata?.features,[ne,re]=(0,q.useState)(qn(M).length?qn(M):e.data?.tags??[]),N=In(e,t,o),{title:P,content:ie,comment:ae,tags:oe,geo:se,setTitle:ce,setContent:le,setComment:F,setTags:ue,setGeo:de}=o?N:{title:g,content:v,comment:k,tags:ne,geo:te,setTitle:_,setContent:y,setComment:ee,setTags:re,setGeo:j},fe=JSON.stringify(se??null)!==JSON.stringify(A??null),pe=Rn(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Vn,version:e.checksumArray?.[0]??null}),[me,I]=(0,q.useState)(null),L=`${e.id}:${e.checksumArray?.[0]??``}`;s&&pe.text!=null&&me!==L&&(I(L),le(pe.text));let[he,ge]=(0,q.useState)([]),[_e,R]=(0,q.useState)(!1),{replicating:ve,mirror:ye}=G(e);(0,q.useEffect)(()=>{let e=!1;return kt(t).then(t=>{e||ge(t)}).catch(()=>{}),()=>{e=!0}},[t]);let be=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),xe=!_e&&(s?!l&&pe.text!=null&&!pe.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?P.trim().length>0:o?N.canSave:be:!0),Se=async()=>{R(!0);let c=[...(M||[]).filter(e=>!e.startsWith(`tag/`)),...Jn(oe)];try{if(o){await N.save(),n();return}if(s){let i=await Kn(t,e,ie,{comment:ae.trim(),metadata:{features:c,...fe?{geo:se}:{}}});r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n(i);return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:ae.trim(),metadata:{features:c}};if(d){let{type:t,...n}=e.data??{};i.schema=`${Xt}/${O.values.type}`,i.data={...n,...kf(O.values)}}else if(u)i.data={...e.data,...wd({title:P,description:b,status:S,priority:w,due:E})};else if(a){let t=oe.map(e=>e.trim()).filter(Boolean),n;o?n={...P.trim()?{title:P.trim()}:{},content:ie}:(n={...e.data},f&&(n[f]=m.trim()),P.trim()?n[p]=P.trim():delete n[p],n.tags=t),i.data=n}fe&&(i.metadata={...i.metadata??{},geo:se}),await An(t,i),d&&(await Vf(t,e.id,O.values.organizations),hu()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{R(!1)}};return(0,Y.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`edit-url`,children:`URL`}),(0,Y.jsx)(H,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!be&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Y.jsx)(Lf,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Y.jsx)(Cf,{idPrefix:`edit-todo`,title:P,setTitle:ce,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`edit-title`,children:`Title`}),(0,Y.jsx)(H,{id:`edit-title`,value:P,onChange:e=>ce(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{children:`Body`}),l?(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&pe.error?(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:pe.error}):s&&pe.text==null?(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Y.jsx)(Hn,{kind:o?`markdown`:c,value:ie,onChange:le,placeholder:o?`Write your note…`:void 0})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{children:`Tags`}),(0,Y.jsx)(Ml,{tags:oe,onChange:ue,suggestions:he})]}),(0,Y.jsx)(Wl,{value:se,onChange:de}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`edit-comment`,children:`Comment`}),(0,Y.jsx)(`textarea`,{id:`edit-comment`,value:ae,onChange:e=>F(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),o&&(0,Y.jsx)(Gn,{...N,onRetry:N.save}),(0,Y.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Y.jsx)(W,{variant:`outline`,size:`sm`,onClick:()=>n(),disabled:_e,children:o?`Close`:`Cancel`}),(0,Y.jsx)(W,{size:`sm`,onClick:Se,disabled:!xe,children:_e?ve?`Replicating to ${ye.label}…`:`Saving…`:`Save changes`})]})]})}var Uf=(0,q.createContext)(null),Wf={open:()=>{},close:()=>{}};function Gf(){return(0,q.useContext)(Uf)??Wf}var Kf=`main`,qf=(0,q.createContext)(null);function Jf(){return(0,q.useContext)(qf)}var Yf=50;function Xf({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=Gf(),o=nu(),s=Jf(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?Gt(l).title:``,[d,f]=(0,q.useState)(!1),{showErrorToast:p}=Tt(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await bn(t,c):l;s?o.open(n,t):a(n,t)}catch(e){p(e instanceof Error?e.message:`Failed to open document`)}finally{f(!1)}}},h=!e.meta||e.meta.src===`doc`;return(0,Y.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,Y.jsx)(Te,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Y.jsx)(lt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Y.jsx)(wc,{document:l,size:3.5}):null,l?(0,Y.jsx)(`button`,{type:`button`,onClick:()=>void m(),disabled:d,className:`min-w-0 flex-1 truncate text-left hover:underline`,title:u,children:u}):(0,Y.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Y.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!h&&(0,Y.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),h&&(0,Y.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,Y.jsx)(L,{className:`h-3.5 w-3.5`})})]})}function Zf({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Tt(),[i,a]=(0,q.useState)(null),[o,s]=(0,q.useState)(null),[c,l]=(0,q.useState)(!1),[u,d]=(0,q.useState)(!1),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(0),[g,_]=(0,q.useState)(1),v=(0,q.useRef)(0),y=(0,q.useCallback)(()=>{v.current++},[]),b=(0,q.useCallback)(async()=>{let n=++v.current;try{let r=await Qt(t,e.id,{offset:m*Yf,limit:Yf,summary:!0});if(n!==v.current)return;let i=Math.max(0,Math.ceil(Math.max(r.outgoingCount??r.outgoing.length,r.incomingCount??r.incoming.length)/Yf)-1);if(_(i+1),m>i){h(i);return}a(r),s(null)}catch(e){if(n!==v.current)return;s(e instanceof Error?e.message:String(e))}},[t,e.id,m]),x=`${t}:${e.id}`,[S,C]=(0,q.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,q.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(mu,e),()=>{y(),window.removeEventListener(mu,e)}},[b,y]);let w=async(i,a)=>{let o=a===`out`?i.to:i.from;if(o==null)return;let s=`${a}:${i.p}:${o}`;p(s);try{await en(t,e.id,i.p,o,a),n(`Relation removed`),hu()}catch(e){r(e instanceof Error?e.message:`Failed to remove relation`)}finally{p(null)}},T=[{dir:`out`,title:`Points at`,hint:`this document as the subject`,entries:i?.outgoing??[]},{dir:`in`,title:`Pointed at by`,hint:`this document as the object`,entries:i?.incoming??[]}],E=e=>{a(null),h(e)};return(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Y.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Y.jsx)(ze,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Y.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,Y.jsxs)(`div`,{className:`mb-2`,children:[(0,Y.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,Y.jsx)(Xf,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,Y.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Y.jsx)(W,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,Y.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,Y.jsx)(As,{onClose:()=>{u||l(!1)},children:(0,Y.jsx)(Lc,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,tabs:[`relations`],fixedWorkspaceName:t,documentCount:1,saving:u,relationPredicates:i?.predicates,relationExcludeIds:new Set([e.id]),onClose:()=>l(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:i,direction:a,targetIds:o})=>{d(!0);try{await On(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),hu()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var Qf=(0,q.lazy)(()=>s(()=>import(`./SketchEditor-CRJF-Jp4.js`),__vite__mapDeps([9,3,4,10,1,11,12,13,14,15,16,17,18,19,20,21,22,23,24]))),$f=(0,q.lazy)(()=>s(()=>import(`./TextDocumentEditor-BF5NzQ6H.js`),__vite__mapDeps([25,3,4,11,10,13,12,14,15,16,26,1,23]))),ep={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},tp={reply:oe,replyAll:p,forward:ce};function np({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Pn()!=null,{showErrorToast:a}=Tt(),[o,s]=(0,q.useState)(!1),c=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[l,u]=(0,q.useState)(null),d=e.schema===`data/schema/message/email`,f=!i&&(d||[`slack`,`whatsapp`].includes(String(e.data?.platform))),p=d?[`reply`,`replyAll`,`forward`]:[`reply`],m=e=>u(t=>t===e?null:e),h=!i,[g,_]=(0,q.useState)(n&&!i),v=e.schema===qt,[y,b]=(0,q.useState)(!1),x=e.schema===`data/schema/note`||Bn(e),[S,w]=(0,q.useState)(!1),T=`${t}:${e.id}:${n}:${i}`,[E,D]=(0,q.useState)(T);T!==E&&(D(T),_(n&&!i),u(null),s(!1),b(!1),w(!1));let k=t=>{if(!h||!zf(e)||t.defaultPrevented)return!1;let n=t.target;return n instanceof Element&&t.currentTarget.contains(n)&&!n.closest(`a, button, input, textarea, select, label, summary, audio, video, [role="button"], [role="checkbox"], [contenteditable]:not([contenteditable="false"])`)};return g&&h?(0,Y.jsx)(Hf,{document:e,workspaceId:t,onClose:e=>{_(!1),r?.(e)}}):(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[h&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[c&&(0,Y.jsx)(W,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=tp[e];return(0,Y.jsxs)(W,{size:`sm`,variant:l===e?`secondary`:`outline`,onClick:()=>m(e),children:[(0,Y.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),ep[e]]},e)}),e.schema===`data/schema/file`&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>Wt(t,e.id,Ft(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Y.jsx)(Me,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Y.jsx)(C,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>w(!0),children:[(0,Y.jsx)(yt,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Y.jsx)(O,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),y&&h&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Y.jsx)(Qf,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),_(!0)}})}),S&&h&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Y.jsx)($f,{doc:e,workspaceName:t,onSaved:e=>{w(!1),r?.(e)},onClose:()=>w(!1),onDetails:()=>{w(!1),_(!0)}})}),(0,Y.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,onMouseDownCapture:e=>{e.button===0&&e.detail>1&&k(e)&&e.preventDefault()},onDoubleClickCapture:e=>{k(e)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.ownerDocument.getSelection()?.removeAllRanges(),_(!0))},children:[o&&!i?(0,Y.jsx)(af,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,Y.jsx)(Zd,{workspaceId:t,document:e}),l&&f&&(0,Y.jsx)(rf,{workspaceId:t,replyToDocumentId:Number(e.id),mode:l,originalSubject:d&&typeof e.data?.subject==`string`?e.data.subject:void 0,onClose:()=>u(null)},`${e.id}:${l}`)]}),e.comment?.trim()&&(0,Y.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Y.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Y.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var rp=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,ip=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function ap({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Y.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,ip(n.exposureTime)),n&&i(`ISO`,Number.isFinite(n.iso)?n.iso:null),n&&i(`Focal length`,Number.isFinite(n.focalLength)?`${n.focalLength} mm`:null),n&&i(`Captured`,rp(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Y.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function op({document:e}){let t=e.metadata;return(0,Y.jsxs)(`div`,{className:`space-y-6`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Y.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Y.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:rp(e.createdAt)})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:rp(e.updatedAt)})]})]})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Y.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Y.jsx)(ap,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Y.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=up(e.url);return(0,Y.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Y.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),e.status&&e.status!==`available`&&(0,Y.jsx)(`span`,{className:`shrink-0 rounded border px-1 text-xs`,title:e.statusChangedAt,children:e.status===`deleted`?`Deleted`:`Not found`}),r&&(0,Y.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Y.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Y.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Y.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Y.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Y.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Y.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Y.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Y.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function sp({document:e}){let{showSuccessToast:t,showErrorToast:n}=Tt(),r=JSON.stringify(e,null,2);return(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`div`,{className:`flex justify-end`,children:(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Y.jsx)(u,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Y.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function cp({document:e,workspaceId:t}){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,q.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,q.useEffect)(()=>{let n=!1;return $t(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Y.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Y.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Y.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Y.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Y.jsx)(Zf,{document:e,workspaceId:t})]}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function lp(e){return e===`stored`?pt:e===`workspace-file`?ne:e===`imap`?z:e===`readonly`?F:at}function up(e){let t=e.match(/^([a-z][a-z0-9+.-]*):\/\/([^/]*)\/?(.*)$/i);return t?{backend:`${t[1]}://${t[2]}`,key:t[3]}:{backend:e,key:``}}function dp({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),[a,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(null),[l,d]=(0,q.useState)(null),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(null),[g,_]=(0,q.useState)(!1),v=`${t}:${e.id}`,[y,b]=(0,q.useState)(v);v!==y&&(b(v),o(null),c(null),p(null));let x=()=>{Lt(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,q.useEffect)(()=>{let n=!1;return Lt(t,e.id).then(e=>{n||o(e)}).catch(e=>{n||c(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[v]);let S=async(a,o)=>{d(a),p(null);try{let i=await gn(t,[e.id],{urls:[a],...o===void 0?{}:{keepDocument:o}}),s=i.successful[0];if(!s)throw Error(i.failed[0]?.reason||`Destroy failed`);s.docDeleted?r(`Removed from backend; document removed from index`):s.deleted.includes(a)?r(`Removed from backend`):r(`Reference dropped (backend is read-only)`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{d(null)}},C=async(a,o,s)=>{_(!0);try{let i=await kn(t,[e.id],{to:a,mode:o,keepDocument:s.keepDocument,folder:s.folder,filename:s.filename,onConflict:s.onConflict}),c=i.successful[0];if(!c)throw Error(ns(i.failed,new Map([[e.id,Ft(e)||`Document ${e.id}`]]))||`Transfer failed`);let l=c.transfers?.flatMap(e=>e.state===`unchanged`?[]:[e.backend])??[],u=a.join(`, `);o===`delete`?r(`Deleted from ${u}`):l.length===0?r(`Nothing to do — already on ${u}`):r(`${o===`move`?`Moved to`:`Copied to`} ${l.join(`, `)}${c.transfers?.some(e=>e.state===`pending`)?` (pending sync)`:``}`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),h(null),n?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{_(!1)}},w=e=>{if((a?.length??0)<=1){p(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&S(e.url)};if(s)return(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let T=a.length===0,E=Ft(e);return(0,Y.jsxs)(`div`,{className:`space-y-3`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(pt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Y.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Y.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),T?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>h(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Y.jsx)(u,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>h(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,Y.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=lp(n.kind),{backend:a,key:o}=up(n.url),s=l===n.url;return(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Y.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Y.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Y.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,Y.jsx)(`button`,{onClick:()=>Wt(t,e.id,E||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,Y.jsx)(Me,{className:`h-3.5 w-3.5`})}),(0,Y.jsx)(`button`,{onClick:()=>w(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,Y.jsx)(L,{className:`h-3.5 w-3.5`})})]})]}),f===n.url&&(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Y.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Y.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Y.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Y.jsx)(W,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!1),children:`Also remove index entry`}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Y.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>p(null),children:`Cancel`})]})]})]},n.url)}),m&&(0,lo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Y.jsx)(Ql,{workspaceId:t,documentCount:1,initialMode:m,defaultFilename:E,saving:g,onConfirm:C,onClose:()=>{g||h(null)}})}),window.document.body)]})}function fp(e){let t=e.metadata?.geo,n=t?.lat,r=t?.lon;if(n==null||r==null||n===``||r===``)return null;let i=Number(n),a=Number(r);return!Number.isFinite(i)||!Number.isFinite(a)||i===0&&a===0?null:{lat:i,lon:a}}function pp(e,t,n){let r=!1;for(let i=0,a=n.length-1;i<n.length;a=i++){let o=n[i].lat,s=n[i].lon,c=n[a].lat,l=n[a].lon;o>e!=c>e&&t<(l-s)*(e-o)/(c-o)+s&&(r=!r)}return r}function mp(e,t,n){if(n.kind===`rect`){let r=n.bbox;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLon&&t<=r.maxLon}return n.points.length>=3&&pp(e,t,n.points)}function hp(e,t,n=!1){let r=fp(e);return r?mp(r.lat,r.lon,t):n}var gp=(0,q.lazy)(()=>s(()=>import(`./LocationTab-BONJQfYM.js`),__vite__mapDeps([27,3,4,28,29]))),_p=[{id:`view`,label:`View`,icon:dt},{id:`location`,label:`Location`,icon:Ie},{id:`metadata`,label:`Metadata`,icon:d},{id:`json`,label:`JSON`,icon:ge},{id:`synapses`,label:`Synapses`,icon:Qe},{id:`backends`,label:`Backends`,icon:pt}];function vp({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1,navigation:s,tabActions:c,onTabChange:l}){let u=Pn()!=null,d=fp(e),f=_p.filter(e=>(e.id!==`location`||d!==null)&&(!u||![`synapses`,`backends`].includes(e.id))),[p,m]=(0,q.useState)(n),h=`${e.id}:${n}`,[g,_]=(0,q.useState)(h);h!==g&&(_(h),m(n));let v=f.some(e=>e.id===p)?p:`view`,y=e=>{m(e),l?.(e)},b=o&&!!c&&!s,x=(0,Y.jsx)(`div`,{className:V(b&&`document-detail-header shrink-0 border-b-[3px] bg-muted`),children:(0,Y.jsxs)(`div`,{className:V(`flex min-w-0 items-center`,b&&`mx-auto h-[calc(3rem-4px)] w-full max-w-[var(--document-reading-width,100%)] gap-1 pl-2 pr-2 sm:pl-4`),children:[(0,Y.jsx)(ku,{tabs:f,active:v,onChange:y,className:V(`min-w-0 flex-1 px-1`,b&&`h-full border-b-0 px-0 max-sm:gap-0 max-sm:[&>button]:px-2.5`),iconOnly:o}),c]})});return(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[s?(0,Y.jsx)(Ou,{...s,tabs:x,section:v,onDocument:()=>y(`view`),onSection:()=>y(`view`),onBack:v===`view`?s.onBack:()=>y(`view`)}):x,(0,Y.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,Y.jsxs)(`div`,{className:`mx-auto h-full w-full max-w-[var(--document-reading-width,100%)] p-4`,children:[v===`view`&&(0,Y.jsx)(np,{document:e,workspaceId:t,initialEdit:r&&!u,onChanged:i}),v===`location`&&d&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Y.jsx)(gp,{lat:d.lat,lon:d.lon})}),v===`metadata`&&(0,Y.jsx)(op,{document:e,workspaceId:t}),v===`json`&&(0,Y.jsx)(sp,{document:e,workspaceId:t}),v===`synapses`&&!u&&(0,Y.jsx)(cp,{document:e,workspaceId:t}),v===`backends`&&!u&&(0,Y.jsx)(dp,{document:e,workspaceId:t,onChanged:i})]})})]})}function yp(e,t){let[n,r]=(0,q.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,q.useState)(a);a!==o&&(s(a),r(null));let c=(0,q.useRef)(a),l=(0,q.useRef)(0);(0,q.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,q.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}bn(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}function bp(e){let t=wu(),n=(0,q.useContext)(eu),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,q.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Y.jsx)(xp,{...e})}function xp({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,q.useState)(!1),c=tr(),{document:l,refresh:u}=yp(r,e);if(ps(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,lo.createPortal)((0,Y.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:V(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,Y.jsxs)(`div`,{className:V(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-(--panel-radius) md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-(--panel-radius)`),onClick:e=>e.stopPropagation(),children:[(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:Gt(l).title}),(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=jt(l);return e?(0,Y.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,Y.jsx)(Ae,{className:`h-4 w-4`})}):null})(),(0,Y.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,Y.jsx)(ve,{className:`h-4 w-4`}):(0,Y.jsx)(qe,{className:`h-4 w-4`})}),(0,Y.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Y.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Y.jsx)(gu.Provider,{value:()=>s(e=>!e),children:(0,Y.jsx)(vp,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Sp={sortBy:`alphabetical`,order:`asc`};function Cp(e){return e?.sortBy===`crud:deleted`?{...Sp}:{sortBy:e?.sortBy??Sp.sortBy,order:e?.order??Sp.order}}var wp={features:{allOf:[],anyOf:[],noneOf:[]},timeline:{quickFilter:null,customRanges:[],indexCreated:!0,indexUpdated:!0,indexDeleted:!1,contentEvents:!1,selectedTimelines:[]},geo:{bbox:null,includeUnlocated:!1},lens:{gps:null,ids:null},sort:{...Sp}};function Tp(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function Ep(e,t=!1){if(!e.gps)return[];let{lat:n,lon:r,radiusM:i}=e.gps;return[`geo:near:${n},${r},${Math.max(1,Math.round(i))}m`,...t?[`geo:missing`]:[]]}function Dp(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function Op(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Dp(e),c=s.length>0?s.map(e=>`${e.start}..${e.end}`):t?[t]:[];if(c.length===0)return[];let l=[];return n&&l.push(`crud:created`),r&&l.push(`crud:updated`),i&&l.push(`crud:deleted`),a&&l.push(`content`),l.push(...o),l.flatMap(e=>c.map(t=>`t:${e}:${t}`))}function kp(e,t,n=[]){return{features:e.features,filters:[...Op(e.timeline),...Tp(e.geo),...Ep(e.lens,e.geo.includeUnlocated)],queryOptions:{ids:e.lens.ids,sortBy:e.sort.sortBy,order:e.sort.order,queries:n,geoSelection:t,includeUnlocated:e.geo.includeUnlocated??!1}}}var Ap=Sp,jp={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function Mp(e){return jp[e]??e}function Np(e){let[t,n]=(0,q.useState)([]);return(0,q.useEffect)(()=>{let t=!1;return hn(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,q.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:Mp(e)})),[t])}function Pp({workspaceId:e,value:t,onChange:n}){let r=Np(e);return(0,Y.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Y.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value,order:[`alphabetical`,`type`].includes(e.target.value)?`asc`:t.order}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by`,"aria-label":`Sort by`,children:[t.sortBy!==`crud:deleted`&&!r.some(e=>e.value===t.sortBy)&&(0,Y.jsx)(`option`,{value:t.sortBy,children:Mp(t.sortBy)}),r.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending`:`Descending`,"aria-label":t.order===`asc`?`Ascending`:`Descending`,className:`flex h-7 w-7 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent hover:text-foreground touch-target`,children:t.order===`asc`?(0,Y.jsx)(Se,{className:`h-3.5 w-3.5`}):(0,Y.jsx)(ke,{className:`h-3.5 w-3.5`})})]})}function Fp(e,t){let n=t?.replace(/^t:/,``)||`crud:created`,r=(n===`crud:created`?[e.createdAt]:n===`crud:updated`?[e.updatedAt]:(e.timelines??[]).filter(e=>(e.timeline||e.name)===n).map(e=>e.start)).map(e=>Date.parse(e??``)).filter(Number.isFinite);return r.length?Math.min(...r):null}var Ip={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},Lp=e=>e*1e6;function Rp(){try{let e=new Intl.Locale(navigator.language),t=(typeof e.getWeekInfo==`function`?e.getWeekInfo():e.weekInfo)?.firstDay;if(typeof t==`number`&&t>=1&&t<=7)return t}catch{}return 1}function zp(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Bp(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=zp(e);return r.setDate(r.getDate()-n),r}var Vp=864e5;function Hp(e){let t=Rp(),n=zp(e),r=Bp(e,t);return{today:n.getTime(),yesterday:n.getTime()-Vp,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*Vp,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function Up(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:Lp(Ip.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:Lp(Ip.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:Lp(Ip.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:Lp(Ip.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:Lp(Ip.lastWeek)};let n=new Date(e),r=n.getFullYear()*12+n.getMonth();if(r===t.month)return{key:`this-month`,label:`Earlier this month`,rank:Lp(Ip.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:Lp(Ip.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:Lp(Ip.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:Lp(Ip.year)+i}}function Wp(e,t,n=`desc`,r=new Date){let i=Hp(r),a=new Map;for(let n of e){let e=Up(t(n),i),r=a.get(e.key);r?r.items.push(n):a.set(e.key,{...e,items:[n]})}let o=[...a.values()].sort((e,t)=>n===`asc`?e.rank-t.rank:t.rank-e.rank),s=o.filter(e=>e.key===`unknown`);return s.length?[...o.filter(e=>e.key!==`unknown`),...s]:o}function Gp(e,t){let n=t.split(`/`).filter(Boolean);if(e!==`backends`||n[0]!==`Trash`)return null;try{return{backend:n[1]?decodeURIComponent(n[1]):null,prefix:n.slice(2).join(`/`)}}catch{return null}}function Kp(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function qp(e,t=``){let n=new Map,r=[],i=t?`${t}/`:``;for(let t of e){if(!t.key.startsWith(i))continue;let e=t.key.slice(i.length);if(!e)continue;let a=e.indexOf(`/`);if(a>=0){let r=e.slice(0,a),o=i+r,s=n.get(o)??{id:`folder:${o}`,name:r,key:o,directory:!0,navigable:!0,items:[]};s.items.push(t),n.set(o,s)}else r.push({id:t.id,name:e,key:t.key,directory:t.type===`directory`,navigable:!1,items:[t]})}return[...n.values(),...r].sort((e,t)=>Number(t.directory)-Number(e.directory)||e.name.localeCompare(t.name)||t.items[0].deletedAt-e.items[0].deletedAt||e.id.localeCompare(t.id))}var Jp=(e,t)=>`${bt.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Yp(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await U.get(`${Jp(e,t)}?${o}`);if(n.push(...s.items),a=s.retention?.days??null,i=s.cursor,i&&r.has(i))throw Error(`Trash listing returned a repeated cursor`);i&&r.add(i)}while(i);return{items:n,days:a}}function Xp(e,t,n){return Qp(e,t,n,`restore`)}function Zp(e,t,n){return Qp(e,t,n,`discard`)}async function Qp(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await U.post(`${Jp(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{ln(e,`backends`),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:`backends`}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e,backend:t}}))}}async function $p(e,t){let n=Gp(`backends`,t);if(!n?.backend)return;let{items:r}=await Yp(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`)).sort((e,t)=>t.deletedAt-e.deletedAt),a=await Xp(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} restored; ${o.length} remain in Trash. Existing paths were kept.`)}function em(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
|
|
18
|
+
`;case`list_item_open`:return`- `;case`link_open`:return n.push(String(e.attrGet(`href`)||``)),``;case`link_close`:return` (${n.pop()||``})`;case`image`:return e.content;default:return``}}).join(``)};return t(Qd.parse(e,{})).trim()}function ef(e,t,n=!1){let r=2166136261;try{for(let e of localStorage.getItem(`authToken`)||``)r=Math.imul(r^e.charCodeAt(0),16777619)}catch{}return`canvas:message-draft:${r>>>0}:${e}:${t||`new`}${n?`:fwd`:``}`}var tf={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function nf({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${ef(e)}:smtp-test:${i?.address}`:ef(e,t,s),l=()=>({requestId:crypto.randomUUID(),text:a?`This is a test email sent from Canvas to check the SMTP configuration.`:``,replyToDocumentId:t,...i,...a?{subject:`Canvas SMTP test`}:{},...s?{forward:!0}:t?{replyAll:n===`replyAll`,quote:!0}:{}}),[u,d]=(0,q.useState)(()=>{try{let e=localStorage.getItem(c);if(e){let r=JSON.parse(e),i=r.draft||r;if(s||!t||r.attempted)return i;let a=n===`replyAll`;return{...i,replyAll:a,...!!i.replyAll===a?{}:{to:void 0,cc:void 0}}}}catch{}return l()}),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)([]),[g,_]=(0,q.useState)(navigator.onLine);(0,q.useEffect)(()=>{let e=()=>_(navigator.onLine);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]);let v=(0,q.useRef)(!1),[y,b]=(0,q.useState)(!1),[x,S]=(0,q.useState)(!1),[C,w]=(0,q.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,q.useState)(``),[D,O]=(0,q.useState)(null);(0,q.useEffect)(()=>{let n=!0;return Promise.all([Ss(e),t?Cs(e,t):Promise.resolve(null)]).then(([e,r])=>{n&&(p(r),h(e.filter(e=>e.canSend&&(!r||e.driver===r.driver&&e.address===r.address))),t&&!r&&E(`This message has no supported reply account.`),r&&d(e=>{let t=e.replyAll?r.allRecipients:r.recipients;return{...e,driver:r.driver,address:r.address,...!s&&t&&!C?{to:e.to?.some(e=>e.trim())?e.to:t.to,cc:e.cc?.some(e=>e.trim())?e.cc:t.cc}:{}}}))}).catch(e=>{n&&E(e.message)}),()=>{n=!1}},[e,t,s,C]),(0,q.useEffect)(()=>{try{D?.status===`accepted`?localStorage.removeItem(c):localStorage.setItem(c,JSON.stringify({draft:u,attempted:C}))}catch{}},[c,u,C,D]);let k=m.find(e=>e.driver===u.driver&&e.address===u.address),ee=k?.driver===`imap`,A=k?.driver===`whatsapp`,te=!!u.images?.length,j=!!u.text.trim(),M=e=>d(t=>({...t,...e})),ne=async()=>{S(!0),E(``),w(!0);let t=ee?j?u:{...u,html:void 0}:{...u,text:A?$d(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await Es(e,u.requestId).catch(n=>{if(n.statusCode===404)return ws(e,t);throw n}):await ws(e,t);if(O(n),n.status===`accepted`){try{localStorage.removeItem(c)}catch{}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}}))}}catch(e){let t=e;E(t.message),!C&&t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==409&&w(!1)}finally{S(!1)}},re=async e=>{if(P||v.current)return;let t=e.filter(e=>[`image/png`,`image/jpeg`,`image/webp`,`image/gif`].includes(e.type));if(t.length){if((u.images?.length||0)+t.length>(A?1:8)){E(A?`One picture per WhatsApp reply.`:`Up to 8 pictures per email.`);return}if((u.images||[]).reduce((e,t)=>e+t.base64.length*3/4,0)+t.reduce((e,t)=>e+t.size,0)>8388608){E(`Pictures must total at most 8 MB.`);return}v.current=!0,b(!0);try{let e=await Promise.all(t.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>n(Error(`Could not read picture`)),r.onload=()=>t({name:e.name,mimeType:e.type,base64:String(r.result).split(`,`)[1]}),r.readAsDataURL(e)})));d(t=>({...t,images:[...t.images||[],...e]})),E(``)}catch(e){E(e instanceof Error?e.message:`Could not read picture`)}finally{v.current=!1,b(!1)}}},N=u.replyAll?f?.allRecipients:f?.recipients,P=x||C||y,ie=a?`Send test email`:t?s?tf.forward:tf[u.replyAll?`replyAll`:`reply`]:`New message`,ae=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Y.jsxs)(`section`,{onPasteCapture:e=>{if(!(ee||A))return;let t=Array.from(e.clipboardData.files);t.some(e=>e.type.startsWith(`image/`))&&(e.preventDefault(),e.stopPropagation(),re(t))},className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${ie} to message`:`New message`,children:[(0,Y.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Y.jsx)(`strong`,{className:`text-sm`,children:ie}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,Y.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:k?`${k.driver}:${k.address}`:``,disabled:P||!!t||!!i,onChange:e=>{let t=m.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&M({driver:t.driver,address:t.address,to:[],cc:[],bcc:[],subject:void 0,target:void 0,images:void 0,replyAll:!1})},children:[(0,Y.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,Y.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses the saved SMTP settings. Enter a recipient you control, then click Send. This sends a real email; provider acceptance does not guarantee inbox delivery.`}),!m.length&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Enable sending in the account’s workspace settings. Your draft stays on this device.`}),ee?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,Y.jsx)(H,{"aria-label":`To`,disabled:P,value:u.to?.join(`, `)||``,onChange:e=>M({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&N&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,N.to.join(`, `),N.cc.length?` · Cc: ${N.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Y.jsx)(H,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:P,value:u[e]?.join(`, `)||``,onChange:t=>M({[e]:[t.target.value]})})]},e)),(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Y.jsx)(H,{"aria-label":`Subject`,disabled:P,value:u.subject||``,placeholder:ae,onChange:e=>M({subject:e.target.value||void 0})})]}),t&&!s&&(0,Y.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Y.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,disabled:P,checked:u.replyAll||!1,onChange:e=>{let t=e.target.checked?f?.allRecipients:f?.recipients;M({replyAll:e.target.checked,...t?{to:t.to,cc:t.cc}:{}})}}),`Reply all`]}),(0,Y.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,disabled:P,checked:u.quote||!1,onChange:e=>M({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,Y.jsx)(Ln,{format:`html`,editable:!P,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>M({html:e,text:t.slice(0,32e3)})})]}):(0,Y.jsxs)(Y.Fragment,{children:[!t&&(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,Y.jsx)(H,{"aria-label":`Conversation`,disabled:P,value:u.target||``,onChange:e=>M({target:e.target.value})})]}),A?(0,Y.jsx)(Ln,{format:`markdown`,editable:!P,value:u.text,placeholder:`Write a message…`,onChange:e=>M({text:e.slice(0,32e3)})}):(0,Y.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:P,value:u.text,onChange:e=>M({text:e.target.value}),placeholder:`Write a message…`})]}),(ee||A)&&(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,Y.jsx)(`input`,{"aria-label":`Attach pictures`,className:`block`,type:`file`,accept:`image/png,image/jpeg,image/webp,image/gif`,multiple:!A,disabled:P,onChange:e=>{re(Array.from(e.target.files||[])),e.target.value=``}})]}),u.images?.map((e,t)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,Y.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,disabled:P,onClick:()=>M({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),A&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,Y.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[D.status===`accepted`?`Accepted by the provider.`:D.message,` `,D.warnings?.join(` `),` `,D.rejected?.length?`Not accepted for: ${D.rejected.join(`, `)}`:``]}),D?.status!==`accepted`&&(0,Y.jsx)(W,{size:`sm`,disabled:x||y||!C&&(!k||!j&&!te&&!(ee&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void ne(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,disabled:x,onClick:()=>{window.confirm(C?`This message may already have been sent. Discard this draft only after checking the conversation.`:`Discard this draft?`)&&(d({...l(),driver:u.driver,address:u.address}),w(!1),O(null),E(``))},children:`Discard draft`}),C&&D?.status!==`accepted`&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Do not start another send until you have checked the conversation. The same request will not be delivered twice by Canvas.`})]})}function rf(e){let t=(0,q.useRef)(null),n=(0,q.useRef)(e.onClose);return(0,q.useEffect)(()=>{n.current=e.onClose}),(0,q.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,Y.jsx)(`dialog`,{ref:t,"aria-label":e.replyToDocumentId?`${e.mode===`forward`?`Forward`:e.mode===`replyAll`?`Reply all`:`Reply`} message`:`Send test email`,className:`m-auto w-[calc(100%-2rem)] max-w-3xl max-h-[90dvh] overflow-y-auto rounded-(--panel-radius) border bg-card p-0 text-foreground shadow-elevation-4 backdrop:bg-black/40`,onKeyDown:e=>e.stopPropagation(),onCancel:e=>{e.preventDefault(),e.stopPropagation(),n.current()},children:(0,Y.jsx)(nf,{...e})})}function af({workspaceId:e,documentId:t}){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(``),[o,s]=(0,q.useState)({}),[c,l]=(0,q.useState)(null),u=(0,q.useCallback)(async()=>{try{let n=await Os(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,q.useEffect)(()=>{let n=!0;Os(e,t).then(e=>{n&&(r(e),a(``))}).catch(e=>{n&&a(e instanceof Error?e.message:`Could not load thread`)});let i=()=>{u()};return window.addEventListener(`workspace:documents:refresh`,i),window.addEventListener(mu,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(mu,i)}},[e,t,u]),i?(0,Y.jsxs)(`div`,{className:`p-3`,children:[(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,Y.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,Y.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Y.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,Y.jsx)(W,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No linked replies have been indexed. Other messages in this conversation are separate from this reply thread.`}),n.truncated&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Showing up to 200 linked messages.`}),n.documents.map(r=>{let i=Gt(r),a=r.schema===`data/schema/message/email`,c=a||[`slack`,`whatsapp`].includes(String(r.data.platform)),u=r.data.timestamp||r.data.date,d=u?new Date(String(u)):null,f=(n.parents[r.id]||[]).flatMap(e=>{let t=n.documents.find(t=>Number(t.id)===e);return t?[Gt(t).title]:[]}),p=o[Number(r.id)]??Number(r.id)===t;return(0,Y.jsxs)(`details`,{open:p,onToggle:e=>{let t=e.currentTarget.open;s(e=>e[Number(r.id)]===t?e:{...e,[Number(r.id)]:t})},className:`rounded-lg border bg-card`,children:[(0,Y.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,Y.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,Y.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,Y.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,Y.jsx)(W,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,Y.jsx)(Zd,{workspaceId:e,document:r})]},r.id)}),c&&(0,Y.jsx)(rf,{workspaceId:e,replyToDocumentId:Number(c.document.id),mode:c.mode,originalSubject:typeof c.document.data.subject==`string`?c.document.data.subject:void 0,onClose:()=>l(null)},`${c.document.id}:${c.mode}`)]})}var of=15,sf=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function cf(e){return String(e).padStart(2,`0`)}function lf(e){let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(e||``);return t?{date:`${t[1]}-${t[2]}-${t[3]}`,time:`${t[4]}:${t[5]}`}:null}function uf(e){return`${e.getFullYear()}-${cf(e.getMonth()+1)}-${cf(e.getDate())}`}function df(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function ff(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/of)*of),`${cf(e.getHours())}:${cf(e.getMinutes())}`}function pf(){let e=[];for(let t=0;t<1440;t+=of)e.push(`${cf(Math.floor(t/60))}:${cf(t%60)}`);return e}var mf=pf();function hf(e){let t=new Date(e.getFullYear(),e.getMonth(),1),n=(t.getDay()+6)%7,r=new Date(t);return r.setDate(t.getDate()-n),Array.from({length:42},(e,t)=>{let n=new Date(r);return n.setDate(r.getDate()+t),n})}function gf(e){let[t,n]=e.split(`:`).map(Number);return new Date(2e3,0,1,t,n).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function _f(e){let t=lf(e);if(!t)return``;let[n,r,i]=t.date.split(`-`).map(Number),[a,o]=t.time.split(`:`).map(Number);return new Date(n,r-1,i,a,o).toLocaleString(void 0,{weekday:`short`,day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}function vf({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,q.useState)(!1),u=(0,q.useRef)(null),d=lf(e),f=d?_f(e):``;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:V(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,Y.jsx)(w,{className:V(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Y.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Y.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Y.jsx)(T,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Y.jsx)(yf,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function yf({anchorRef:e,value:t,onChange:n,onClose:r}){let i=lf(t),a=i?.date??uf(new Date),o=i?.time??null,[s,c]=(0,q.useState)(()=>{let e=df(a);return new Date(e.getFullYear(),e.getMonth(),1)}),u=(0,q.useRef)(null),d=(0,q.useRef)(null),[f,p]=(0,q.useState)(null);(0,q.useLayoutEffect)(()=>{let t=u.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));p({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let m=(0,q.useMemo)(()=>!o||mf.includes(o)?mf:[...mf,o].sort(),[o]);(0,q.useEffect)(()=>{let e=d.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let h=(e,t)=>n(`${e}T${t}`),g=e=>{let t=o??ff();h(uf(e),t),e.getMonth()!==s.getMonth()&&c(new Date(e.getFullYear(),e.getMonth(),1))},_=e=>{h(a,e),r()},v=e=>{let t=new Date;t.setDate(t.getDate()+e);let n=o??ff();h(uf(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},y=uf(new Date),b=hf(s);return(0,lo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Y.jsxs)(`div`,{ref:u,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:f?.x??-9999,top:f?.y??-9999,visibility:f?`visible`:`hidden`},children:[(0,Y.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Y.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Y.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Y.jsx)(l,{className:`h-4 w-4`})}),(0,Y.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Y.jsx)(vt,{className:`h-4 w-4`})})]}),(0,Y.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:sf.map(e=>(0,Y.jsx)(`span`,{children:e},e))}),(0,Y.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:b.map(e=>{let t=uf(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Y.jsx)(`button`,{type:`button`,onClick:()=>g(e),"aria-pressed":r,className:V(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===y&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,Y.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Y.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,Y.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Y.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&h(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,Y.jsx)(`div`,{ref:d,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:m.map(e=>{let t=e===o;return(0,Y.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>_(e),"aria-pressed":t,className:V(`block w-full rounded px-2 py-1 text-left text-xs tabular-nums transition-colors`,t?`bg-primary text-primary-foreground`:`hover:bg-muted`),children:gf(e)},e)})})]})]})]}),document.body)}var bf={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},xf=`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,Sf=`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Cf({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-title`,children:`Title`}),(0,Y.jsx)(H,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-desc`,children:`Description`}),(0,Y.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:Sf})]}),(0,Y.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-due`,children:`Due`}),(0,Y.jsx)(vf,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Y.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:xf,children:[(0,Y.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Y.jsx)(`option`,{value:e,children:bf[e]},e))]})]})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-status`,children:`Status`}),(0,Y.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:xf,children:_d.map(e=>(0,Y.jsx)(`option`,{value:e,children:vd[e]},e))})]})]})}var wf=`3.0`,Tf=[`person`,`organization`,`service`,`bot`],Ef={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Df=[`email`,`phone`,`sms`,`chat`,`web`],Of=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function kf(e){let t=e.primaryEmail.trim().toLowerCase(),n=e.channels.map(e=>({...e,kind:e.kind.trim(),value:e.value.trim(),label:e.label?.trim()||void 0})).filter(e=>e.kind&&e.value);if(t&&!n.some(e=>e.kind===`email`&&e.value===t)){for(let e of n)e.kind===`email`&&(e.primary=!1);n.push({kind:`email`,value:t,label:void 0,primary:!0})}let r=e.given.trim(),i=e.family.trim();return{displayName:e.displayName.trim(),...t?{primaryEmail:t}:{},...r||i?{name:{...r?{given:r}:{},...i?{family:i}:{}}}:{},channels:n,identifiers:e.identifiers.map(e=>({...e,type:e.type.trim(),identifier:e.identifier.trim(),provider:e.provider?.trim()||void 0})).filter(e=>e.type&&e.identifier),organizations:e.organizations.map(({identityId:e,...t})=>({...t,name:t.name.trim(),role:t.role?.trim()||void 0,...e?{metadata:{identityId:e}}:{}})).filter(e=>e.name)}}function Af(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Cn(String(e?.schema||``),Xt);return{displayName:String(t.displayName||``),type:Tf.includes(i)?i:`person`,primaryEmail:String(t.primaryEmail||``),given:String(n.given||``),family:String(n.family||``),channels:r(t.channels),identifiers:r(t.identifiers),organizations:r(t.organizations).map(e=>({name:String(e.name||``),role:e.role?String(e.role):void 0,identityId:Number(e.metadata?.identityId)||void 0}))}}async function jf(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await On(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function Mf(e){let[t,n]=(0,q.useState)(e?.displayName??``),[r,i]=(0,q.useState)(e?.type??`person`),[a,o]=(0,q.useState)(e?.primaryEmail??``),[s,c]=(0,q.useState)(e?.given??``),[l,u]=(0,q.useState)(e?.family??``),[d,f]=(0,q.useState)(e?.channels??[]),[p,m]=(0,q.useState)(e?.identifiers??[]),[h,g]=(0,q.useState)(e?.organizations??[]),[_,v]=(0,q.useState)([]),[y,b]=(0,q.useState)(``),[x,S]=(0,q.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${Xt}/${C.type}`,schemaVersion:wf,data:kf(C),...t?{comment:t}:{},metadata:{features:Jn(_)}},r=await ar(e,[n]);return await jf(e,r[0],h),r}finally{S(!1)}}return{displayName:t,setDisplayName:n,type:r,setType:i,primaryEmail:a,setPrimaryEmail:o,given:s,setGiven:c,family:l,setFamily:u,channels:d,setChannels:f,identifiers:p,setIdentifiers:m,organizations:h,setOrganizations:g,tags:_,setTags:v,comment:y,setComment:b,values:C,saving:x,canSave:T,emailValid:w,save:E}}var Nf=`h-9 shrink-0 rounded-md border border-input bg-transparent px-2 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Pf({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Y.jsx)(uo,{children:e}),(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Y.jsx)(ze,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Y.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,Y.jsx)(L,{className:`h-3.5 w-3.5`})})]},i))})]})}function Ff(e,t){let n=e[t].kind,r=e[t].primary;return e.map((e,i)=>e.kind===n?{...e,primary:!r&&i===t}:e)}function If(e){let[t,n]=(0,q.useState)([]);return(0,q.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Jt(e,`organization`);t||n(r.map(e=>({id:e.id,name:Gt(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function Lf({idPrefix:e,workspaceName:t,displayName:n,setDisplayName:r,type:i,setType:a,primaryEmail:o,setPrimaryEmail:s,given:c,setGiven:l,family:u,setFamily:d,channels:f,setChannels:p,identifiers:m,setIdentifiers:h,organizations:g,setOrganizations:_,emailValid:v=!0}){let y=If(t);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Y.jsx)(H,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-type`,children:`Type`}),(0,Y.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:V(Nf,`w-full`),children:Tf.map(e=>(0,Y.jsx)(`option`,{value:e,children:Ef[e]},e))})]}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Y.jsx)(H,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-given`,children:`Given name`}),(0,Y.jsx)(H,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-family`,children:`Family name`}),(0,Y.jsx)(H,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Y.jsx)(Pf,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:V(Nf,`w-24`),children:[Df.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Df.includes(e.kind)&&(0,Y.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Y.jsx)(H,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>p(Ff(f,f.indexOf(e))),className:V(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,Y.jsx)(Ye,{className:V(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Y.jsx)(Pf,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:V(Nf,`w-24`),children:[Of.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Of.includes(e.type)&&(0,Y.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Y.jsx)(H,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,Y.jsx)(Pf,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[y.length>0?(0,Y.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:V(Nf,`min-w-0 flex-1`),children:[(0,Y.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Y.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Y.jsx)(H,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Y.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Y.jsx)(Ne,{className:`h-3.5 w-3.5`})}),(0,Y.jsx)(H,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function Rf(e){return e===`data/schema/note`||e===`data/schema/link`||e===`data/schema/tab`||e===`data/schema/task`||e===`data/schema/drawing`||e===`data/schema/identity`||e.startsWith(`data/schema/identity/`)}function zf(e){return Rf(e.schema)||Bn(e)}function Bf(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function Vf(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await Qt(e,t,{resolve:!1}),a=new Set(i.outgoing.filter(e=>e.p===`member-of`).map(e=>e.to));for(let n of r)a.has(n)||await On(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await en(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function Hf({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),a=Rf(e.schema),o=e.schema===Yt,s=Bn(e),c=Wn(e)??`markdown`,l=s&&Fn(e),u=e.schema===Nt,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=Bf(e.schema),[m,h]=(0,q.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,q.useState)(String(e.data?.[p]??``)),[v,y]=(0,q.useState)(String(e.data?.content??``)),[b,x]=(0,q.useState)(String(e.data?.description??``)),[S,C]=(0,q.useState)(e.data?.status??`pending`),[w,T]=(0,q.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,q.useState)(e.data?.dueDate?xd(String(e.data.dueDate)):Cd()),O=Mf(Af(e)),[k,ee]=(0,q.useState)(String(e.comment??``)),A=e.metadata?.geo??null,[te,j]=(0,q.useState)(A),M=e.features??e.metadata?.features,[ne,re]=(0,q.useState)(qn(M).length?qn(M):e.data?.tags??[]),N=In(e,t,o),{title:P,content:ie,comment:ae,tags:oe,geo:se,setTitle:ce,setContent:le,setComment:F,setTags:ue,setGeo:de}=o?N:{title:g,content:v,comment:k,tags:ne,geo:te,setTitle:_,setContent:y,setComment:ee,setTags:re,setGeo:j},fe=JSON.stringify(se??null)!==JSON.stringify(A??null),pe=Rn(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Vn,version:e.checksumArray?.[0]??null}),[me,I]=(0,q.useState)(null),L=`${e.id}:${e.checksumArray?.[0]??``}`;s&&pe.text!=null&&me!==L&&(I(L),le(pe.text));let[he,ge]=(0,q.useState)([]),[_e,R]=(0,q.useState)(!1),{replicating:ve,mirror:ye}=G(e);(0,q.useEffect)(()=>{let e=!1;return kt(t).then(t=>{e||ge(t)}).catch(()=>{}),()=>{e=!0}},[t]);let be=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),xe=!_e&&(s?!l&&pe.text!=null&&!pe.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?P.trim().length>0:o?N.canSave:be:!0),Se=async()=>{R(!0);let c=[...(M||[]).filter(e=>!e.startsWith(`tag/`)),...Jn(oe)];try{if(o){await N.save(),n();return}if(s){let i=await Kn(t,e,ie,{comment:ae.trim(),metadata:{features:c,...fe?{geo:se}:{}}});r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n(i);return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:ae.trim(),metadata:{features:c}};if(d){let{type:t,...n}=e.data??{};i.schema=`${Xt}/${O.values.type}`,i.data={...n,...kf(O.values)}}else if(u)i.data={...e.data,...wd({title:P,description:b,status:S,priority:w,due:E})};else if(a){let t=oe.map(e=>e.trim()).filter(Boolean),n;o?n={...P.trim()?{title:P.trim()}:{},content:ie}:(n={...e.data},f&&(n[f]=m.trim()),P.trim()?n[p]=P.trim():delete n[p],n.tags=t),i.data=n}fe&&(i.metadata={...i.metadata??{},geo:se}),await An(t,i),d&&(await Vf(t,e.id,O.values.organizations),hu()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{R(!1)}};return(0,Y.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`edit-url`,children:`URL`}),(0,Y.jsx)(H,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!be&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Y.jsx)(Lf,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Y.jsx)(Cf,{idPrefix:`edit-todo`,title:P,setTitle:ce,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`edit-title`,children:`Title`}),(0,Y.jsx)(H,{id:`edit-title`,value:P,onChange:e=>ce(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{children:`Body`}),l?(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&pe.error?(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:pe.error}):s&&pe.text==null?(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Y.jsx)(Hn,{kind:o?`markdown`:c,value:ie,onChange:le,placeholder:o?`Write your note…`:void 0})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{children:`Tags`}),(0,Y.jsx)(Ml,{tags:oe,onChange:ue,suggestions:he})]}),(0,Y.jsx)(Wl,{value:se,onChange:de}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`edit-comment`,children:`Comment`}),(0,Y.jsx)(`textarea`,{id:`edit-comment`,value:ae,onChange:e=>F(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),o&&(0,Y.jsx)(Gn,{...N,onRetry:N.save}),(0,Y.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Y.jsx)(W,{variant:`outline`,size:`sm`,onClick:()=>n(),disabled:_e,children:o?`Close`:`Cancel`}),(0,Y.jsx)(W,{size:`sm`,onClick:Se,disabled:!xe,children:_e?ve?`Replicating to ${ye.label}…`:`Saving…`:`Save changes`})]})]})}var Uf=(0,q.createContext)(null),Wf={open:()=>{},close:()=>{}};function Gf(){return(0,q.useContext)(Uf)??Wf}var Kf=`main`,qf=(0,q.createContext)(null);function Jf(){return(0,q.useContext)(qf)}var Yf=50;function Xf({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=Gf(),o=nu(),s=Jf(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?Gt(l).title:``,[d,f]=(0,q.useState)(!1),{showErrorToast:p}=Tt(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await bn(t,c):l;s?o.open(n,t):a(n,t)}catch(e){p(e instanceof Error?e.message:`Failed to open document`)}finally{f(!1)}}},h=!e.meta||e.meta.src===`doc`;return(0,Y.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,Y.jsx)(Te,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Y.jsx)(lt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Y.jsx)(wc,{document:l,size:3.5}):null,l?(0,Y.jsx)(`button`,{type:`button`,onClick:()=>void m(),disabled:d,className:`min-w-0 flex-1 truncate text-left hover:underline`,title:u,children:u}):(0,Y.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Y.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!h&&(0,Y.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),h&&(0,Y.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,Y.jsx)(L,{className:`h-3.5 w-3.5`})})]})}function Zf({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Tt(),[i,a]=(0,q.useState)(null),[o,s]=(0,q.useState)(null),[c,l]=(0,q.useState)(!1),[u,d]=(0,q.useState)(!1),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(0),[g,_]=(0,q.useState)(1),v=(0,q.useRef)(0),y=(0,q.useCallback)(()=>{v.current++},[]),b=(0,q.useCallback)(async()=>{let n=++v.current;try{let r=await Qt(t,e.id,{offset:m*Yf,limit:Yf,summary:!0});if(n!==v.current)return;let i=Math.max(0,Math.ceil(Math.max(r.outgoingCount??r.outgoing.length,r.incomingCount??r.incoming.length)/Yf)-1);if(_(i+1),m>i){h(i);return}a(r),s(null)}catch(e){if(n!==v.current)return;s(e instanceof Error?e.message:String(e))}},[t,e.id,m]),x=`${t}:${e.id}`,[S,C]=(0,q.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,q.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(mu,e),()=>{y(),window.removeEventListener(mu,e)}},[b,y]);let w=async(i,a)=>{let o=a===`out`?i.to:i.from;if(o==null)return;let s=`${a}:${i.p}:${o}`;p(s);try{await en(t,e.id,i.p,o,a),n(`Relation removed`),hu()}catch(e){r(e instanceof Error?e.message:`Failed to remove relation`)}finally{p(null)}},T=[{dir:`out`,title:`Points at`,hint:`this document as the subject`,entries:i?.outgoing??[]},{dir:`in`,title:`Pointed at by`,hint:`this document as the object`,entries:i?.incoming??[]}],E=e=>{a(null),h(e)};return(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Y.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Y.jsx)(ze,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Y.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,Y.jsxs)(`div`,{className:`mb-2`,children:[(0,Y.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,Y.jsx)(Xf,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,Y.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Y.jsx)(W,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,Y.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,Y.jsx)(As,{onClose:()=>{u||l(!1)},children:(0,Y.jsx)(Lc,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,tabs:[`relations`],fixedWorkspaceName:t,documentCount:1,saving:u,relationPredicates:i?.predicates,relationExcludeIds:new Set([e.id]),onClose:()=>l(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:i,direction:a,targetIds:o})=>{d(!0);try{await On(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),hu()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var Qf=(0,q.lazy)(()=>s(()=>import(`./SketchEditor-CRJF-Jp4.js`),__vite__mapDeps([9,3,4,10,1,11,12,13,14,15,16,17,18,19,20,21,22,23,24]))),$f=(0,q.lazy)(()=>s(()=>import(`./TextDocumentEditor-BF5NzQ6H.js`),__vite__mapDeps([25,3,4,11,10,13,12,14,15,16,26,1,23]))),ep={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},tp={reply:oe,replyAll:p,forward:ce};function np({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Pn()!=null,{showErrorToast:a}=Tt(),[o,s]=(0,q.useState)(!1),c=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[l,u]=(0,q.useState)(null),d=e.schema===`data/schema/message/email`,f=!i&&(d||[`slack`,`whatsapp`].includes(String(e.data?.platform))),p=d?[`reply`,`replyAll`,`forward`]:[`reply`],m=e=>u(t=>t===e?null:e),h=!i,[g,_]=(0,q.useState)(n&&!i),v=e.schema===qt,[y,b]=(0,q.useState)(!1),x=e.schema===`data/schema/note`||Bn(e),[S,w]=(0,q.useState)(!1),T=`${t}:${e.id}:${n}:${i}`,[E,D]=(0,q.useState)(T);T!==E&&(D(T),_(n&&!i),u(null),s(!1),b(!1),w(!1));let k=t=>{if(!h||!zf(e)||t.defaultPrevented)return!1;let n=t.target;return n instanceof Element&&t.currentTarget.contains(n)&&!n.closest(`a, button, input, textarea, select, label, summary, audio, video, [role="button"], [role="checkbox"], [contenteditable]:not([contenteditable="false"])`)};return g&&h?(0,Y.jsx)(Hf,{document:e,workspaceId:t,onClose:e=>{_(!1),r?.(e)}}):(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[h&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[c&&(0,Y.jsx)(W,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=tp[e];return(0,Y.jsxs)(W,{size:`sm`,variant:l===e?`secondary`:`outline`,onClick:()=>m(e),children:[(0,Y.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),ep[e]]},e)}),e.schema===`data/schema/file`&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>Wt(t,e.id,Ft(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Y.jsx)(Me,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Y.jsx)(C,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>w(!0),children:[(0,Y.jsx)(yt,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Y.jsx)(O,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),y&&h&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Y.jsx)(Qf,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),_(!0)}})}),S&&h&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Y.jsx)($f,{doc:e,workspaceName:t,onSaved:e=>{w(!1),r?.(e)},onClose:()=>w(!1),onDetails:()=>{w(!1),_(!0)}})}),(0,Y.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,onMouseDownCapture:e=>{e.button===0&&e.detail>1&&k(e)&&e.preventDefault()},onDoubleClickCapture:e=>{k(e)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.ownerDocument.getSelection()?.removeAllRanges(),_(!0))},children:[o&&!i?(0,Y.jsx)(af,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,Y.jsx)(Zd,{workspaceId:t,document:e}),l&&f&&(0,Y.jsx)(rf,{workspaceId:t,replyToDocumentId:Number(e.id),mode:l,originalSubject:d&&typeof e.data?.subject==`string`?e.data.subject:void 0,onClose:()=>u(null)},`${e.id}:${l}`)]}),e.comment?.trim()&&(0,Y.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Y.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Y.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var rp=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,ip=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function ap({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Y.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,ip(n.exposureTime)),n&&i(`ISO`,Number.isFinite(n.iso)?n.iso:null),n&&i(`Focal length`,Number.isFinite(n.focalLength)?`${n.focalLength} mm`:null),n&&i(`Captured`,rp(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Y.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function op({document:e}){let t=e.metadata;return(0,Y.jsxs)(`div`,{className:`space-y-6`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Y.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Y.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:rp(e.createdAt)})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:rp(e.updatedAt)})]})]})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Y.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Y.jsx)(ap,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Y.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=up(e.url);return(0,Y.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Y.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),e.status&&e.status!==`available`&&(0,Y.jsx)(`span`,{className:`shrink-0 rounded border px-1 text-xs`,title:e.statusChangedAt,children:e.status===`deleted`?`Deleted`:`Not found`}),r&&(0,Y.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Y.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Y.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Y.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Y.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Y.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Y.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Y.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Y.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function sp({document:e}){let{showSuccessToast:t,showErrorToast:n}=Tt(),r=JSON.stringify(e,null,2);return(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`div`,{className:`flex justify-end`,children:(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Y.jsx)(u,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Y.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function cp({document:e,workspaceId:t}){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,q.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,q.useEffect)(()=>{let n=!1;return $t(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Y.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Y.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Y.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Y.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Y.jsx)(Zf,{document:e,workspaceId:t})]}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function lp(e){return e===`stored`?pt:e===`workspace-file`?ne:e===`imap`?z:e===`readonly`?F:at}function up(e){let t=e.match(/^([a-z][a-z0-9+.-]*):\/\/([^/]*)\/?(.*)$/i);return t?{backend:`${t[1]}://${t[2]}`,key:t[3]}:{backend:e,key:``}}function dp({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),[a,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(null),[l,d]=(0,q.useState)(null),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(null),[g,_]=(0,q.useState)(!1),v=`${t}:${e.id}`,[y,b]=(0,q.useState)(v);v!==y&&(b(v),o(null),c(null),p(null));let x=()=>{Lt(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,q.useEffect)(()=>{let n=!1;return Lt(t,e.id).then(e=>{n||o(e)}).catch(e=>{n||c(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[v]);let S=async(a,o)=>{d(a),p(null);try{let i=await gn(t,[e.id],{urls:[a],...o===void 0?{}:{keepDocument:o}}),s=i.successful[0];if(!s)throw Error(i.failed[0]?.reason||`Destroy failed`);s.docDeleted?r(`Removed from backend; document removed from index`):s.deleted.includes(a)?r(`Removed from backend`):r(`Reference dropped (backend is read-only)`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{d(null)}},C=async(a,o,s)=>{_(!0);try{let i=await kn(t,[e.id],{to:a,mode:o,keepDocument:s.keepDocument,folder:s.folder,filename:s.filename,onConflict:s.onConflict}),c=i.successful[0];if(!c)throw Error(ns(i.failed,new Map([[e.id,Ft(e)||`Document ${e.id}`]]))||`Transfer failed`);let l=c.transfers?.flatMap(e=>e.state===`unchanged`?[]:[e.backend])??[],u=a.join(`, `);o===`delete`?r(`Deleted from ${u}`):l.length===0?r(`Nothing to do — already on ${u}`):r(`${o===`move`?`Moved to`:`Copied to`} ${l.join(`, `)}${c.transfers?.some(e=>e.state===`pending`)?` (pending sync)`:``}`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),h(null),n?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{_(!1)}},w=e=>{if((a?.length??0)<=1){p(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&S(e.url)};if(s)return(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let T=a.length===0,E=Ft(e);return(0,Y.jsxs)(`div`,{className:`space-y-3`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(pt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Y.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Y.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),T?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>h(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Y.jsx)(u,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>h(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,Y.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=lp(n.kind),{backend:a,key:o}=up(n.url),s=l===n.url;return(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Y.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Y.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Y.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,Y.jsx)(`button`,{onClick:()=>Wt(t,e.id,E||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,Y.jsx)(Me,{className:`h-3.5 w-3.5`})}),(0,Y.jsx)(`button`,{onClick:()=>w(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,Y.jsx)(L,{className:`h-3.5 w-3.5`})})]})]}),f===n.url&&(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Y.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Y.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Y.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Y.jsx)(W,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!1),children:`Also remove index entry`}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Y.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>p(null),children:`Cancel`})]})]})]},n.url)}),m&&(0,lo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Y.jsx)(Ql,{workspaceId:t,documentCount:1,initialMode:m,defaultFilename:E,saving:g,onConfirm:C,onClose:()=>{g||h(null)}})}),window.document.body)]})}function fp(e){let t=e.metadata?.geo,n=t?.lat,r=t?.lon;if(n==null||r==null||n===``||r===``)return null;let i=Number(n),a=Number(r);return!Number.isFinite(i)||!Number.isFinite(a)||i===0&&a===0?null:{lat:i,lon:a}}function pp(e,t,n){let r=!1;for(let i=0,a=n.length-1;i<n.length;a=i++){let o=n[i].lat,s=n[i].lon,c=n[a].lat,l=n[a].lon;o>e!=c>e&&t<(l-s)*(e-o)/(c-o)+s&&(r=!r)}return r}function mp(e,t,n){if(n.kind===`rect`){let r=n.bbox;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLon&&t<=r.maxLon}return n.points.length>=3&&pp(e,t,n.points)}function hp(e,t,n=!1){let r=fp(e);return r?mp(r.lat,r.lon,t):n}var gp=(0,q.lazy)(()=>s(()=>import(`./LocationTab-BONJQfYM.js`),__vite__mapDeps([27,3,4,28,29]))),_p=[{id:`view`,label:`View`,icon:dt},{id:`location`,label:`Location`,icon:Ie},{id:`metadata`,label:`Metadata`,icon:d},{id:`json`,label:`JSON`,icon:ge},{id:`synapses`,label:`Synapses`,icon:Qe},{id:`backends`,label:`Backends`,icon:pt}];function vp({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1,navigation:s,tabActions:c,onTabChange:l}){let u=Pn()!=null,d=fp(e),f=_p.filter(e=>(e.id!==`location`||d!==null)&&(!u||![`synapses`,`backends`].includes(e.id))),[p,m]=(0,q.useState)(n),h=`${e.id}:${n}`,[g,_]=(0,q.useState)(h);h!==g&&(_(h),m(n));let v=f.some(e=>e.id===p)?p:`view`,y=e=>{m(e),l?.(e)},b=o&&!!c&&!s,x=(0,Y.jsx)(`div`,{className:V(b&&`document-detail-header shrink-0 border-b-[3px] bg-muted`),children:(0,Y.jsxs)(`div`,{className:V(`flex min-w-0 items-center`,b&&`mx-auto h-[calc(3rem-4px)] w-full max-w-[var(--document-reading-width,100%)] gap-1 pl-2 pr-2 sm:pl-4`),children:[(0,Y.jsx)(ku,{tabs:f,active:v,onChange:y,className:V(`min-w-0 flex-1 px-1`,b&&`h-full border-b-0 px-0 max-sm:gap-0 max-sm:[&>button]:px-2.5`),iconOnly:o}),c]})});return(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[s?(0,Y.jsx)(Ou,{...s,tabs:x,section:v,onDocument:()=>y(`view`),onSection:()=>y(`view`),onBack:v===`view`?s.onBack:()=>y(`view`)}):x,(0,Y.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,Y.jsxs)(`div`,{className:`mx-auto h-full w-full max-w-[var(--document-reading-width,100%)] p-4`,children:[v===`view`&&(0,Y.jsx)(np,{document:e,workspaceId:t,initialEdit:r&&!u,onChanged:i}),v===`location`&&d&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Y.jsx)(gp,{lat:d.lat,lon:d.lon})}),v===`metadata`&&(0,Y.jsx)(op,{document:e,workspaceId:t}),v===`json`&&(0,Y.jsx)(sp,{document:e,workspaceId:t}),v===`synapses`&&!u&&(0,Y.jsx)(cp,{document:e,workspaceId:t}),v===`backends`&&!u&&(0,Y.jsx)(dp,{document:e,workspaceId:t,onChanged:i})]})})]})}function yp(e,t){let[n,r]=(0,q.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,q.useState)(a);a!==o&&(s(a),r(null));let c=(0,q.useRef)(a),l=(0,q.useRef)(0);(0,q.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,q.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}bn(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}function bp(e){let t=wu(),n=(0,q.useContext)(eu),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,q.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Y.jsx)(xp,{...e})}function xp({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,q.useState)(!1),c=tr(),{document:l,refresh:u}=yp(r,e);if(ps(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,lo.createPortal)((0,Y.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:V(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,Y.jsxs)(`div`,{className:V(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-(--panel-radius) md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-(--panel-radius)`),onClick:e=>e.stopPropagation(),children:[(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:Gt(l).title}),(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=jt(l);return e?(0,Y.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,Y.jsx)(Ae,{className:`h-4 w-4`})}):null})(),(0,Y.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,Y.jsx)(ve,{className:`h-4 w-4`}):(0,Y.jsx)(qe,{className:`h-4 w-4`})}),(0,Y.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Y.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Y.jsx)(gu.Provider,{value:()=>s(e=>!e),children:(0,Y.jsx)(vp,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Sp={sortBy:`content`,order:`desc`};function Cp(e){return e?.sortBy===`crud:deleted`?{...Sp}:{sortBy:e?.sortBy??Sp.sortBy,order:e?.order??Sp.order}}var wp={features:{allOf:[],anyOf:[],noneOf:[]},timeline:{quickFilter:null,customRanges:[],indexCreated:!0,indexUpdated:!0,indexDeleted:!1,contentEvents:!1,selectedTimelines:[]},geo:{bbox:null,includeUnlocated:!1},lens:{gps:null,ids:null},sort:{...Sp}};function Tp(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function Ep(e,t=!1){if(!e.gps)return[];let{lat:n,lon:r,radiusM:i}=e.gps;return[`geo:near:${n},${r},${Math.max(1,Math.round(i))}m`,...t?[`geo:missing`]:[]]}function Dp(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function Op(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Dp(e),c=s.length>0?s.map(e=>`${e.start}..${e.end}`):t?[t]:[];if(c.length===0)return[];let l=[];return n&&l.push(`crud:created`),r&&l.push(`crud:updated`),i&&l.push(`crud:deleted`),a&&l.push(`content`),l.push(...o),l.flatMap(e=>c.map(t=>`t:${e}:${t}`))}function kp(e,t,n=[]){return{features:e.features,filters:[...Op(e.timeline),...Tp(e.geo),...Ep(e.lens,e.geo.includeUnlocated)],queryOptions:{ids:e.lens.ids,sortBy:e.sort.sortBy,order:e.sort.order,queries:n,geoSelection:t,includeUnlocated:e.geo.includeUnlocated??!1}}}var Ap=Sp,jp={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function Mp(e){return jp[e]??e}function Np(e){let[t,n]=(0,q.useState)([]);return(0,q.useEffect)(()=>{let t=!1;return hn(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,q.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:Mp(e)})),[t])}function Pp({workspaceId:e,value:t,onChange:n}){let r=Np(e);return(0,Y.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Y.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value,order:[`alphabetical`,`type`].includes(e.target.value)?`asc`:t.order}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by`,"aria-label":`Sort by`,children:[t.sortBy!==`crud:deleted`&&!r.some(e=>e.value===t.sortBy)&&(0,Y.jsx)(`option`,{value:t.sortBy,children:Mp(t.sortBy)}),r.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending`:`Descending`,"aria-label":t.order===`asc`?`Ascending`:`Descending`,className:`flex h-7 w-7 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent hover:text-foreground touch-target`,children:t.order===`asc`?(0,Y.jsx)(Se,{className:`h-3.5 w-3.5`}):(0,Y.jsx)(ke,{className:`h-3.5 w-3.5`})})]})}function Fp(e,t){let n=t?.replace(/^t:/,``)||`crud:created`,r=(n===`crud:created`?[e.createdAt]:n===`crud:updated`?[e.updatedAt]:(e.timelines??[]).filter(e=>(e.timeline||e.name)===n).map(e=>e.start)).map(e=>Date.parse(e??``)).filter(Number.isFinite);if(r.length)return Math.min(...r);let i=n===`content`?Date.parse(e.createdAt??``):NaN;return Number.isFinite(i)?i:null}var Ip={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},Lp=e=>e*1e6;function Rp(){try{let e=new Intl.Locale(navigator.language),t=(typeof e.getWeekInfo==`function`?e.getWeekInfo():e.weekInfo)?.firstDay;if(typeof t==`number`&&t>=1&&t<=7)return t}catch{}return 1}function zp(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Bp(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=zp(e);return r.setDate(r.getDate()-n),r}var Vp=864e5;function Hp(e){let t=Rp(),n=zp(e),r=Bp(e,t);return{today:n.getTime(),yesterday:n.getTime()-Vp,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*Vp,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function Up(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:Lp(Ip.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:Lp(Ip.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:Lp(Ip.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:Lp(Ip.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:Lp(Ip.lastWeek)};let n=new Date(e),r=n.getFullYear()*12+n.getMonth();if(r===t.month)return{key:`this-month`,label:`Earlier this month`,rank:Lp(Ip.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:Lp(Ip.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:Lp(Ip.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:Lp(Ip.year)+i}}function Wp(e,t,n=`desc`,r=new Date){let i=Hp(r),a=new Map;for(let n of e){let e=Up(t(n),i),r=a.get(e.key);r?r.items.push(n):a.set(e.key,{...e,items:[n]})}let o=[...a.values()].sort((e,t)=>n===`asc`?e.rank-t.rank:t.rank-e.rank),s=o.filter(e=>e.key===`unknown`);return s.length?[...o.filter(e=>e.key!==`unknown`),...s]:o}function Gp(e,t){let n=t.split(`/`).filter(Boolean);if(e!==`backends`||n[0]!==`Trash`)return null;try{return{backend:n[1]?decodeURIComponent(n[1]):null,prefix:n.slice(2).join(`/`)}}catch{return null}}function Kp(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function qp(e,t=``){let n=new Map,r=[],i=t?`${t}/`:``;for(let t of e){if(!t.key.startsWith(i))continue;let e=t.key.slice(i.length);if(!e)continue;let a=e.indexOf(`/`);if(a>=0){let r=e.slice(0,a),o=i+r,s=n.get(o)??{id:`folder:${o}`,name:r,key:o,directory:!0,navigable:!0,items:[]};s.items.push(t),n.set(o,s)}else r.push({id:t.id,name:e,key:t.key,directory:t.type===`directory`,navigable:!1,items:[t]})}return[...n.values(),...r].sort((e,t)=>Number(t.directory)-Number(e.directory)||e.name.localeCompare(t.name)||t.items[0].deletedAt-e.items[0].deletedAt||e.id.localeCompare(t.id))}var Jp=(e,t)=>`${bt.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Yp(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await U.get(`${Jp(e,t)}?${o}`);if(n.push(...s.items),a=s.retention?.days??null,i=s.cursor,i&&r.has(i))throw Error(`Trash listing returned a repeated cursor`);i&&r.add(i)}while(i);return{items:n,days:a}}function Xp(e,t,n){return Qp(e,t,n,`restore`)}function Zp(e,t,n){return Qp(e,t,n,`discard`)}async function Qp(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await U.post(`${Jp(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{ln(e,`backends`),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:`backends`}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e,backend:t}}))}}async function $p(e,t){let n=Gp(`backends`,t);if(!n?.backend)return;let{items:r}=await Yp(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`)).sort((e,t)=>t.deletedAt-e.deletedAt),a=await Xp(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} restored; ${o.length} remain in Trash. Existing paths were kept.`)}function em(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
|
|
19
19
|
`)+(n.length>5?`\n…and ${n.length-5} more paths`:``);return window.confirm(`Permanently delete ${t.length} Trash item(s) from ${e}?\n\n${r}\n\nDeleted folders include all their contents. This cannot be undone. Files currently at the original paths are kept.`)}async function tm(e,t){let n=Gp(`backends`,t);if(!n?.backend)return;let{items:r}=await Yp(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!em(n.backend,i))return;let a=await Zp(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} deleted; ${o.length} remain in Trash. ${o[0].message||o[0].reason||`Please retry.`}`)}function nm(){let{showProgress:e}=wt();return(0,q.useCallback)(async(t,n,r,i)=>{let a=e({title:t,description:n});try{let e=await i();if(e===!1)throw Error(`The operation could not be completed.`);return a.done({title:r,description:n}),e}catch(e){throw a.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}},[e])}var rm=new Map;function im(e,t,n,r,i){let a=JSON.stringify([t,n,r]),o=rm.get(a);if(o)return o;let s=(async()=>{let a=e({title:`Resyncing…`,description:r});try{for(await dn(t,n,r);;){let e=await Zt(t,n,r);if(i?.(e),!e.resyncing&&e.status!==`syncing`){if(e.lastError)throw Error(e.lastError);a.done({title:e.resyncCancelledAt?`Resync stopped`:`Resync complete`,description:`${r}${e.progress?` · ${e.progress.scanned} files scanned`:``}`}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t,treeName:`backends`}}));return}let o=e.progress;a.update({title:`Resyncing…`,description:`${r}${o?` · ${o.scanned}${o.total==null?``:` / ${o.total}`} files scanned`:``}`}),await new Promise(e=>setTimeout(e,2e3))}}catch(e){throw a.fail({title:`Resync needs attention`,description:`${r}: ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return rm.set(a,s),s.finally(()=>{rm.get(a)===s&&rm.delete(a)}).catch(()=>{}),s}var am=[`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.path.locked`,`tree.path.unlocked`,`tree.layer.updated`,`tree.layer.converted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`,`context.path.changed`,`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`],om=new Map;function sm(e,t,n){ln(e,t),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t,cacheInvalidated:!0}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}function cm(e,t){let n=om.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=am.map(n=>{let a=(a={})=>{if(n===`backend.resync.changed`&&a.resyncing!==!1)return;let o=typeof a.workspaceId==`string`?a.workspaceId:null,s=typeof a.workspaceName==`string`?a.workspaceName:null;if(o&&!t.has(o)||!o&&s&&s!==e)return;let c=typeof a.treeName==`string`?a.treeName:void 0;n===`tree.renamed`?c=void 0:n===`context.path.changed`?c??=`context`:[`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`].includes(n)&&(c??=`backends`),r.add(c),!i&&(i=setTimeout(()=>{i=void 0;let t=r.has(void 0)?[void 0]:[...r];r.clear();for(let n of t)ln(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return mo.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)ln(e,t);a.forEach(([e,t])=>mo.off(e,t))}},om.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),om.delete(e))}}function lm({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=nm(),{showProgress:a}=wt(),o=n||`context`,c=o===`directory`,l=(0,q.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),u=(0,q.useCallback)(async(n,r=!0)=>{let i;if(e)i=await or(e,n,r);else if(t)i=await fn(t,n,r,o);else return!1;let a=ac(n);if(i&&a)try{e?await er(e,n,a):t&&await At(t,n,a,o)}catch{}return l(),i},[e,t,o,l]),d=(0,q.useCallback)(async(n,r=!1,a=!1,s=!1)=>i(s?`Destroying…`:a?`Purging…`:`Removing…`,n,s?`Destroyed`:a?`Purged`:`Removed`,async()=>{try{return e?await $n(e,n,r):t?await Dt(t,n,r,o,a,s):!1}finally{l()}}),[e,t,o,l,i]),f=(0,q.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await Qn(e,n,t.join(`/`),!1)}else if(t)i=await At(t,n,{name:r},o);else return!1;return l(),i},[e,t,o,l]),p=(0,q.useCallback)(async(n,r,a=!1,s=o,c=o,u={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await Qn(e,n,r,a,u);else if(t)i=await Nn(t,n,r,a,s,c,u);else return!1;return l(),i}),[e,t,o,l,i]),m=(0,q.useCallback)(async n=>{let r;if(e)r=await nr(e,n);else if(t)r=await It(t,n,o);else return null;return l(),r},[e,t,o,l]),h=(0,q.useCallback)(async n=>{let r;if(e)r=await Zn(e,n);else if(t)r=await xn(t,n,o);else return null;return l(),r},[e,t,o,l]),g=(0,q.useCallback)(async(n,r,a=!1,s=o,c=o)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await ir(e,n,r,a);else if(t)i=await K(t,n,r,a,s,c);else return!1;return l(),i}),[e,t,o,l,i]),_=(0,q.useCallback)(async(n,r)=>e?await er(e,n,r):t?await At(t,n,r,o):!1,[e,t,o]),v=(0,q.useCallback)(async(n,r)=>{let i;if(e)i=await sr(e,n,r);else if(t)i=await Ht(t,n,r,o);else return null;return l(),i},[e,t,o,l]),y=(0,q.useCallback)(async(n,r)=>{let i;if(e)i=await rr(e,n,r);else if(t)i=await yn(t,n,r,o);else return null;return l(),i},[e,t,o,l]),b=(0,q.useCallback)(async e=>{if(!t)return!1;let n=await Mt(t,e,t,o);return l(300),n},[t,o,l]),x=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;try{await nn(t,e,n??t,o)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return l(300),!0},[t,o,l]),S=(0,q.useCallback)(async e=>{if(!t)return!1;let n=await Ot(t,e,o);return l(),n},[t,o,l]),C=(0,q.useCallback)(async e=>{if(!t)return!1;let n=await rn(t).catch(()=>[]),r=Tn(e,n);return r?(await im(a,t,r.driver,r.address),l(300),!0):!1},[t,l,a]),w=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;let r=await rn(t).catch(()=>[]),i=an(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await tn(t,i.driver,i.address,[a]),l(200),!0},[t,l]),T=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;let r=await rn(t).catch(()=>[]),i=an(e,r);return!i||!i.key?!1:(await cn(t,i.driver,i.address,i.key,n),l(200),!0)},[t,l]),E=(0,q.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await rn(t),r=Dn(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await zt(t,r.driver,r.address,r.key),!0}finally{l(200)}}):!1,[t,l,i]),D=(0,q.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await s(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-CSjPDp4d.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([30,3,4,10,11,13,12,14]));r({mode:e,path:n,workspaceId:t,treeName:o,onImported:()=>{sm(t,o),l()}})},[t,o,l]),O=(0,q.useCallback)(async(e,n)=>{if(!t)return;let r=await s(()=>Promise.resolve().then(()=>dm),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await sn(t,n,e,o,Mn(o))).length!==e.length)throw Error(`Some documents could not be imported`);return sm(t,o),l(),!0});else{let e=[];for(let r=0;;){let i=await pn(t,n,[],{treeName:o,treeType:Mn(o),limit:500,offset:r,order:`asc`}),a=i.payload||[];if(e.push(...a),r+=a.length,!a.length||r>=(i.totalCount??i.count??1/0))break}r.showDocumentExport(e)}},[t,o,l]);return{onImportDocuments:t&&o!==`backends`?e=>O(`import`,e):void 0,onExportDocuments:t?e=>O(`export`,e):void 0,onInsertPath:u,onRemovePath:d,onRenamePath:f,onMovePath:p,onCopyPath:g,onExportSubtree:t?e=>D(`export`,e):void 0,onImportSubtree:t&&o!==`backends`?e=>D(`import`,e):void 0,onUpdateNode:_,onMergeLayer:v,onSubtractLayer:y,onMergeDown:c?void 0:m,onSubtractDown:c?void 0:h,onLockLayer:t?b:void 0,onUnlockLayer:t?x:void 0,onDestroyLayer:t&&!c?S:void 0,onResyncBackend:t?C:void 0,onCreateBackendFolder:t?w:void 0,onRenameBackendFolder:t?T:void 0,onDeleteBackendFolder:t?E:void 0}}function um({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let d=Pi(),f=lm({workspaceId:n,treeName:r}),p=r===`backends`,h=p?an(i):null,[g,_]=(0,q.useState)([]);(0,q.useEffect)(()=>{if(!p)return;let e=!1;return rn(n).then(t=>{e||_(t)}).catch(()=>{}),()=>{e=!0}},[n,p]);let v=p?Dn(i,g):null,y=i.split(`/`).filter(Boolean).pop()||i,[b,x]=(0,q.useState)(void 0);(0,q.useEffect)(()=>{let e=!1;return Ut(n).then(t=>{e||x(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||x(null)}),()=>{e=!0}},[n,r,i]);let S=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},C=(e,t,n,r=!1)=>(0,Y.jsxs)(`button`,{type:`button`,className:V(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>S(n),children:[e,t]}),w=(0,Y.jsx)(`div`,{className:`my-1 h-px bg-border`}),T=e=>{let t=p?(()=>{let t=Mo(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:Po(i)};d(`/workspaces/${n}/settings/hooks?${No(t).toString()}`)},E=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},D=Gp(r,i);return D?(0,Y.jsxs)(js,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,Y.jsx)(L,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),D.backend&&C((0,Y.jsx)(ht,{className:`h-3 w-3`}),`Restore original paths`,()=>$p(n,i)),D.backend&&C((0,Y.jsx)(L,{className:`h-3 w-3`}),`Empty Trash`,()=>tm(n,i),!0)]}):(0,Y.jsxs)(js,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,Y.jsx)(he,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&C((0,Y.jsx)(dt,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),w,p?h&&(0,Y.jsxs)(Y.Fragment,{children:[C((0,Y.jsx)(ze,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=E(`New folder name:`);e&&await f.onCreateBackendFolder?.(i,e)}),h.key&&C((0,Y.jsx)(N,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=E(`New folder name:`,y);e&&await f.onRenameBackendFolder?.(i,e)}),C((0,Y.jsx)(ne,{className:`w-3 h-3`}),`Create storage rule…`,()=>T(`store`))]}):(0,Y.jsxs)(Y.Fragment,{children:[C((0,Y.jsx)(ze,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=E(`New folder name:`);e&&await f.onInsertPath(`${i===`/`?``:i}/${e}`)}),C((0,Y.jsx)(N,{className:`w-3 h-3`}),`Rename`,async()=>{let e=E(`New name:`,y);e&&await f.onRenamePath(i,e)}),C((0,Y.jsx)(ne,{className:`w-3 h-3`}),`Create rule…`,()=>T(`store`)),C((0,Y.jsx)(Me,{className:`w-3 h-3`}),`Create download rule…`,()=>T(`download`))]}),b!==void 0&&C(b?(0,Y.jsx)(m,{className:`w-3 h-3`}):(0,Y.jsx)(te,{className:`w-3 h-3`}),b?`Unpin`:`Pin`,async()=>{b?await jn(n,b.id):await Pt(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),w,f.onImportDocuments&&C((0,Y.jsx)(ze,{className:`w-3 h-3`}),`Import documents…`,()=>f.onImportDocuments(i)),f.onExportDocuments&&C((0,Y.jsx)(Me,{className:`w-3 h-3`}),`Export documents…`,()=>f.onExportDocuments(i)),C((0,Y.jsx)(u,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!p&&l&&c&&c.length>0&&C((0,Y.jsx)(A,{className:`w-3 h-3`}),`Paste ${c.length} document(s)`,()=>l(i,c)),p?v&&(0,Y.jsxs)(Y.Fragment,{children:[w,C((0,Y.jsx)(L,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${y}" and its contents from the backend?`)&&await f.onDeleteBackendFolder?.(i)},!0)]}):(0,Y.jsxs)(Y.Fragment,{children:[w,C((0,Y.jsx)(L,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await f.onRemovePath(i,!0)},!0)]})]})}var dm=t({DocumentList:()=>Im,default:()=>Im,showDocumentExport:()=>Rm,showDocumentImport:()=>Lm});function fm({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,q.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map(ru),l=JSON.stringify(c,null,2),d=async()=>{try{await navigator.clipboard.writeText(l),a(`copied`),setTimeout(()=>a(`idle`),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e),a(`error`),setTimeout(()=>a(`idle`),2e3)}};return(0,Y.jsx)(ms,{label:`Export Documents`,onClose:o,children:(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,Y.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,Y.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,Y.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,Y.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Y.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,Y.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,Y.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,Y.jsxs)(W,{onClick:d,size:`sm`,className:`flex items-center gap-2`,children:[(0,Y.jsx)(u,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,Y.jsx)(`textarea`,{className:`w-full min-h-24 flex-1 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&d()}},onFocus:e=>e.target.select()})]})}),(0,Y.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-end gap-2`,children:[(0,Y.jsx)(W,{variant:`outline`,onClick:()=>{let e=URL.createObjectURL(new Blob([l],{type:`application/json`})),t=window.document.createElement(`a`);t.href=e,t.download=`canvas-documents.json`,t.click(),setTimeout(()=>URL.revokeObjectURL(e),1e3)},children:`Download JSON`}),(0,Y.jsx)(W,{onClick:o,children:`Close`})]})]})})}function pm({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,q.useState)(``),[a,o]=(0,q.useState)(!1),[s,c]=(0,q.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e||typeof e!=`object`||!e.schema||!e.data){c(`Each document must have "schema" and "data" fields`);return}o(!0),await n(a)?(i(``),t()):c(`Failed to import documents`)}catch(e){c(e instanceof Error?e.message:`Import failed`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,lo.createPortal)((0,Y.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Y.jsx)(`div`,{className:`bg-background border rounded-(--panel-radius) max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Y.jsxs)(`div`,{className:`p-6`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,Y.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data or choose a document export file`})]}),(0,Y.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,Y.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),className:`w-full h-64 p-3 border rounded-lg font-mono text-sm`,placeholder:`[{"schema": "data/schema/tab", "schemaVersion": "2.0", "data": {...}, "metadata": {...}}]`,disabled:a,autoFocus:!0})]}),s&&(0,Y.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,Y.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,Y.jsxs)(`p`,{children:[(0,Y.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,Y.jsxs)(`p`,{children:[(0,Y.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,Y.jsxs)(`label`,{className:`mt-4 block text-sm`,children:[`Import JSON file`,(0,Y.jsx)(`input`,{type:`file`,accept:`.json,application/json`,disabled:a,className:`mt-2 block w-full text-sm`,onChange:e=>{let t=e.target.files?.[0];t&&t.text().then(e=>{i(e),c(null)}).catch(e=>c(String(e)))}})]}),(0,Y.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,Y.jsx)(W,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,Y.jsx)(W,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function mm({document:e}){let{replicating:t,label:n}=G(e);return t?(0,Y.jsxs)(`span`,{role:`status`,className:`inline-flex shrink-0 items-center gap-1 rounded-full border bg-muted/60 px-2 py-0.5 text-[11px] font-normal text-muted-foreground`,children:[(0,Y.jsx)(ut,{className:`h-3 w-3 animate-spin`}),n]}):null}function hm(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Bs(e.currentTarget,`inside`)}function gm({documentId:e,onOpenActions:t,className:n}){return t?(0,Y.jsx)(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),t(n.currentTarget,e)},className:`rounded-sm p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground ${n??``}`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,Y.jsx)(Pe,{className:`h-4 w-4`})}):null}function _m(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function vm({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=is(),[c,l]=(0,q.useState)(!1),{replicating:u}=G(e),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=Gt(e),m=bm(e),h=m||Sm(e),{blobUrl:g}=Ju(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),_=t=>{o?.(t,e.id)},v=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),y=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),b=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},x=e=>{e.shiftKey&&e.preventDefault()},S=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(cu,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>_m(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring transition-opacity ${u?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:b,onMouseDown:x,...s,onContextMenu:S,draggable:!0,onDragStart:_,children:[(0,Y.jsx)(uu,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,Y.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:!!t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}})}),(0,Y.jsx)(uu,{className:`w-12`,children:g?(0,Y.jsx)(`img`,{src:g,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,Y.jsx)(wc,{document:e,chip:!0})}),(0,Y.jsx)(uu,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),p.isExternal&&(0,Y.jsx)(Ae,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Y.jsx)(mm,{document:e})]}),p.subtitle&&(0,Y.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,Y.jsx)(uu,{className:`hidden md:table-cell`,children:(0,Y.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:p.schemaLabel})}),(0,Y.jsx)(uu,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,Y.jsx)(uu,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:y&&(0,Y.jsx)(`span`,{className:`font-mono`,title:`${y.algo} checksum`,children:y.hash})}),(0,Y.jsx)(uu,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,Y.jsx)(uu,{className:`w-12 text-right`,children:(0,Y.jsx)(gm,{documentId:e.id,onOpenActions:a})})]}),(0,Y.jsx)(bp,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function ym({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=is(),[c,l]=(0,q.useState)(!1),u=e.schema===`data/schema/tab`,{replicating:d}=G(e),f=u?e.data.url:null,p=Gt(e),m=bm(e),h=m||Sm(e),{blobUrl:g,loading:_}=Ju(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),v=t=>{o?.(t,e.id)},y=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),b=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),x=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},S=e=>{e.shiftKey&&e.preventDefault()},C=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>_m(n,()=>u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${d?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${u&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:x,onMouseDown:S,...s,onContextMenu:C,draggable:!0,onDragStart:v,children:(0,Y.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[h&&(0,Y.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:g?(0,Y.jsx)(`img`,{src:g,alt:p.title,loading:`lazy`,className:`h-full w-full object-cover`}):_?(0,Y.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,Y.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Y.jsx)(wc,{document:e})})}),(0,Y.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,Y.jsx)(wc,{document:e,chip:!0}),(0,Y.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:p.title,children:p.title}),p.isExternal&&(0,Y.jsx)(Ae,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Y.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:p.schemaLabel}),(0,Y.jsx)(mm,{document:e})]}),p.subtitle&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:p.subtitle,children:p.subtitle}),p.preview&&(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:p.preview}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Y.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),b&&(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(E,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{className:`font-mono`,title:`${b.algo} checksum`,children:b.hash})]}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(me,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{title:`Created: ${y(e.createdAt)}`,children:y(e.createdAt)})]})]})]}),(0,Y.jsx)(gm,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,Y.jsx)(bp,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function bm(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function xm(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function Sm(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Cm({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Un(e,t),[a,o]=(0,q.useState)(!1);return i||a?(0,Y.jsx)(Y.Fragment,{children:n}):r?(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,Y.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,Y.jsx)(ee,{className:`h-3.5 w-3.5`})})]}):(0,Y.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function wm({document:e,workspaceId:t,markdown:n}){let r=(0,q.useRef)(null),[i,a]=(0,q.useState)(()=>typeof IntersectionObserver>`u`);(0,q.useEffect)(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(a(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let{text:o,loading:s,error:c}=Rn(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,Y.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,Y.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,Y.jsx)(rd,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,Y.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,Y.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,Y.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,Y.jsx)(wc,{document:e,size:10,chip:!0}),i&&s&&(0,Y.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function Tm({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let c=is(),[l,u]=(0,q.useState)(!1),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=bm(e),m=xm(e),h=p||Sm(e),g=Gt(e),_=Vt(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||Ft(e)),v=e.schema===`data/schema/file`&&(_===`markdown`||_===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,y=!h&&e.schema!==`data/schema/file`&&!!(g.preview||g.subtitle),{replicating:b}=G(e),{blobUrl:x,loading:S}=Ju(n??``,e.id,768,{enabled:h,blobFallback:p,version:e.checksumArray?.[0]??null}),C=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&r(e.id,!i||!t,i),i||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0))},w=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>_m(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0),()=>r?.(e.id,!t,!0)),className:`group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-(--card-radius) border transition cursor-pointer outline-none hover:shadow-elevation-2 focus-visible:ring-2 focus-visible:ring-ring ${b?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:C,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...c,onContextMenu:w,draggable:!0,onDragStart:t=>s?.(t,e.id),title:g.title,children:[(0,Y.jsx)(`input`,{type:`checkbox`,className:`absolute left-2 top-2 z-10 h-4 w-4 cursor-pointer accent-primary ${t?``:`reveal-on-hover`}`,checked:t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}}),(0,Y.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${h&&x||y||v&&n||m&&n?``:`aspect-square`}`,children:[h&&S&&(0,Y.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),h&&x?(0,Y.jsx)(`img`,{src:x,alt:g.title,loading:`lazy`,className:`block h-auto w-full`}):m&&n?(0,Y.jsx)(Cm,{workspaceId:n,documentId:e.id,fallback:(0,Y.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,Y.jsx)(wc,{document:e,size:10,chip:!0})})}):v&&n?(0,Y.jsx)(wm,{document:e,workspaceId:n,markdown:_===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):y?(0,Y.jsxs)(`div`,{className:`flex min-h-28 w-full flex-col gap-1.5 overflow-hidden bg-card p-3 pt-7 text-left`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Y.jsx)(wc,{document:e}),(0,Y.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:g.schemaLabel})]}),(0,Y.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:g.title}),g.subtitle&&(0,Y.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:g.subtitle}),(0,Y.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:g.preview})]}):(0,Y.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Y.jsx)(wc,{document:e,size:10,chip:!0})}),(0,Y.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,Y.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Open to the side`,children:(0,Y.jsx)(de,{className:`h-3.5 w-3.5`})}),o&&(0,Y.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(t.currentTarget,e.id)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,Y.jsx)(Pe,{className:`h-3.5 w-3.5`})})]})]}),!y&&(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,Y.jsx)(`span`,{className:`truncate text-xs font-medium`,title:g.title,children:g.title}),g.isExternal&&(0,Y.jsx)(Ae,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,Y.jsx)(bp,{document:e,isOpen:l,onClose:()=>u(!1),workspaceId:n})]})}function Em(e,t,n,r,i){let[a,o]=(0,q.useState)(!1),s=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:a,onDragOver:e=>{!t||!s(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,a||o(!0))},onDragLeave:()=>o(!1),onDrop:async a=>{if(o(!1),!t||!s(a))return;a.preventDefault(),a.stopPropagation();let c=null;try{c=JSON.parse(a.dataTransfer.getData(`application/json`))}catch{c=null}if(!(c?.type!==`document`||!Array.isArray(c.documentIds)||c.documentIds.length===0)&&!ql(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function Dm(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function Om({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,Y.jsx)(gt,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,Y.jsx)(pe,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var km=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function Am({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Em(e,r,i,a,o);return(0,Y.jsxs)(`button`,{type:`button`,title:km(e),onClick:()=>t?.(e.path),onContextMenu:t=>Dm(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 max-w-full items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm transition-colors hover:bg-accent ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Y.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,Y.jsx)(Om,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,Y.jsx)(gt,{className:`hidden h-4 w-4 group-hover:block`}):(0,Y.jsx)(he,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,Y.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Y.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function jm({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Em(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,Y.jsxs)(`button`,{type:`button`,title:km(e),onClick:()=>t?.(e.path),onContextMenu:t=>Dm(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-(--card-radius) border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Y.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,Y.jsx)(gt,{className:`h-10 w-10`,strokeWidth:1.5}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(pe,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,Y.jsx)(he,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c})]})}),(0,Y.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Y.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function Mm({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,Y.jsx)(`div`,{className:`mb-4 grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Y.jsx)(jm,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function Nm({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,Y.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Y.jsx)(Am,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function Pm({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Em(e,r,i,a,o);return(0,Y.jsxs)(cu,{"data-selection-ignore":``,className:`cursor-pointer ${s.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:t=>Dm(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:km(e),children:[(0,Y.jsx)(uu,{className:`w-10`}),(0,Y.jsx)(uu,{className:`w-12`,children:(0,Y.jsx)(Om,{folder:e})}),(0,Y.jsx)(uu,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,Y.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,Y.jsx)(uu,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,Y.jsx)(uu,{className:`hidden lg:table-cell`}),(0,Y.jsx)(uu,{className:`hidden lg:table-cell`}),(0,Y.jsx)(uu,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,Y.jsx)(uu,{className:`w-12 md:w-auto`})]})}function Fm({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,Y.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-1 mb-2 flex items-center gap-2 bg-background/95 px-1 py-1.5 backdrop-blur-sm`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 cursor-pointer accent-primary ${r||i?``:`reveal-on-hover`}`,checked:r,ref:e=>{e&&(e.indeterminate=i&&!r)},onChange:e=>o(e.target.checked),title:`Select everything in "${e}"`,onClick:e=>e.stopPropagation()}),(0,Y.jsxs)(`button`,{type:`button`,onClick:a,"aria-expanded":!n,className:`flex min-w-0 items-center gap-1.5 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,Y.jsx)(vt,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,Y.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,Y.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function Im({externalSearchQuery:e,toolbarActions:t,documents:n,isLoading:r,contextPath:i,treeName:a,workspaceId:o,totalCount:s,onRemoveDocument:d,onDeleteDocument:f,onDestroyDocument:p,onRemoveDocuments:m,onDeleteDocuments:h,onDestroyDocuments:v,onCopyDocuments:y,onCutDocuments:b,onPasteDocuments:x,onImportDocuments:S,onSelectionChange:C,pastedDocumentIds:w,viewMode:E=`card`,allowViewToggle:k=!1,activeContextUrl:ee,currentContextUrl:te,currentPage:j=1,pageSize:M=50,onPageChange:N,onPageSizeChange:P,onPurgeDocuments:ae,disablePurgeDocuments:oe=!1,backendSearchQueries:se=[],onBackendSearch:ce,onRemoveBackendQuery:le,serverSort:ue,onServerSortChange:pe,scope:me=`path`,onScopeChange:I,canSaveChanges:he=!1,isSavingChanges:ge=!1,onSaveChanges:_e,linkTree:R,folders:ve,onOpenFolder:ye}){let[be,xe]=(0,q.useState)(()=>{if(!k)return E;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return E}),Se=k?be:E,z=(0,q.useCallback)(e=>{xe(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[Te,Ee]=(0,q.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),De=(0,q.useCallback)(()=>{Ee(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[Oe,ke]=(0,q.useState)(new Set),Pe=(0,q.useCallback)(e=>{ke(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[B,Fe]=(0,q.useState)(new Set),[Ie,Le]=(0,q.useState)(null),[Re,Be]=(0,q.useState)(null),He=tr(),Ue=!!(He&&o),Ke=(0,q.useCallback)((e,t=!1)=>{if(!He||!o)return;let r=e.map(e=>n.find(t=>t.id===e)).filter(e=>!!e);r.length!==0&&He.openAddRelated({workspaceName:o,documents:r},t)},[He,o,n]),[qe,Je]=(0,q.useState)(!1),[Ye,Qe]=(0,q.useState)(null),[$e,et]=(0,q.useState)(!1),[tt,nt]=(0,q.useState)(null),[at,ot]=(0,q.useState)(!1),st=(0,q.useRef)(!1),ct=(0,q.useRef)(!1),lt=a===`backends`&&me===`path`?Mo(i):null;(0,q.useEffect)(()=>()=>{st.current=!0},[]);let[ut,pt]=(0,q.useState)(!1),[ht,gt]=(0,q.useState)(null),[_t,yt]=(0,q.useState)(!1),[V,bt]=(0,q.useState)(null),H=Pn()==null&&!!o,[U,xt]=(0,q.useState)(null),[St,Ct]=(0,q.useState)(null),Et=!!(R&&x),Dt=!!o,{showSuccessToast:Ot,showErrorToast:kt}=Tt(),{showProgress:At}=wt(),jt=nu(),Mt=o?e=>jt.open(e,o):void 0,Nt=me===`workspace`,Pt=Nt?void 0:d,It=Nt?void 0:m,[Lt,Rt]=(0,q.useState)(!1),[zt,Bt]=(0,q.useState)(!1),[Vt,Ht]=(0,q.useState)(``),G=e??Vt,Ut=e!==void 0,[Wt,Kt]=(0,q.useState)(!1),qt=se.length>0,Jt=(0,q.useRef)(null),Yt=(0,q.useCallback)(()=>{Ht(``),Jt.current&&(Jt.current.value=``)},[]);(0,q.useEffect)(()=>{if(!k||window.matchMedia(`(max-width: 767px)`).matches)return;let e=Jt.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[k]);let Xt=JSON.stringify([o,a,i]),[Zt,Qt]=(0,q.useState)(Xt);Xt!==Zt&&(Qt(Xt),Fe(new Set),Qe(null),Be(null),Le(null)),(0,q.useEffect)(()=>{C?.(Array.from(B))},[B,C]);let $t=(0,q.useCallback)(()=>{if(!ce)return;let e=G.trim();e&&(ce(e),Yt())},[ce,G,Yt]),en=(0,q.useCallback)(()=>{Yt(),le&&se.length>0&&le(-1)},[le,se.length,Yt]),tn=(0,q.useCallback)((e,t)=>{let n;B.has(t)&&B.size>1?n=Array.from(B):(n=[t],Fe(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:me===`path`?i:void 0,sourceTreeName:a,sourceWorkspaceId:o};e.dataTransfer.setData(`application/json`,JSON.stringify(r)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[B,i,a,o,me]),nn=(0,q.useCallback)(async e=>{if(!x)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let n=null;try{n=JSON.parse(t)}catch{return}n?.type!==`document`||!Array.isArray(n.documentIds)||n.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),Kt(!1),!ql(n,o,a,i)&&(await x(i,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),Fe(new Set)))},[i,a,o,x]),rn=(0,q.useCallback)(e=>{x&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,Kt(!0))},[x]),an=(0,q.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||Kt(!1)},[]),on=(0,q.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),sn=(0,q.useMemo)(()=>n.length===0?null:new Xn(n,on),[n,on]),cn=(0,q.useDeferredValue)(G),K=(0,q.useMemo)(()=>{if(!cn.trim())return n;let{text:e,ids:t,invalid:r}=ts(cn);if(r)return[];let i=e&&sn?sn.search(e).map(e=>e.item):n;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[n,cn,sn]),ln=(0,q.useMemo)(()=>{if(!ve||ve.length===0||cn.trim())return[];let e=ue?.order===`desc`?-1:1;return[...ve].sort((t,n)=>Number(!!n.isParent)-Number(!!t.isParent)||(t.label||t.name).localeCompare(n.label||n.name,void 0,{numeric:!0,sensitivity:`base`})*e)},[ve,cn,ue?.order]),un=ln.length>0,[dn,fn]=(0,q.useState)(null),pn=(0,q.useMemo)(()=>o&&a&&ye?(e,t)=>fn({x:t.clientX,y:t.clientY,path:e}):void 0,[o,a,ye]),hn={folders:ln,onOpen:ye,onMenu:pn,onPasteDocuments:x,contextPath:i,treeName:a,workspaceId:o},{sorted:gn,sort:vn,toggleSort:yn}=pu(K,(0,q.useMemo)(()=>({title:e=>Gt(e).title?.toLowerCase()??``,schema:e=>Gt(e).schemaLabel??``,type:_n,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),bn=(0,q.useCallback)(e=>Fp(e,ue?.sortBy),[ue?.sortBy]),xn=(0,q.useMemo)(()=>Wp(K,bn,ue?.order===`asc`?`asc`:`desc`),[K,bn,ue?.order]),Sn=Te&&!mn(ue?.sortBy)&&xn.length>1,Cn=(0,q.useCallback)((e,t)=>{Fe(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),wn=(0,q.useMemo)(()=>(Se===`table`?gn:Sn?xn.filter(e=>!Oe.has(e.key)).flatMap(e=>e.items):K).map(e=>e.id),[Se,gn,Sn,xn,Oe,K]),Tn=(0,q.useRef)(null),En=JSON.stringify([o,i,a,j]),Dn=(0,q.useCallback)(e=>{Tn.current=null,Fe(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),An=(0,q.useCallback)((e,t,n,r=!1)=>{let i=Tn.current,a=i?.scope===En&&wn.includes(i.id)?i.id:null;(!r||a===null)&&(Tn.current={scope:En,id:e}),Fe(i=>{if(r)return as(wn,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[En,wn]),jn=(0,q.useCallback)((e,t)=>{let n;B.has(e)?n=Array.from(B):(n=[e],Fe(new Set([e]))),Le({anchor:t,ids:n})},[B]),Mn=(0,q.useCallback)((e,t)=>{jn(t,Bs(e))},[jn]),Nn=(0,q.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),jn(t,hm(e)))},[jn]),Fn=(0,q.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){Je(!0);try{for(let n of t)await On(o,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;Ot(`Created ${n} relation${n===1?``:`s`}`),hu(),Be(null)}catch(e){kt(e instanceof Error?e.message:`Failed to create relations`)}finally{Je(!1)}}},[o,Ot,kt]),In=(0,q.useCallback)(async(e,t,n)=>{if(x){for(let r of e)await x(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});Fe(new Set)}},[x]),Ln=(0,q.useCallback)(async(e,t,r)=>{if(!o||!Ye||ct.current)return;ct.current=!0,st.current=!1,ot(!1),et(!0);let i=At({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${Ye.ids.length} document(s) · ${e.join(`, `)}`});try{let a=n=>kn(o,n,{to:e,mode:t,keepDocument:r.keepDocument,...t===`delete`&<?{deleteFrom:{backend:lt.backend,folder:lt.rel}}:{},folder:r.folder,filename:r.filename,onConflict:r.onConflict}),s=t===`delete`?await go(Ye.ids,a,{shouldStop:()=>st.current,onProgress:(t,n)=>{nt({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(Ye.ids),pending:[]},c=s.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,l=s.successful.filter(e=>e.transfers?.some(e=>e.state===`pending`)).length,u=s.successful.length-c-l,d=s.failed.length,f=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,p=e.join(`, `),m=[c?`${c} already there`:null,l?`${l} queued for backend sync`:null,d?`${d} skipped`:null,s.pending.length?`${s.pending.length} not processed`:null].filter(Boolean).join(` · `),h=`${f} ${p}: ${u} document${u===1?``:`s`}${m?` · ${m}`:``}`;d>0?(i.fail({title:`Operation incomplete`,description:`${h}. ${ns(s.failed,new Map(n.map(e=>[e.id,Gt(e).title])))}`,variant:`destructive`}),console.warn(`Backend transfer skipped documents:`,s.failed)):i.done({title:s.pending.length?`Operation stopped`:l?`Transfer queued`:`Operation complete`,description:h}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`));let g=[...s.failed.map(e=>e.id),...s.pending];Qe(g.length?{ids:g,mode:t}:null),Fe(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{ct.current=!1,et(!1),nt(null)}},[o,Ye,lt,n,At]),Rn=(0,q.useCallback)(()=>{B.size===K.length?Fe(new Set):Fe(new Set(K.map(e=>e.id)))},[B.size,K]),zn=(0,q.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{let t=window.document.createElement(`textarea`);t.value=e,window.document.body.appendChild(t),t.select(),window.document.execCommand(`copy`),window.document.body.removeChild(t)}},[]),Bn=e=>{if(e.length===0)return[];let t=e.length,r=t>1?` (${t})`:``,i=t===1?n.find(t=>t.id===e[0]):void 0,o=()=>Fe(new Set),s=e.some(e=>n.find(t=>t.id===e)?.locations?.some(e=>e.status==null||e.status===`available`)),c=[],l=e=>{e&&c.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;l({id:`view`,group:`open`,label:`View details`,icon:dt,run:()=>Ct({document:i})}),l(H&&{id:`edit`,group:`open`,label:`Edit`,icon:O,run:()=>Ct({document:i,edit:!0})}),l(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:Ae,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),l(Mt&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:de,run:()=>Mt(i)})}return l(y&&{id:`copy`,group:`clipboard`,label:`Copy${r}`,icon:u,shortcut:`Mod+C`,run:()=>y(e)}),l(b&&{id:`cut`,group:`clipboard`,label:`Cut${r}`,icon:we,shortcut:`Mod+X`,run:()=>b(e)}),l(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:We,run:()=>zn(String(i.id))}),l(i&&H&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:Ze,run:()=>xt(i)}),l(Et&&{id:`link-to`,group:`organize`,label:`Link to…${r}`,icon:Ne,run:()=>Be(e)}),l(Ue&&{id:`add-related`,group:`organize`,label:`Add related document…${r}`,icon:ze,run:t=>Ke(e,t?.shiftKey)}),l(H&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${r}`,icon:O,run:()=>bt(e)}),l(H&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:u,run:t=>{yt(!!t?.shiftKey),gt(e)}}),l({id:`export`,group:`organize`,label:`Export…${r}`,icon:Me,run:()=>Rt(!0)}),l(a!==`backends`&&(Pt||It)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${r}`,icon:_,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&Pt?Pt(e[0]):It?.(e),o()}}),l(a!==`backends`&&(f||h)&&{id:`delete`,group:`remove`,label:`Delete from index${r}`,icon:L,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&f?f(e[0]):h?.(e),o()}}),s&&Dt?(l({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${r}`,icon:ne,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Qe({ids:e,mode:`copy`})}),l({id:`backend-move`,group:`backends`,label:`Move to backend…${r}`,icon:Ve,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Qe({ids:e,mode:`move`})}),l({id:`backend-delete`,group:`backends`,label:`Delete from backend…${r}`,icon:L,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Qe({ids:e,mode:`delete`})})):s&&(p||v)&&l({id:`destroy`,group:`backends`,label:`Delete from backend(s)${r}`,icon:L,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&p?p(e[0]):v?.(e),o()}}),c},Vn=()=>{let e=[],t=t=>{t&&e.push(t)},r=w??[];return t(x&&r.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${r.length})`,icon:A,shortcut:`Mod+V`,run:async()=>{try{await x(i,r)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(K.length>0&&{id:`select-all`,group:`select`,label:G?`Select all matches (${K.length})`:`Select all on this page`,icon:Ce,shortcut:`Mod+A`,run:()=>Fe(new Set(K.map(e=>e.id)))}),t(B.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:it,run:()=>Fe(new Set)}),t(x&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:Xe,hint:`Browse and add existing documents to this folder`,run:()=>pt(!0)}),t(S&&{id:`import`,group:`add`,label:`Import…`,icon:fe,run:()=>Bt(!0)}),t(n.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:Me,run:()=>{Fe(new Set),Rt(!0)}}),t(ae&&s>0&&{id:`purge`,group:`purge`,label:`Purge all (${s})`,icon:L,destructive:!0,disabled:oe||!!G,hint:G?`Purge is disabled while local search is active`:oe?`Purge requires loaded server results with no browser-only or live selection`:`Delete all documents matching the current server-side filters across all pages`,run:ae}),e},Hn=!!(pe&&ue&&o),Un=Ie?Ie.ids?Bn(Ie.ids):Vn():[],Wn=Ie?.ids?.length===1?n.find(e=>e.id===Ie.ids[0]):void 0,Gn=Wn?(0,Y.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Y.jsx)(wc,{document:Wn,chip:!0}),(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Gt(Wn).title}),(0,Y.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Wn.id,` · `,Wn.schema]})]})]}):(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Ie?.ids?`${Ie.ids.length} documents`:`This folder`}),Kn=e=>{Le({anchor:Bs(e.currentTarget),ids:B.size>0?Array.from(B):null})},qn=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),Fe(new Set),Le({anchor:hm(e),ids:null}))},Jn=e=>{if(e.defaultPrevented||Is(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Rs(e)){e.preventDefault(),t?jn(Number(t.dataset.documentId),Bs(t,`inside`)):Le({anchor:Bs(e.target,`inside`),ids:B.size>0?Array.from(B):null});return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=Array.from(e.currentTarget.querySelectorAll(`[data-document-id]`));if(n.length===0)return;let r=t?n.indexOf(t):-1,i=n[e.key===`ArrowDown`?Math.min(r+1,n.length-1):Math.max(r-1,0)];e.preventDefault(),i.focus({preventScroll:!0}),i.scrollIntoView({block:`nearest`}),e.shiftKey&&An(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&B.size>0){e.preventDefault(),Fe(new Set);return}Ls(e,[...Bn(Array.from(B)),...Vn()])},Yn=(0,q.useCallback)(async e=>{if(!S)return!1;try{return await S(e,i)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[S,i]),Zn=e=>Sn?xn.map(t=>{let n=Oe.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!B.has(t),0);return(0,Y.jsxs)(`section`,{className:`group mb-4`,children:[(0,Y.jsx)(Fm,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>Pe(t.key),onSelectAll:e=>Cn(r,e)}),!n&&e(t.items)]},t.key)}):e(K);return r?(0,Y.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,Y.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Y.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})}):(0,Y.jsxs)(`div`,{tabIndex:-1,onKeyDown:Jn,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${Wt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:rn,onDragLeave:an,onDrop:nn,children:[(0,Y.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,Y.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,Y.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,Y.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:G?`${K.length} of ${n.length}`:`${s.toLocaleString()} document${s===1?``:`s`}`})]}),(0,Y.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Y.jsxs)(`p`,{hidden:Ut,className:`min-w-0 truncate`,children:[`Context: `,(0,Y.jsx)(`span`,{className:`font-mono`,children:i}),ee&&te&&ee!==te&&(0,Y.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,Y.jsxs)(`p`,{className:`shrink-0`,children:[B.size>0&&(0,Y.jsxs)(`span`,{className:`text-info`,children:[B.size,` selected`]}),B.size>0&&(G||s>M)&&(0,Y.jsx)(`span`,{className:`mx-1`,children:`·`}),G?`on this page`:s>M?`Showing ${Math.min((j-1)*M+1,s)}–${Math.min(j*M,s)}`:null]})]})]}),!Ut&&(0,Y.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Y.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[!Ut&&I&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,Y.jsx)(`button`,{type:`button`,onClick:()=>I(`path`),className:`px-2.5 py-2 transition-colors ${me===`path`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List documents in the selected path`,children:`This path`}),(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>I(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${me===`workspace`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List every document in the workspace (staging excluded)`,children:[(0,Y.jsx)(F,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!Ut&&(0,Y.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,Y.jsx)(mt,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,Y.jsx)(`input`,{ref:Jt,type:`text`,placeholder:ce?qt?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,title:`Search text or an exact document ID, e.g. @id:101140. Press Enter to search the server.`,defaultValue:``,onChange:e=>Ht(e.target.value),onFocus:e=>{let t=e.currentTarget;window.matchMedia(`(max-width: 767px)`).matches&&setTimeout(()=>t.scrollIntoView({block:`center`,behavior:`smooth`}),250)},onKeyDown:e=>{e.key===`Enter`&&ce&&(e.preventDefault(),$t())},className:`w-full pl-10 pr-9 py-2 border border-input rounded-md bg-background text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent`}),(G||qt)&&(0,Y.jsx)(`button`,{onClick:en,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,Y.jsx)(T,{className:`h-4 w-4`})})]}),!Ut&&ce&&G.trim()&&!se.includes(G.trim())&&(0,Y.jsxs)(W,{size:`sm`,variant:`default`,onClick:$t,className:`shrink-0`,title:qt?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,Y.jsx)(mt,{className:`h-3.5 w-3.5 mr-1`}),qt?`Refine`:`Search server`]})]}),!Ut&&qt&&(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),se.map((e,t)=>(0,Y.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,Y.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,Y.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,Y.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),le&&(0,Y.jsx)(`button`,{onClick:()=>le(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,Y.jsx)(T,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),le&&se.length>1&&(0,Y.jsx)(`button`,{onClick:()=>le(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,Y.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,Y.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,Y.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[k&&(0,Y.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,ft,`Tile view`],[`card`,je,`Card view`]].map(([e,t,n])=>(0,Y.jsx)(`button`,{type:`button`,onClick:()=>z(e),title:n,"aria-pressed":Se===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${Se===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Y.jsx)(t,{className:`h-4 w-4`})},e))}),k&&Se!==`table`&&!mn(ue?.sortBy)&&(0,Y.jsx)(`button`,{type:`button`,onClick:De,title:Te?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":Te,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${Te?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Y.jsx)(g,{className:`h-4 w-4`})})]}),N&&s>0&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,Y.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,Y.jsxs)(`select`,{value:M,onChange:e=>P?.(Number(e.target.value)),className:`h-control-sm rounded-(--input-radius) border-(length:--input-border-width) border-input bg-background px-2 text-sm focus-ring`,"aria-label":`Documents per page`,children:[(0,Y.jsx)(`option`,{value:25,children:`25`}),(0,Y.jsx)(`option`,{value:50,children:`50`}),(0,Y.jsx)(`option`,{value:100,children:`100`}),(0,Y.jsx)(`option`,{value:200,children:`200`})]}),(0,Y.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,Y.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[Hn&&(0,Y.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,Y.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,Y.jsx)(Pp,{workspaceId:o,value:ue,onChange:pe})]}),(0,Y.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(n.length>0||S||x)&&(0,Y.jsxs)(`div`,{className:`contents`,children:[(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:Kn,"aria-haspopup":`menu`,"aria-label":B.size>0?`Actions (${B.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${Ps(`Shift+F10`)} or right-click)`,children:[(0,Y.jsx)(Ge,{className:`h-4 w-4`}),(0,Y.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,B.size>0?` (${B.size} selected)`:``]})]}),B.size>0&&(0,Y.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:()=>Fe(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,Y.jsx)(T,{className:`h-3.5 w-3.5`}),(0,Y.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),w&&w.length>0&&x&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>x(i,w),className:`flex items-center gap-1.5`,title:`Paste into this folder (${Ps(`Mod+V`)})`,children:[(0,Y.jsx)(A,{className:`h-4 w-4`}),`Paste (`,w.length,`)`]})]}),he&&_e&&(0,Y.jsx)(W,{size:`sm`,variant:`outline`,onClick:_e,disabled:ge,className:`w-control-sm shrink-0 px-0 touch-target`,"aria-label":ge?`Saving filters`:`Save current query and filters`,title:`Save current query and filters`,children:(0,Y.jsx)(ie,{className:`h-3.5 w-3.5`})}),t]})]})]})}),N&&s>M&&(0,Y.jsxs)(`div`,{className:`document-pagination mt-3 flex min-w-0 flex-wrap items-center justify-end gap-2 border-t pt-3 max-sm:gap-0.5`,children:[(0,Y.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((j-1)*M+1,s),` - `,Math.min(j*M,s),` of `,s]}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>N(1),disabled:j===1,className:`p-1 touch-target`,children:(0,Y.jsx)(re,{className:`h-4 w-4`})}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>N(j-1),disabled:j===1,className:`p-1 touch-target`,children:(0,Y.jsx)(l,{className:`h-4 w-4`})}),(0,Y.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,Y.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),j,(0,Y.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,Y.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(s/M)]}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>N(j+1),disabled:j>=Math.ceil(s/M),className:`p-1 touch-target`,children:(0,Y.jsx)(vt,{className:`h-4 w-4`})}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>N(Math.ceil(s/M)),disabled:j>=Math.ceil(s/M),className:`p-1 touch-target`,children:(0,Y.jsx)(D,{className:`h-4 w-4`})})]})]})]}),(0,Y.jsx)(kl,{scope:JSON.stringify([En,Se,wn]),selected:B,onSelectionChange:Dn,onContextMenu:qn,children:K.length===0&&!un?(0,Y.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,Y.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Y.jsx)(rt,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:G?`No documents match your search`:`No documents found in this context`}),(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:G?(0,Y.jsxs)(Y.Fragment,{children:[`Search: `,(0,Y.jsxs)(`span`,{className:`font-mono`,children:[`"`,G,`"`]})]}):(0,Y.jsxs)(Y.Fragment,{children:[`Path: `,(0,Y.jsx)(`span`,{className:`font-mono`,children:i})]})}),!Ut&&G&&(0,Y.jsx)(`button`,{onClick:Yt,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!G&&w&&w.length>0&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,Ps(`Mod+V`),` to paste `,w.length,` document(s)`]})]})}):Se===`tile`?(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(Mm,{...hn}),K.length===0&&(0,Y.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Zn(e=>(0,Y.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,Y.jsx)(Tm,{document:e,isSelected:B.has(e.id),workspaceId:o,onSelect:An,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn},e.id))}))]}):Se===`table`?(0,Y.jsx)(`div`,{children:(0,Y.jsxs)(iu,{children:[(0,Y.jsx)(au,{children:(0,Y.jsxs)(cu,{children:[(0,Y.jsx)(lu,{className:`w-10`,children:(0,Y.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:K.length>0&&B.size===K.length,ref:e=>{e&&(e.indeterminate=B.size>0&&B.size<K.length)},onChange:Rn,title:`Select all on this page`})}),(0,Y.jsx)(fu,{label:(0,Y.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:vn,onSort:yn,className:`w-12`}),(0,Y.jsx)(fu,{label:`Title`,sortKey:`title`,sort:vn,onSort:yn,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,Y.jsx)(fu,{label:`Schema`,sortKey:`schema`,sort:vn,onSort:yn,className:`hidden md:table-cell`}),(0,Y.jsx)(fu,{label:`ID`,sortKey:`id`,sort:vn,onSort:yn,className:`hidden lg:table-cell`}),(0,Y.jsx)(lu,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,Y.jsx)(fu,{label:`Created`,sortKey:`created`,sort:vn,onSort:yn,className:`hidden sm:table-cell`}),(0,Y.jsx)(lu,{className:`w-12 md:w-auto`,children:(0,Y.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,Y.jsxs)(ou,{children:[ln.map(e=>(0,Y.jsx)(Pm,{folder:e,onOpen:ye,onMenu:pn,onPasteDocuments:x,contextPath:i,treeName:a,workspaceId:o},e.path)),gn.map(e=>(0,Y.jsx)(vm,{document:e,isSelected:B.has(e.id),workspaceId:o,onSelect:An,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn},e.id))]})]})}):(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(Nm,{...hn}),K.length===0&&(0,Y.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Zn(e=>(0,Y.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,Y.jsx)(`div`,{children:(0,Y.jsx)(ym,{document:e,isSelected:B.has(e.id),workspaceId:o,onSelect:An,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn})},e.id))}))]})}),Ie&&(0,Y.jsx)(Gs,{anchor:Ie.anchor,items:Un,onClose:()=>Le(null),label:Ie.ids?`Document actions`:`Folder actions`,header:Gn}),(0,Y.jsx)(fm,{isOpen:Lt,onClose:()=>Rt(!1),documents:n,selectedDocuments:B}),(0,Y.jsx)(pm,{isOpen:zt,onClose:()=>Bt(!1),onImport:Yn}),ht&&o&&(0,Y.jsx)(jl,{modal:_t,workspaceId:o,ids:ht,onClose:()=>gt(null)}),Re&&R&&(0,Y.jsx)(ms,{label:`Link to`,onClose:()=>Be(null),children:(0,Y.jsx)(Lc,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:Re.length,fixedWorkspaceName:o,tabs:[`context`,`directory`,`relations`],saving:qe,relationExcludeIds:new Set(Re),onConfirm:(e,t)=>In(e,Re,t),onConfirmRelation:e=>Fn(e,Re),onClose:()=>Be(null)})}),Ye&&o&&(0,lo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Y.jsx)(Ql,{workspaceId:o,documentCount:Ye.ids.length,initialMode:Ye.mode,defaultFilename:Ye.ids.length===1?Ft(n.find(e=>e.id===Ye.ids[0])??{}):``,saving:$e,progress:tt,stopping:at,onStop:()=>{st.current=!0,ot(!0)},deleteFrom:lt?{backend:lt.backend,folder:lt.rel}:void 0,onConfirm:Ln,onClose:()=>{$e||Qe(null)}})}),window.document.body),ut&&x&&(0,lo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>pt(!1),"aria-hidden":!0}),(0,Y.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Y.jsx)($l,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:o,onConfirm:async e=>{await x(i,e),pt(!1)},onClose:()=>pt(!1)})})]}),window.document.body),U&&o&&(0,Y.jsx)(Cl,{workspaceId:o,document:U,onClose:()=>xt(null)},`${o}:${U.id}`),V&&o&&(0,Y.jsx)(Gl,{workspaceId:o,documentIds:V,onClose:()=>bt(null)}),(0,Y.jsx)(bp,{document:St?.document??null,isOpen:!!St,onClose:()=>Ct(null),workspaceId:o,initialEdit:St?.edit}),dn&&o&&a&&ye&&(0,Y.jsx)(um,{x:dn.x,y:dn.y,workspaceName:o,treeName:a,path:dn.path,onClose:()=>fn(null),onOpen:ye,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:a,path:e}})),pastedDocumentIds:w,onPasteDocuments:x?(e,t)=>x(e,t):void 0})]})}function Lm(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,fo.createRoot)(t);n.render((0,Y.jsx)(pm,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function Rm(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,fo.createRoot)(t);n.render((0,Y.jsx)(fm,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{Cd as $,da as $n,Fs as $t,fp as A,Ro as An,Sl as At,vf as B,mo as Bn,Xs as Bt,Dp as C,Zo as Cn,eu as Ct,vp as D,Eo as Dn,Gl as Dt,yp as E,qo as En,ql as Et,Uf as F,bo as Fn,wc as Ft,kd as G,xi as Gn,rc as Gt,nf as H,pr as Hn,Zs as Ht,Gf as I,Ko as In,uc as It,Ed as J,sa as Jn,oc as Jt,Od as K,oa as Kn,ic as Kt,Lf as L,Oo as Ln,hc as Lt,qf as M,Xo as Mn,Lc as Mt,Kf as N,No as Nn,Ec as Nt,hp as O,To as On,Vl as Ot,Jf as P,Yo as Pn,Tc as Pt,Sd as Q,xr as Qn,Is as Qt,Mf as R,Mo as Rn,mc as Rt,Ep as S,yo as Sn,cu as St,bp as T,ko as Tn,$l as Tt,Xd as U,Xa as Un,$s as Ut,rf as V,uo as Vn,Ys as Vt,Dd as W,Za as Wn,Qs as Wt,wd as X,Si as Xn,Js as Xt,vd as Y,ca as Yn,ac as Yt,xd as Z,ua as Zn,Gs as Zt,wp as _,zo as _n,iu as _t,im as a,bs as an,ro as ar,Bu as at,Op as b,Qo as bn,lu as bt,tm as c,ys as cn,ku as ct,$p as d,os as dn,Su as dt,js as en,Tr as er,Td as et,Gp as f,is as fn,wu as ft,Ap as g,Wo as gn,fu as gt,Pp as h,Jo as hn,pu as ht,cm as i,Ds as in,Ri as ir,Ju as it,Qf as j,Vo as jn,Rc as jt,mp as k,vo as kn,Ml as kt,Yp as l,ms as ln,Ou as lt,qp as m,es as mn,hu as mt,lm as n,As as nn,ji as nr,rd as nt,em as o,vs as on,Vu as ot,Kp as p,Ho as pn,gu as pt,Ad as q,bi as qn,qs as qt,sm as r,Ts as rn,Pi as rr,Qu as rt,Zp as s,_s as sn,Iu as st,Im as t,ks as tn,Sr as tr,hd as tt,Xp as u,ps as un,Du as ut,Sp as v,Po as vn,ou as vt,Cp as w,Bo as wn,nu as wt,Tp as x,Go as xn,au as xt,kp as y,xo as yn,uu as yt,Cf as z,ho as zn,pc as zt};
|