@loomcycle/explorer 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,14 +1,14 @@
1
- "use strict";var tt=Object.create;var be=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,rt=Object.prototype.hasOwnProperty;var ot=(t,s,n,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of st(s))!rt.call(t,r)&&r!==n&&be(t,r,{get:()=>s[r],enumerable:!(a=nt(s,r))||a.enumerable});return t};var ct=(t,s,n)=>(n=t!=null?tt(at(t)):{},ot(s||!t||!t.__esModule?be(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),o=require("react"),it=require("@loomcycle/client"),lt=require("react-markdown"),dt=require("remark-gfm");function pe(t,s){return{pathLs:(n,a,r,i)=>t.path({op:"ls",path:n,scope:a,recursive:r},i),pathMkdir:(n,a,r)=>t.path({op:"mkdir",path:n,scope:a},r),pathMv:(n,a,r,i)=>t.path({op:"mv",path:n,to:a,scope:r},i),pathRm:(n,a,r,i)=>t.path({op:"rm",path:n,scope:a,recursive:r},i),documentCreate:(n,a,r,i)=>t.document({op:"create_document",title:n,path:a,scope:r},i),documentDelete:(n,a,r)=>t.document({op:"delete_document",id:n,scope:a},r),documentGet:(n,a,r)=>t.document({op:"get_document",id:n,scope:a},r),documentsSummary:(n,a,r)=>t.document({op:"documents_summary",scope:a,...n.documentIds?{document_ids:n.documentIds}:{},...n.underPath?{under_path:n.underPath}:{}},r),documentQueryChunks:(n,a,r)=>t.document({op:"query_chunks",document_id:n,scope:a,limit:1e3},r),documentGetChunk:(n,a,r)=>t.document({op:"get_chunk",id:n,scope:a},r),documentCreateChunk:(n,a,r,i,c,l)=>t.document({op:"create_chunk",document_id:n,parent_id:a,scope:i,...l?{after_id:l}:{},...r},c),documentReorderChunk:(n,a,r,i)=>t.document({op:"reorder_chunk",id:n,direction:a,scope:r},i),documentDeleteChunk:(n,a,r)=>t.document({op:"delete_chunk",id:n,scope:a},r),documentSetAsset:(n,a,r,i,c,l)=>t.document({op:"set_asset",id:n,media_type:a,data:r,...i?{filename:i}:{},scope:c},l),documentGetEdges:(n,a,r)=>t.document({op:"get_edges",document_id:n,scope:a},r),documentUpdateChunk:(n,a,r,i,c)=>t.document({op:"update_chunk",id:n,revision:a,scope:i,...r},c),documentExportMd:(n,a,r,i)=>t.document({op:"export_md",document_id:n,scope:a,include_metadata:r},i),documentBacklinks:(n,a,r)=>t.document({op:"backlinks",id:n,scope:a},r),documentRelated:(n,a,r,i)=>t.document({op:"related",id:n,scope:a,...i?{limit:i}:{}},r),documentUnlinkedMentions:(n,a,r,i)=>t.document({op:"unlinked_mentions",id:n,scope:a,...i?{limit:i}:{}},r),documentHistory:(n,a,r,i)=>t.document({op:"history",id:n,scope:a,...i?{limit:i}:{}},r),documentGetVersion:(n,a,r,i)=>t.document({op:"get_version",id:n,revision:a,scope:r},i),documentDiff:(n,a,r,i,c)=>t.document({op:"diff",id:n,from_revision:a,to_revision:r,scope:i},c),documentExportCanvas:(n,a,r)=>t.document({op:"export_canvas",document_id:n,scope:a},r),...s?{documentAssetObjectUrl:async(n,a,r)=>{const i=new URLSearchParams({scope:a});r?.scopeId&&i.set("scope_id",r.scopeId),r?.tenant&&i.set("tenant",r.tenant);const c=await s(`/v1/_document/asset/${encodeURIComponent(n)}?${i.toString()}`);if(!c.ok)throw new Error(`asset fetch failed: ${c.status}`);const l=await c.blob();return URL.createObjectURL(l)}}:{}}}const Me=o.createContext(null);function ut({value:t,children:s}){return e.jsx(Me.Provider,{value:t,children:s})}function X(){const t=o.useContext(Me);if(!t)throw new Error("useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)");return t}function De(t){const s=t.fetch;return new it.LoomcycleClient({baseUrl:t.baseUrl,authToken:t.token||void 0,fetch:(n,a)=>s?s(n,a):fetch(n,a)})}function Re(t){const s=t.fetch,n=(a,r)=>s?s(a,r):fetch(a,r);return a=>{const r={};return t.token&&(r.Authorization=`Bearer ${t.token}`),n(t.baseUrl+a,{headers:r})}}function $e(t){const{dataLayer:s,client:n,connection:a}=t;return o.useMemo(()=>s||(n?pe(n):a?pe(De(a),Re(a)):null),[s,n,a?.baseUrl,a?.token,a?.fetch])}function Le({theme:t,dataLayer:s,children:n}){const a=t?{"data-theme":t}:{};return s?e.jsx("div",{className:"loomcycle-explorer",...a,children:e.jsx(ut,{value:s,children:n})}):e.jsx("div",{className:"loomcycle-explorer",...a,children:e.jsxs("div",{className:"error-banner",children:["@loomcycle/explorer: provide a ",e.jsx("code",{children:"connection"}),", ",e.jsx("code",{children:"client"}),", or"," ",e.jsx("code",{children:"dataLayer"})," prop."]})})}const ke=6;function mt({children:t,defaultLeftWidth:s=380,minLeftWidth:n=180,minRightWidth:a=240,storageKey:r,className:i}){const[c,l]=o.useState(()=>{if(r){const v=localStorage.getItem(r),R=v?parseInt(v,10):NaN;if(Number.isFinite(R)&&R>=n)return R}return s}),d=o.useRef(null),[p,h]=o.useState(!1);o.useEffect(()=>{!r||p||localStorage.setItem(r,String(Math.round(c)))},[r,c,p]);const y=o.useCallback(v=>{v.preventDefault(),h(!0),v.target.setPointerCapture(v.pointerId)},[]),m=o.useCallback(v=>{if(!p||!d.current)return;const R=d.current.getBoundingClientRect(),O=v.clientX-R.left,A=R.width-a-ke,T=Math.max(n,Math.min(O,A));l(T)},[p,n,a]),L=o.useCallback(v=>{h(!1);try{v.target.releasePointerCapture(v.pointerId)}catch{}},[]);return e.jsxs("div",{ref:d,className:`splitter ${i??""} ${p?"dragging":""}`,style:{gridTemplateColumns:`${c}px ${ke}px 1fr`},children:[e.jsx("div",{className:"splitter-pane splitter-left",children:t[0]}),e.jsx("div",{className:"splitter-handle",role:"separator","aria-orientation":"vertical","aria-valuenow":Math.round(c),onPointerDown:y,onPointerMove:m,onPointerUp:L,onPointerCancel:L}),e.jsx("div",{className:"splitter-pane splitter-right",children:t[1]})]})}const ht=["image/png","image/jpeg","image/gif","image/webp"];function Te(t){return ht.includes(t)}function Pe(t){return new Promise((s,n)=>{if(!Te(t.type)){n(new Error(`unsupported image type "${t.type||"unknown"}" (png, jpeg, gif, webp only)`));return}const a=new FileReader;a.onerror=()=>n(a.error??new Error("failed to read file")),a.onload=()=>{const r=String(a.result??""),i=r.indexOf(",");if(i<0){n(new Error("could not decode image data"));return}s({mediaType:t.type,data:r.slice(i+1)})},a.readAsDataURL(t)})}function ft(t){if(!t)return null;for(let s=0;s<t.length;s++){const n=t[s];if(n.kind==="file"&&Te(n.type)){const a=n.getAsFile();if(a)return a}}return null}const re={"doc.rfc.draft":"#c99a3a","doc.rfc.review":"#6a7bd6","doc.rfc.confirmed":"#3a9ad6","doc.rfc.done":"#3aa06a","doc.plan.draft":"#c99a3a","doc.plan.review":"#6a7bd6","doc.plan.confirmed":"#3a9ad6","doc.plan.done":"#3aa06a","doc.document.done":"#3aa06a","doc.research.done":"#8a6ad6","doc.publication.draft":"#c99a3a","chunk.draft":"#c99a3a","chunk.review":"#6a7bd6","chunk.confirmed":"#3a9ad6","chunk.done":"#3aa06a","chunk.backlog":"#8a8f98","chunk.implementation":"#d1863a","chunk.merged":"#3aa06a"},pt=.16;function oe(t){return t&&Object.keys(t).length>0?t:re}function ge(t,s,n){const a=t??"",r=s??"";if(a&&r&&n[`doc.${a}.${r}`])return n[`doc.${a}.${r}`];if(a&&n[`doc.${a}`])return n[`doc.${a}`]}function Ae(t,s){const n=t??"";return n?s[`chunk.${n}`]:void 0}function Ue(t){const s=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!s)return;let n=s[1];n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]);const a=parseInt(n.slice(0,2),16),r=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${a}, ${r}, ${i}, ${pt})`}function ce(t){if(!t)return;const s=Ue(t);if(s)return{background:s,borderLeft:`3px solid ${t}`}}function xt(t){const s=new Map;t.forEach(r=>s.set(r.id,{row:r,children:[]}));const n=[];t.forEach(r=>{const i=s.get(r.id);r.parent_id&&s.has(r.parent_id)?s.get(r.parent_id).children.push(i):n.push(i)});const a=r=>{r.sort((i,c)=>i.row.position-c.row.position),r.forEach(i=>a(i.children))};return a(n),n}function ve(t){return t==="image"?"🖼":t==="mermaid"?"📊":""}function Oe(t,s){for(const n of t){if(n.row.id===s)return n;const a=Oe(n.children,s);if(a)return a}}function gt({tree:t,selectedId:s,onSelect:n,colorEnabled:a,scheme:r,linkedIds:i}){const[c,l]=o.useState(()=>new Map),d=o.useCallback(h=>{l(y=>{const m=new Map(y);return m.set(h,y.get(h)===!1),m})},[]);o.useEffect(()=>{if(!s)return;const h=jt(t,s);h.length!==0&&l(y=>{let m=!1;const L=new Map(y);for(const v of h)L.get(v)===!1&&(L.set(v,!0),m=!0);return m?L:y})},[t,s]);const p=a?oe(r):null;return t.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"No chunks."})}):e.jsx("ul",{className:"tree chunk-tree",children:t.map(h=>e.jsx(Fe,{node:h,expanded:c,toggle:d,selectedId:s,onSelect:n,tintScheme:p,linkedIds:i},h.row.id))})}function jt(t,s){const n=[],a=(r,i)=>{for(const c of r){if(c.row.id===s)return n.push(...i),!0;if(a(c.children,[...i,c.row.id]))return!0}return!1};return a(t,[]),n}function Fe({node:t,expanded:s,toggle:n,selectedId:a,onSelect:r,tintScheme:i,linkedIds:c}){const l=t.children.length>0,d=s.get(t.row.id)!==!1,p=a===t.row.id,h=i?ce(Ae(t.row.status,i)):void 0,y=c?.has(t.row.id);return e.jsxs("li",{className:`node chunk-node ${p?"selected":""}`,children:[e.jsxs("div",{className:"row chunk-row",style:h,children:[e.jsx("button",{type:"button",className:"tree-caret","aria-label":d?"collapse":"expand",disabled:!l,onClick:m=>{m.stopPropagation(),l&&n(t.row.id)},children:l?d?"▼":"▶":"·"}),e.jsxs("button",{type:"button",className:"chunk-link",onClick:()=>r(t),title:t.row.title,children:[ve(t.row.type)&&e.jsx("span",{className:"chunk-type-icon","aria-hidden":!0,children:ve(t.row.type)}),e.jsx("span",{className:"chunk-title",children:t.row.title||"(untitled)"}),t.row.type&&e.jsx("span",{className:"chunk-badge",children:t.row.type}),t.row.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:t.row.status}),y&&e.jsx("span",{className:"chunk-link-badge",title:"Has cross-reference links","aria-label":"linked",children:"🔗"})]})]}),l&&d&&e.jsx("ul",{className:"children chunk-children",children:t.children.map(m=>e.jsx(Fe,{node:m,expanded:s,toggle:n,selectedId:a,onSelect:r,tintScheme:i,linkedIds:c},m.row.id))})]})}let yt=0;function ie({code:t}){const s=o.useRef(null),[n,a]=o.useState({});return o.useEffect(()=>{let r=!1;return(async()=>{try{const i=(await import("mermaid")).default,c=s.current?.closest("[data-theme]")?.getAttribute("data-theme"),l=c?c==="dark":!0;i.initialize({startOnLoad:!1,theme:l?"dark":"default",securityLevel:"strict"});const{svg:d}=await i.render(`lc-mmd-${yt++}`,t);r||a({svg:d})}catch{r||a({err:!0})}})(),()=>{r=!0}},[t]),n.err?e.jsx("pre",{className:"md-pre md-mermaid-error",title:"diagram failed to render",children:e.jsx("code",{children:t})}):n.svg?e.jsx("div",{ref:s,className:"md-mermaid",dangerouslySetInnerHTML:{__html:n.svg}}):e.jsx("div",{ref:s,className:"md-mermaid md-mermaid-loading",children:"rendering diagram…"})}function bt({chunk:t,scope:s,browse:n,onClose:a,onSaved:r}){const i=X(),[c,l]=o.useState(t.title),[d,p]=o.useState(t.type??""),[h,y]=o.useState(t.status??""),[m,L]=o.useState(t.body??""),[v,R]=o.useState(t.fields?JSON.stringify(t.fields,null,2):""),[O,A]=o.useState((t.tags??[]).join(", ")),[T,M]=o.useState(!1),[U,D]=o.useState(null),[F,E]=o.useState(!1),x=d==="mermaid",_=d==="image"||!!t.asset,[W,G]=o.useState(m);o.useEffect(()=>{if(!x)return;const k=setTimeout(()=>G(m),400);return()=>clearTimeout(k)},[m,x]);const b=async k=>{D(null),M(!0);try{const{mediaType:w,data:$}=await Pe(k),Z=await i.documentSetAsset(t.id,w,$,k.name,s,n);r(Z),a()}catch(w){D(w instanceof Error?w.message:String(w)),M(!1)}},g=x?"Mermaid source":_?"Caption (optional)":"Body (Markdown)",f=async k=>{k.preventDefault(),D(null),E(!1);const w={body:m,title:c,type:d,status:h,tags:O.split(",").map($=>$.trim()).filter($=>$!=="")};if(v.trim()!=="")try{w.fields=JSON.parse(v)}catch{D("fields must be valid JSON");return}M(!0);try{const $=await i.documentUpdateChunk(t.id,t.revision,w,s,n);r($),a()}catch($){const Z=$ instanceof Error?$.message:String($);D(Z),E(/revision conflict/i.test(Z)),M(!1)}};return e.jsx("div",{className:"modal-overlay",onClick:a,children:e.jsxs("form",{className:"modal chunk-editor",onClick:k=>k.stopPropagation(),onSubmit:f,children:[e.jsxs("div",{className:"modal-header sticky-top",children:[e.jsx("h3",{children:"Edit chunk"}),e.jsxs("div",{className:"modal-buttons modal-buttons-top",children:[e.jsx("button",{type:"button",onClick:a,disabled:T,children:"cancel"}),e.jsx("button",{type:"submit",className:"primary",disabled:T,children:T?"saving…":"save"})]})]}),U&&e.jsxs("div",{className:"modal-err",children:[U,F&&" — reopen the chunk to load the latest, then reapply your edit."]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Title"}),e.jsx("input",{className:"path-modal-input",value:c,onChange:k=>l(k.target.value)})]}),e.jsxs("div",{className:"chunk-editor-row",children:[e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Type"}),e.jsx("input",{className:"path-modal-input",value:d,placeholder:"(none)",onChange:k=>p(k.target.value)})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Status"}),e.jsx("input",{className:"path-modal-input",value:h,placeholder:"(none)",onChange:k=>y(k.target.value)})]})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Tags"}),e.jsx("input",{className:"path-modal-input",value:O,placeholder:"comma-separated, nest with a slash: area/sub, priority/high",onChange:k=>A(k.target.value)})]}),_&&e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Replace image"}),e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",disabled:T,onChange:k=>{const w=k.target.files?.[0];w&&b(w)}})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:g}),e.jsx("textarea",{className:"modal-textarea chunk-body-input",rows:x?8:12,value:m,onChange:k=>L(k.target.value)})]}),x&&e.jsxs("div",{className:"path-field",children:[e.jsx("span",{children:"Preview"}),e.jsx("div",{className:"chunk-mermaid-preview",children:W.trim()?e.jsx(ie,{code:W}):e.jsx("p",{className:"doc-empty-body",children:"(enter Mermaid source above)"})})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Fields (JSON, optional)"}),e.jsx("textarea",{className:"modal-textarea chunk-fields-input",rows:4,value:v,placeholder:"{}",onChange:k=>R(k.target.value)})]})]})})}function kt(t){const s=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((t??"").trim());if(!s)return"#888888";let n=s[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),"#"+n.toLowerCase()}function vt({documentId:t,rootChunkId:s,docType:n,docStatus:a,chunkStatuses:r,scope:i,browse:c,onClose:l,onSaved:d}){const p=X(),[h,y]=o.useState(null),[m,L]=o.useState(!1),[v,R]=o.useState({}),[O,A]=o.useState(!1),[T,M]=o.useState(null),[U,D]=o.useState(null),F=o.useMemo(()=>{const g=new Set(Object.keys(re));n&&g.add(`doc.${n}.${a||"draft"}`);for(const f of r)f&&g.add(`chunk.${f}`);return[...g].sort()},[n,a,r]);o.useEffect(()=>{let g=!1;return p.documentGetChunk(s,i,c).then(f=>{if(g)return;y(f);const k=f.fields??{};L(k.color_enabled===!0);const w=k.color_scheme??{};R({...re,...w})}).catch(f=>!g&&D(f instanceof Error?f.message:String(f))),()=>{g=!0}},[p,s,i,c]);const E=(g,f)=>R(k=>({...k,[g]:f})),x=g=>({...g??{},color_enabled:m,color_scheme:v}),_=async()=>{if(h){A(!0),D(null),M(null);try{await p.documentUpdateChunk(s,h.revision,{fields:x(h.fields)},i,c),d(),l()}catch(g){D(g instanceof Error?g.message:String(g)),A(!1)}}},W=async()=>{if(!n){D("this document has no type to match");return}A(!0),D(null),M(null);try{const{documents:g}=await p.documentsSummary({underPath:"/"},i,c),f=(g??[]).filter(w=>w.type===n&&w.document_id!==t&&w.root_chunk_id);let k=0;for(const w of f)try{const $=await p.documentGetChunk(w.root_chunk_id,i,c);await p.documentUpdateChunk(w.root_chunk_id,$.revision,{fields:x($.fields)},i,c),k++}catch{}M(`Applied to ${k} other ${n} document(s).`),d()}catch(g){D(g instanceof Error?g.message:String(g))}finally{A(!1)}},G=F.filter(g=>g.startsWith("doc.")),b=F.filter(g=>g.startsWith("chunk."));return e.jsx("div",{className:"modal-overlay",onClick:l,children:e.jsxs("div",{className:"modal scheme-editor",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"scheme-editor-head",children:[e.jsx("h3",{children:"Document colors"}),e.jsxs("div",{className:"scheme-editor-actions",children:[e.jsx("button",{type:"button",onClick:l,disabled:O,children:"cancel"}),e.jsx("button",{type:"button",className:"primary",onClick:()=>{_()},disabled:O||!h,children:O?"saving…":"save"})]})]}),U&&e.jsx("div",{className:"modal-err",children:U}),h?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"scheme-toggle",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:g=>L(g.target.checked)}),e.jsx("span",{children:"Enable coloring for this document"})]}),e.jsx("p",{className:"modal-context",children:"Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable."}),e.jsxs("div",{className:"scheme-group",children:[e.jsx("h4",{children:"Document (type · status)"}),G.map(g=>e.jsx(Ne,{label:g.slice(4),value:v[g],onChange:f=>E(g,f)},g))]}),e.jsxs("div",{className:"scheme-group",children:[e.jsx("h4",{children:"Chunks (status)"}),b.map(g=>e.jsx(Ne,{label:g.slice(6),value:v[g],onChange:f=>E(g,f)},g))]}),e.jsxs("div",{className:"scheme-editor-foot",children:[e.jsxs("button",{type:"button",onClick:()=>{W()},disabled:O||!n,title:n?`Apply this palette to every other ${n} document`:"This document has no type",children:["copy to all ",n||"same-type"," documents"]}),T&&e.jsx("span",{className:"scheme-status",children:T})]})]}):e.jsx("p",{className:"modal-context",children:"Loading…"})]})})}function Ne({label:t,value:s,onChange:n}){const a=kt(s);return e.jsxs("label",{className:"scheme-row",children:[e.jsx("input",{type:"color",value:a,onChange:r=>n(r.target.value)}),e.jsx("span",{className:"scheme-key",children:t}),e.jsx("code",{className:"scheme-hex",children:a})]})}const Nt=8,wt=20;function Ct(t){return/embedder|embedding|vector|semantic|not configured/i.test(t)}function St({documentId:t,selectedId:s,scope:n,browse:a,onSelectChunk:r}){const i=X(),[c,l]=o.useState(!1),[d,p]=o.useState(!1),[h,y]=o.useState(void 0),[m,L]=o.useState([]),[v,R]=o.useState([]),[O,A]=o.useState(null),[T,M]=o.useState([]),[U,D]=o.useState(!1);o.useEffect(()=>{if(!c||!s)return;const x=s;let _=!1;return p(!0),Promise.allSettled([i.documentBacklinks(x,n,a),i.documentRelated(x,n,a,Nt),i.documentUnlinkedMentions(x,n,a,wt)]).then(([W,G,b])=>{if(!_){if(L(W.status==="fulfilled"?W.value.backlinks??[]:[]),G.status==="fulfilled")R(G.value.related??[]),A(null);else{R([]);const g=G.reason instanceof Error?G.reason.message:String(G.reason);A(Ct(g)?"semantic search not configured":g)}b.status==="fulfilled"?(M(b.value.unlinked_mentions??[]),D(!!b.value.truncated)):(M([]),D(!1)),y(x),p(!1)}}),()=>{_=!0}},[i,c,s,n,a]);const F=x=>!!x&&x!==t,E=!!(c&&s&&!d&&h===s);return e.jsxs("div",{className:"doc-conn",children:[e.jsxs("button",{type:"button",className:"doc-conn-toggle",onClick:()=>l(x=>!x),children:[c?"▼":"▶"," Connections"]}),c&&e.jsx("div",{className:"doc-conn-body",children:s?E?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Backlinks"}),m.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsx("ul",{className:"doc-conn-list",children:m.map((x,_)=>e.jsxs("li",{className:"doc-conn-row",children:[e.jsx(he,{id:x.from_id,title:x.from_title,crossDoc:F(x.from_document_id),onSelect:r}),e.jsx("span",{className:"doc-ref-kind",children:x.kind}),x.auto&&e.jsx("span",{className:"doc-conn-auto",title:"Auto-linked from a [[wikilink]]",children:"auto"})]},`${x.from_id}-${x.kind}-${_}`))})]}),e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Related"}),O?e.jsx("p",{className:"doc-conn-empty",children:O}):v.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsx("ul",{className:"doc-conn-list",children:v.map((x,_)=>e.jsxs("li",{className:"doc-conn-row",children:[e.jsx(he,{id:x.chunk_id,title:x.title,crossDoc:F(x.document_id),onSelect:r}),e.jsx("span",{className:"doc-conn-score",title:"similarity score",children:x.score.toFixed(2)})]},`${x.chunk_id}-${_}`))})]}),e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Unlinked mentions"}),T.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsxs("ul",{className:"doc-conn-list",children:[T.map((x,_)=>e.jsx("li",{className:"doc-conn-row",children:e.jsx(he,{id:x.chunk_id,title:x.title,crossDoc:F(x.document_id),onSelect:r})},`${x.chunk_id}-${_}`)),U&&e.jsx("li",{className:"doc-conn-more","aria-hidden":!0,children:"(more…)"})]})]})]}):e.jsx("p",{className:"doc-conn-empty",children:"loading…"}):e.jsx("p",{className:"doc-conn-empty",children:"Select a chunk."})})]})}function he({id:t,title:s,crossDoc:n,onSelect:a}){const r=s||t.slice(0,8);return n?e.jsxs("span",{className:"doc-ref-target external",title:"In another document",children:[r," ↗"]}):e.jsx("button",{type:"button",className:"doc-ref-target",onClick:()=>a(t),children:r})}const fe=24;function _t({edges:t,documentId:s,selectedId:n,onSelectChunk:a}){const[r,i]=o.useState(!1),[c,l]=o.useState(!1);if(t.length===0)return null;const d=n?t.filter(y=>y.from_id===n||y.to_id===n):[],p=c?t:t.slice(0,fe),h=Mt(p);return e.jsxs("div",{className:"doc-refs",children:[n&&e.jsxs("div",{className:"doc-refs-list-wrap",children:[e.jsx("h4",{children:"References"}),d.length===0?e.jsx("p",{className:"doc-refs-empty",children:"This chunk has no links."}):e.jsx("ul",{className:"doc-refs-list",children:d.map((y,m)=>e.jsx(Et,{edge:y,selectedId:n,documentId:s,onSelectChunk:a},`${y.from_id}-${y.to_id}-${y.kind}-${m}`))})]}),e.jsxs("div",{className:"doc-graph",children:[e.jsxs("button",{type:"button",className:"doc-graph-toggle",onClick:()=>i(y=>!y),children:[r?"▼":"▶"," relationship graph (",t.length,")"]}),r&&e.jsxs(e.Fragment,{children:[e.jsx(ie,{code:h}),t.length>fe&&e.jsx("button",{type:"button",className:"doc-graph-more",onClick:()=>l(y=>!y),children:c?`show top ${fe}`:`show all ${t.length}`})]})]})]})}function Et({edge:t,selectedId:s,documentId:n,onSelectChunk:a}){const r=t.from_id===s,i=r?t.to_id:t.from_id,c=(r?t.to_title:t.from_title)||i.slice(0,8),l=r?t.to_document_id:t.from_document_id,d=!l||l===n;return e.jsxs("li",{className:"doc-ref",children:[e.jsx("span",{className:"doc-ref-kind",children:t.kind}),e.jsx("span",{className:"doc-ref-arrow","aria-hidden":!0,children:r?"→":"←"}),d?e.jsx("button",{type:"button",className:"doc-ref-target",onClick:()=>a(i),children:c}):e.jsxs("span",{className:"doc-ref-target external",title:"In another document",children:[c," ↗"]})]})}function Mt(t){const s=["graph LR"];for(const n of t){const a=`${we(n.from_id)}["${Ce(n.from_title,n.from_id)}"]`,r=`${we(n.to_id)}["${Ce(n.to_title,n.to_id)}"]`,i=(n.kind||"link").replace(/[|"]/g," ");s.push(` ${a} -->|${i}| ${r}`)}return s.join(`
2
- `)}function we(t){return"n"+t.replace(/[^a-zA-Z0-9]/g,"")}function Ce(t,s){const a=(t??"").replace(/["[\]{}|<>]/g," ").replace(/\s+/g," ").trim()||s.slice(0,6);return a.length>30?a.slice(0,29)+"…":a}function Dt(t){const s=typeof t=="number"?t/1e6:Date.parse(String(t));return!Number.isFinite(s)||s<=0?String(t??""):new Date(s).toLocaleString()}function Rt({chunkId:t,chunkTitle:s,scope:n,browse:a,onClose:r}){const i=X(),[c,l]=o.useState([]),[d,p]=o.useState(!0),[h,y]=o.useState(null),[m,L]=o.useState("none"),[v,R]=o.useState(null),[O,A]=o.useState(""),[T,M]=o.useState(!1),[U,D]=o.useState(null),[F,E]=o.useState(null),[x,_]=o.useState("");o.useEffect(()=>{let b=!1;return p(!0),y(null),i.documentHistory(t,n,a).then(g=>{if(b)return;const f=g.revisions??[];if(l(f),f.length>=2){const k=f.map(w=>w.revision);D(Math.min(...k)),E(Math.max(...k))}}).catch(g=>!b&&y(g instanceof Error?g.message:String(g))).finally(()=>!b&&p(!1)),()=>{b=!0}},[i,t,n,a]);const W=async b=>{y(null),M(!0),R(b),L("version");try{const g=await i.documentGetVersion(t,b,n,a);A(g.body??"")}catch(g){y(g instanceof Error?g.message:String(g))}finally{M(!1)}},G=async()=>{if(!(U===null||F===null)){y(null),M(!0),L("diff");try{const b=await i.documentDiff(t,U,F,n,a);_(b.diff??"")}catch(b){y(b instanceof Error?b.message:String(b))}finally{M(!1)}}};return e.jsx("div",{className:"modal-overlay",onClick:r,children:e.jsxs("div",{className:"modal history-modal",onClick:b=>b.stopPropagation(),children:[e.jsxs("div",{className:"modal-header sticky-top",children:[e.jsxs("h3",{children:["History",s?` — ${s}`:""]}),e.jsx("div",{className:"modal-buttons modal-buttons-top",children:e.jsx("button",{type:"button",onClick:r,children:"close"})})]}),h&&e.jsx("div",{className:"modal-err",children:h}),d?e.jsx("p",{className:"doc-empty-body",children:"loading…"}):c.length===0?e.jsx("p",{className:"doc-empty-body",children:"No history recorded for this chunk."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"doc-hist-revs",children:c.map(b=>e.jsxs("button",{type:"button",className:"doc-hist-rev"+(m==="version"&&v===b.revision?" active":""),onClick:()=>{W(b.revision)},children:[e.jsxs("span",{className:"doc-hist-rev-num",children:["rev ",b.revision]}),e.jsx("span",{className:"doc-hist-rev-time",children:Dt(b.created_at)}),e.jsx("span",{className:"doc-hist-rev-actor",children:b.actor||"unknown"})]},b.revision))}),c.length>=2&&e.jsxs("div",{className:"doc-hist-diffbar",children:[e.jsx("span",{children:"Compare"}),e.jsx("select",{value:U??"",onChange:b=>D(b.target.value===""?null:Number(b.target.value)),"aria-label":"diff from revision",children:c.map(b=>e.jsxs("option",{value:b.revision,children:["rev ",b.revision]},b.revision))}),e.jsx("span",{"aria-hidden":!0,children:"→"}),e.jsx("select",{value:F??"",onChange:b=>E(b.target.value===""?null:Number(b.target.value)),"aria-label":"diff to revision",children:c.map(b=>e.jsxs("option",{value:b.revision,children:["rev ",b.revision]},b.revision))}),e.jsx("button",{type:"button",onClick:()=>{G()},disabled:T||U===null||F===null,children:"diff"})]}),e.jsx("div",{className:"doc-hist-output",children:T?e.jsx("p",{className:"doc-empty-body",children:"loading…"}):m==="diff"?e.jsx($t,{text:x}):m==="version"?e.jsx("pre",{className:"md-pre doc-hist-version",children:e.jsx("code",{children:O||"(empty)"})}):e.jsx("p",{className:"doc-empty-body",children:"Select a revision to view it, or compare two."})})]})]})})}function $t({text:t}){if(!t.trim())return e.jsx("p",{className:"doc-empty-body",children:"(no differences)"});const s=t.split(`
1
+ "use strict";var nt=Object.create;var be=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var at=Object.getOwnPropertyNames;var rt=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var ot=(t,s,n,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of at(s))!ct.call(t,r)&&r!==n&&be(t,r,{get:()=>s[r],enumerable:!(a=st(s,r))||a.enumerable});return t};var it=(t,s,n)=>(n=t!=null?nt(rt(t)):{},ot(s||!t||!t.__esModule?be(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),lt=require("@loomcycle/client"),dt=require("react-markdown"),ut=require("remark-gfm");function pe(t,s){return{pathLs:(n,a,r,i)=>t.path({op:"ls",path:n,scope:a,recursive:r},i),pathMkdir:(n,a,r)=>t.path({op:"mkdir",path:n,scope:a},r),pathMv:(n,a,r,i)=>t.path({op:"mv",path:n,to:a,scope:r},i),pathRm:(n,a,r,i)=>t.path({op:"rm",path:n,scope:a,recursive:r},i),documentCreate:(n,a,r,i)=>t.document({op:"create_document",title:n,path:a,scope:r},i),documentDelete:(n,a,r)=>t.document({op:"delete_document",id:n,scope:a},r),documentGet:(n,a,r)=>t.document({op:"get_document",id:n,scope:a},r),documentsSummary:(n,a,r)=>t.document({op:"documents_summary",scope:a,...n.documentIds?{document_ids:n.documentIds}:{},...n.underPath?{under_path:n.underPath}:{}},r),documentQueryChunks:(n,a,r)=>t.document({op:"query_chunks",document_id:n,scope:a,limit:1e3},r),documentGetChunk:(n,a,r)=>t.document({op:"get_chunk",id:n,scope:a},r),documentCreateChunk:(n,a,r,i,o,l)=>t.document({op:"create_chunk",document_id:n,parent_id:a,scope:i,...l?{after_id:l}:{},...r},o),documentReorderChunk:(n,a,r,i)=>t.document({op:"reorder_chunk",id:n,direction:a,scope:r},i),documentDeleteChunk:(n,a,r)=>t.document({op:"delete_chunk",id:n,scope:a},r),documentSetAsset:(n,a,r,i,o,l)=>t.document({op:"set_asset",id:n,media_type:a,data:r,...i?{filename:i}:{},scope:o},l),documentGetEdges:(n,a,r)=>t.document({op:"get_edges",document_id:n,scope:a},r),documentUpdateChunk:(n,a,r,i,o)=>t.document({op:"update_chunk",id:n,revision:a,scope:i,...r},o),documentExportMd:(n,a,r,i)=>t.document({op:"export_md",document_id:n,scope:a,include_metadata:r},i),documentBacklinks:(n,a,r)=>t.document({op:"backlinks",id:n,scope:a},r),documentRelated:(n,a,r,i)=>t.document({op:"related",id:n,scope:a,...i?{limit:i}:{}},r),documentUnlinkedMentions:(n,a,r,i)=>t.document({op:"unlinked_mentions",id:n,scope:a,...i?{limit:i}:{}},r),documentHistory:(n,a,r,i)=>t.document({op:"history",id:n,scope:a,...i?{limit:i}:{}},r),documentGetVersion:(n,a,r,i)=>t.document({op:"get_version",id:n,revision:a,scope:r},i),documentDiff:(n,a,r,i,o)=>t.document({op:"diff",id:n,from_revision:a,to_revision:r,scope:i},o),documentExportCanvas:(n,a,r)=>t.document({op:"export_canvas",document_id:n,scope:a},r),...s?{documentAssetObjectUrl:async(n,a,r)=>{const i=new URLSearchParams({scope:a});r?.scopeId&&i.set("scope_id",r.scopeId),r?.tenant&&i.set("tenant",r.tenant);const o=await s(`/v1/_document/asset/${encodeURIComponent(n)}?${i.toString()}`);if(!o.ok)throw new Error(`asset fetch failed: ${o.status}`);const l=await o.blob();return URL.createObjectURL(l)}}:{}}}const Me=c.createContext(null);function mt({value:t,children:s}){return e.jsx(Me.Provider,{value:t,children:s})}function X(){const t=c.useContext(Me);if(!t)throw new Error("useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)");return t}function De(t){const s=t.fetch;return new lt.LoomcycleClient({baseUrl:t.baseUrl,authToken:t.token||void 0,fetch:(n,a)=>s?s(n,a):fetch(n,a)})}function Re(t){const s=t.fetch,n=(a,r)=>s?s(a,r):fetch(a,r);return a=>{const r={};return t.token&&(r.Authorization=`Bearer ${t.token}`),n(t.baseUrl+a,{headers:r})}}function $e(t){const{dataLayer:s,client:n,connection:a}=t;return c.useMemo(()=>s||(n?pe(n):a?pe(De(a),Re(a)):null),[s,n,a?.baseUrl,a?.token,a?.fetch])}function Le({theme:t,dataLayer:s,children:n}){const a=t?{"data-theme":t}:{};return s?e.jsx("div",{className:"loomcycle-explorer",...a,children:e.jsx(mt,{value:s,children:n})}):e.jsx("div",{className:"loomcycle-explorer",...a,children:e.jsxs("div",{className:"error-banner",children:["@loomcycle/explorer: provide a ",e.jsx("code",{children:"connection"}),", ",e.jsx("code",{children:"client"}),", or"," ",e.jsx("code",{children:"dataLayer"})," prop."]})})}const ke=6;function ht({children:t,defaultLeftWidth:s=380,minLeftWidth:n=180,minRightWidth:a=240,storageKey:r,className:i}){const[o,l]=c.useState(()=>{if(r){const v=localStorage.getItem(r),R=v?parseInt(v,10):NaN;if(Number.isFinite(R)&&R>=n)return R}return s}),u=c.useRef(null),[p,m]=c.useState(!1);c.useEffect(()=>{!r||p||localStorage.setItem(r,String(Math.round(o)))},[r,o,p]);const y=c.useCallback(v=>{v.preventDefault(),m(!0),v.target.setPointerCapture(v.pointerId)},[]),h=c.useCallback(v=>{if(!p||!u.current)return;const R=u.current.getBoundingClientRect(),O=v.clientX-R.left,A=R.width-a-ke,T=Math.max(n,Math.min(O,A));l(T)},[p,n,a]),L=c.useCallback(v=>{m(!1);try{v.target.releasePointerCapture(v.pointerId)}catch{}},[]);return e.jsxs("div",{ref:u,className:`splitter ${i??""} ${p?"dragging":""}`,style:{gridTemplateColumns:`${o}px ${ke}px 1fr`},children:[e.jsx("div",{className:"splitter-pane splitter-left",children:t[0]}),e.jsx("div",{className:"splitter-handle",role:"separator","aria-orientation":"vertical","aria-valuenow":Math.round(o),onPointerDown:y,onPointerMove:h,onPointerUp:L,onPointerCancel:L}),e.jsx("div",{className:"splitter-pane splitter-right",children:t[1]})]})}const ft=["image/png","image/jpeg","image/gif","image/webp"];function Te(t){return ft.includes(t)}function Pe(t){return new Promise((s,n)=>{if(!Te(t.type)){n(new Error(`unsupported image type "${t.type||"unknown"}" (png, jpeg, gif, webp only)`));return}const a=new FileReader;a.onerror=()=>n(a.error??new Error("failed to read file")),a.onload=()=>{const r=String(a.result??""),i=r.indexOf(",");if(i<0){n(new Error("could not decode image data"));return}s({mediaType:t.type,data:r.slice(i+1)})},a.readAsDataURL(t)})}function pt(t){if(!t)return null;for(let s=0;s<t.length;s++){const n=t[s];if(n.kind==="file"&&Te(n.type)){const a=n.getAsFile();if(a)return a}}return null}const re={"doc.rfc.draft":"#c99a3a","doc.rfc.review":"#6a7bd6","doc.rfc.confirmed":"#3a9ad6","doc.rfc.done":"#3aa06a","doc.plan.draft":"#c99a3a","doc.plan.review":"#6a7bd6","doc.plan.confirmed":"#3a9ad6","doc.plan.done":"#3aa06a","doc.document.done":"#3aa06a","doc.research.done":"#8a6ad6","doc.publication.draft":"#c99a3a","chunk.draft":"#c99a3a","chunk.review":"#6a7bd6","chunk.confirmed":"#3a9ad6","chunk.done":"#3aa06a","chunk.backlog":"#8a8f98","chunk.implementation":"#d1863a","chunk.merged":"#3aa06a"},xt=.16;function ce(t){return t&&Object.keys(t).length>0?t:re}function ge(t,s,n){const a=t??"",r=s??"";if(a&&r&&n[`doc.${a}.${r}`])return n[`doc.${a}.${r}`];if(a&&n[`doc.${a}`])return n[`doc.${a}`]}function Ae(t,s){const n=t??"";return n?s[`chunk.${n}`]:void 0}function Ue(t){const s=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!s)return;let n=s[1];n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]);const a=parseInt(n.slice(0,2),16),r=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${a}, ${r}, ${i}, ${xt})`}function oe(t){if(!t)return;const s=Ue(t);if(s)return{background:s,borderLeft:`3px solid ${t}`}}function gt(t){const s=new Map;t.forEach(r=>s.set(r.id,{row:r,children:[]}));const n=[];t.forEach(r=>{const i=s.get(r.id);r.parent_id&&s.has(r.parent_id)?s.get(r.parent_id).children.push(i):n.push(i)});const a=r=>{r.sort((i,o)=>i.row.position-o.row.position),r.forEach(i=>a(i.children))};return a(n),n}function ve(t){return t==="image"?"🖼":t==="mermaid"?"📊":""}function Oe(t,s){for(const n of t){if(n.row.id===s)return n;const a=Oe(n.children,s);if(a)return a}}function jt({tree:t,selectedId:s,onSelect:n,colorEnabled:a,scheme:r,linkedIds:i}){const[o,l]=c.useState(()=>new Map),u=c.useCallback(m=>{l(y=>{const h=new Map(y);return h.set(m,y.get(m)===!1),h})},[]);c.useEffect(()=>{if(!s)return;const m=yt(t,s);m.length!==0&&l(y=>{let h=!1;const L=new Map(y);for(const v of m)L.get(v)===!1&&(L.set(v,!0),h=!0);return h?L:y})},[t,s]);const p=a?ce(r):null;return t.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"No chunks."})}):e.jsx("ul",{className:"tree chunk-tree",children:t.map(m=>e.jsx(Fe,{node:m,expanded:o,toggle:u,selectedId:s,onSelect:n,tintScheme:p,linkedIds:i},m.row.id))})}function yt(t,s){const n=[],a=(r,i)=>{for(const o of r){if(o.row.id===s)return n.push(...i),!0;if(a(o.children,[...i,o.row.id]))return!0}return!1};return a(t,[]),n}function Fe({node:t,expanded:s,toggle:n,selectedId:a,onSelect:r,tintScheme:i,linkedIds:o}){const l=t.children.length>0,u=s.get(t.row.id)!==!1,p=a===t.row.id,m=i?oe(Ae(t.row.status,i)):void 0,y=o?.has(t.row.id);return e.jsxs("li",{className:`node chunk-node ${p?"selected":""}`,children:[e.jsxs("div",{className:"row chunk-row",style:m,children:[e.jsx("button",{type:"button",className:"tree-caret","aria-label":u?"collapse":"expand",disabled:!l,onClick:h=>{h.stopPropagation(),l&&n(t.row.id)},children:l?u?"▼":"▶":"·"}),e.jsxs("button",{type:"button",className:"chunk-link",onClick:()=>r(t),title:t.row.title,children:[ve(t.row.type)&&e.jsx("span",{className:"chunk-type-icon","aria-hidden":!0,children:ve(t.row.type)}),e.jsx("span",{className:"chunk-title",children:t.row.title||"(untitled)"}),t.row.type&&e.jsx("span",{className:"chunk-badge",children:t.row.type}),t.row.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:t.row.status}),y&&e.jsx("span",{className:"chunk-link-badge",title:"Has cross-reference links","aria-label":"linked",children:"🔗"})]})]}),l&&u&&e.jsx("ul",{className:"children chunk-children",children:t.children.map(h=>e.jsx(Fe,{node:h,expanded:s,toggle:n,selectedId:a,onSelect:r,tintScheme:i,linkedIds:o},h.row.id))})]})}let bt=0;function ie({code:t}){const s=c.useRef(null),[n,a]=c.useState({});return c.useEffect(()=>{let r=!1;return(async()=>{try{const i=(await import("mermaid")).default,o=s.current?.closest("[data-theme]")?.getAttribute("data-theme"),l=o?o==="dark":!0;i.initialize({startOnLoad:!1,theme:l?"dark":"default",securityLevel:"strict"});const{svg:u}=await i.render(`lc-mmd-${bt++}`,t);r||a({svg:u})}catch{r||a({err:!0})}})(),()=>{r=!0}},[t]),n.err?e.jsx("pre",{className:"md-pre md-mermaid-error",title:"diagram failed to render",children:e.jsx("code",{children:t})}):n.svg?e.jsx("div",{ref:s,className:"md-mermaid",dangerouslySetInnerHTML:{__html:n.svg}}):e.jsx("div",{ref:s,className:"md-mermaid md-mermaid-loading",children:"rendering diagram…"})}function kt({chunk:t,scope:s,browse:n,onClose:a,onSaved:r}){const i=X(),[o,l]=c.useState(t.title),[u,p]=c.useState(t.type??""),[m,y]=c.useState(t.status??""),[h,L]=c.useState(t.body??""),[v,R]=c.useState(t.fields?JSON.stringify(t.fields,null,2):""),[O,A]=c.useState((t.tags??[]).join(", ")),[T,M]=c.useState(!1),[U,D]=c.useState(null),[F,E]=c.useState(!1),x=u==="mermaid",_=u==="image"||!!t.asset,[W,H]=c.useState(h);c.useEffect(()=>{if(!x)return;const k=setTimeout(()=>H(h),400);return()=>clearTimeout(k)},[h,x]);const b=async k=>{D(null),M(!0);try{const{mediaType:w,data:$}=await Pe(k),Z=await i.documentSetAsset(t.id,w,$,k.name,s,n);r(Z),a()}catch(w){D(w instanceof Error?w.message:String(w)),M(!1)}},g=x?"Mermaid source":_?"Caption (optional)":"Body (Markdown)",f=async k=>{k.preventDefault(),D(null),E(!1);const w={body:h,title:o,type:u,status:m,tags:O.split(",").map($=>$.trim()).filter($=>$!=="")};if(v.trim()!=="")try{w.fields=JSON.parse(v)}catch{D("fields must be valid JSON");return}M(!0);try{const $=await i.documentUpdateChunk(t.id,t.revision,w,s,n);r($),a()}catch($){const Z=$ instanceof Error?$.message:String($);D(Z),E(/revision conflict/i.test(Z)),M(!1)}};return e.jsx("div",{className:"modal-overlay",onClick:a,children:e.jsxs("form",{className:"modal chunk-editor",onClick:k=>k.stopPropagation(),onSubmit:f,children:[e.jsxs("div",{className:"modal-header sticky-top",children:[e.jsx("h3",{children:"Edit chunk"}),e.jsxs("div",{className:"modal-buttons modal-buttons-top",children:[e.jsx("button",{type:"button",onClick:a,disabled:T,children:"cancel"}),e.jsx("button",{type:"submit",className:"primary",disabled:T,children:T?"saving…":"save"})]})]}),U&&e.jsxs("div",{className:"modal-err",children:[U,F&&" — reopen the chunk to load the latest, then reapply your edit."]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Title"}),e.jsx("input",{className:"path-modal-input",value:o,onChange:k=>l(k.target.value)})]}),e.jsxs("div",{className:"chunk-editor-row",children:[e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Type"}),e.jsx("input",{className:"path-modal-input",value:u,placeholder:"(none)",onChange:k=>p(k.target.value)})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Status"}),e.jsx("input",{className:"path-modal-input",value:m,placeholder:"(none)",onChange:k=>y(k.target.value)})]})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Tags"}),e.jsx("input",{className:"path-modal-input",value:O,placeholder:"comma-separated, nest with a slash: area/sub, priority/high",onChange:k=>A(k.target.value)})]}),_&&e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Replace image"}),e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",disabled:T,onChange:k=>{const w=k.target.files?.[0];w&&b(w)}})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:g}),e.jsx("textarea",{className:"modal-textarea chunk-body-input",rows:x?8:12,value:h,onChange:k=>L(k.target.value)})]}),x&&e.jsxs("div",{className:"path-field",children:[e.jsx("span",{children:"Preview"}),e.jsx("div",{className:"chunk-mermaid-preview",children:W.trim()?e.jsx(ie,{code:W}):e.jsx("p",{className:"doc-empty-body",children:"(enter Mermaid source above)"})})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Fields (JSON, optional)"}),e.jsx("textarea",{className:"modal-textarea chunk-fields-input",rows:4,value:v,placeholder:"{}",onChange:k=>R(k.target.value)})]})]})})}function vt(t){const s=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((t??"").trim());if(!s)return"#888888";let n=s[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),"#"+n.toLowerCase()}function Nt({documentId:t,rootChunkId:s,docType:n,docStatus:a,chunkStatuses:r,scope:i,browse:o,onClose:l,onSaved:u}){const p=X(),[m,y]=c.useState(null),[h,L]=c.useState(!1),[v,R]=c.useState({}),[O,A]=c.useState(!1),[T,M]=c.useState(null),[U,D]=c.useState(null),F=c.useMemo(()=>{const g=new Set(Object.keys(re));n&&g.add(`doc.${n}.${a||"draft"}`);for(const f of r)f&&g.add(`chunk.${f}`);return[...g].sort()},[n,a,r]);c.useEffect(()=>{let g=!1;return p.documentGetChunk(s,i,o).then(f=>{if(g)return;y(f);const k=f.fields??{};L(k.color_enabled===!0);const w=k.color_scheme??{};R({...re,...w})}).catch(f=>!g&&D(f instanceof Error?f.message:String(f))),()=>{g=!0}},[p,s,i,o]);const E=(g,f)=>R(k=>({...k,[g]:f})),x=g=>({...g??{},color_enabled:h,color_scheme:v}),_=async()=>{if(m){A(!0),D(null),M(null);try{await p.documentUpdateChunk(s,m.revision,{fields:x(m.fields)},i,o),u(),l()}catch(g){D(g instanceof Error?g.message:String(g)),A(!1)}}},W=async()=>{if(!n){D("this document has no type to match");return}A(!0),D(null),M(null);try{const{documents:g}=await p.documentsSummary({underPath:"/"},i,o),f=(g??[]).filter(w=>w.type===n&&w.document_id!==t&&w.root_chunk_id);let k=0;for(const w of f)try{const $=await p.documentGetChunk(w.root_chunk_id,i,o);await p.documentUpdateChunk(w.root_chunk_id,$.revision,{fields:x($.fields)},i,o),k++}catch{}M(`Applied to ${k} other ${n} document(s).`),u()}catch(g){D(g instanceof Error?g.message:String(g))}finally{A(!1)}},H=F.filter(g=>g.startsWith("doc.")),b=F.filter(g=>g.startsWith("chunk."));return e.jsx("div",{className:"modal-overlay",onClick:l,children:e.jsxs("div",{className:"modal scheme-editor",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"scheme-editor-head",children:[e.jsx("h3",{children:"Document colors"}),e.jsxs("div",{className:"scheme-editor-actions",children:[e.jsx("button",{type:"button",onClick:l,disabled:O,children:"cancel"}),e.jsx("button",{type:"button",className:"primary",onClick:()=>{_()},disabled:O||!m,children:O?"saving…":"save"})]})]}),U&&e.jsx("div",{className:"modal-err",children:U}),m?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"scheme-toggle",children:[e.jsx("input",{type:"checkbox",checked:h,onChange:g=>L(g.target.checked)}),e.jsx("span",{children:"Enable coloring for this document"})]}),e.jsx("p",{className:"modal-context",children:"Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable."}),e.jsxs("div",{className:"scheme-group",children:[e.jsx("h4",{children:"Document (type · status)"}),H.map(g=>e.jsx(Ne,{label:g.slice(4),value:v[g],onChange:f=>E(g,f)},g))]}),e.jsxs("div",{className:"scheme-group",children:[e.jsx("h4",{children:"Chunks (status)"}),b.map(g=>e.jsx(Ne,{label:g.slice(6),value:v[g],onChange:f=>E(g,f)},g))]}),e.jsxs("div",{className:"scheme-editor-foot",children:[e.jsxs("button",{type:"button",onClick:()=>{W()},disabled:O||!n,title:n?`Apply this palette to every other ${n} document`:"This document has no type",children:["copy to all ",n||"same-type"," documents"]}),T&&e.jsx("span",{className:"scheme-status",children:T})]})]}):e.jsx("p",{className:"modal-context",children:"Loading…"})]})})}function Ne({label:t,value:s,onChange:n}){const a=vt(s);return e.jsxs("label",{className:"scheme-row",children:[e.jsx("input",{type:"color",value:a,onChange:r=>n(r.target.value)}),e.jsx("span",{className:"scheme-key",children:t}),e.jsx("code",{className:"scheme-hex",children:a})]})}const wt=8,Ct=20;function St(t){return/embedder|embedding|vector|semantic|not configured/i.test(t)}function _t({documentId:t,selectedId:s,scope:n,browse:a,onSelectChunk:r}){const i=X(),[o,l]=c.useState(!1),[u,p]=c.useState(!1),[m,y]=c.useState(void 0),[h,L]=c.useState([]),[v,R]=c.useState([]),[O,A]=c.useState(null),[T,M]=c.useState([]),[U,D]=c.useState(!1);c.useEffect(()=>{if(!o||!s)return;const x=s;let _=!1;return p(!0),Promise.allSettled([i.documentBacklinks(x,n,a),i.documentRelated(x,n,a,wt),i.documentUnlinkedMentions(x,n,a,Ct)]).then(([W,H,b])=>{if(!_){if(L(W.status==="fulfilled"?W.value.backlinks??[]:[]),H.status==="fulfilled")R(H.value.related??[]),A(null);else{R([]);const g=H.reason instanceof Error?H.reason.message:String(H.reason);A(St(g)?"semantic search not configured":g)}b.status==="fulfilled"?(M(b.value.unlinked_mentions??[]),D(!!b.value.truncated)):(M([]),D(!1)),y(x),p(!1)}}),()=>{_=!0}},[i,o,s,n,a]);const F=x=>!!x&&x!==t,E=!!(o&&s&&!u&&m===s);return e.jsxs("div",{className:"doc-conn",children:[e.jsxs("button",{type:"button",className:"doc-conn-toggle",onClick:()=>l(x=>!x),children:[o?"▼":"▶"," Connections"]}),o&&e.jsx("div",{className:"doc-conn-body",children:s?E?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Backlinks"}),h.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsx("ul",{className:"doc-conn-list",children:h.map((x,_)=>e.jsxs("li",{className:"doc-conn-row",children:[e.jsx(he,{id:x.from_id,title:x.from_title,crossDoc:F(x.from_document_id),onSelect:r}),e.jsx("span",{className:"doc-ref-kind",children:x.kind}),x.auto&&e.jsx("span",{className:"doc-conn-auto",title:"Auto-linked from a [[wikilink]]",children:"auto"})]},`${x.from_id}-${x.kind}-${_}`))})]}),e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Related"}),O?e.jsx("p",{className:"doc-conn-empty",children:O}):v.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsx("ul",{className:"doc-conn-list",children:v.map((x,_)=>e.jsxs("li",{className:"doc-conn-row",children:[e.jsx(he,{id:x.chunk_id,title:x.title,crossDoc:F(x.document_id),onSelect:r}),e.jsx("span",{className:"doc-conn-score",title:"similarity score",children:x.score.toFixed(2)})]},`${x.chunk_id}-${_}`))})]}),e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Unlinked mentions"}),T.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsxs("ul",{className:"doc-conn-list",children:[T.map((x,_)=>e.jsx("li",{className:"doc-conn-row",children:e.jsx(he,{id:x.chunk_id,title:x.title,crossDoc:F(x.document_id),onSelect:r})},`${x.chunk_id}-${_}`)),U&&e.jsx("li",{className:"doc-conn-more","aria-hidden":!0,children:"(more…)"})]})]})]}):e.jsx("p",{className:"doc-conn-empty",children:"loading…"}):e.jsx("p",{className:"doc-conn-empty",children:"Select a chunk."})})]})}function he({id:t,title:s,crossDoc:n,onSelect:a}){const r=s||t.slice(0,8);return n?e.jsxs("span",{className:"doc-ref-target external",title:"In another document",children:[r," ↗"]}):e.jsx("button",{type:"button",className:"doc-ref-target",onClick:()=>a(t),children:r})}const fe=24;function Et({edges:t,documentId:s,selectedId:n,onSelectChunk:a}){const[r,i]=c.useState(!1),[o,l]=c.useState(!1);if(t.length===0)return null;const u=n?t.filter(y=>y.from_id===n||y.to_id===n):[],p=o?t:t.slice(0,fe),m=Dt(p);return e.jsxs("div",{className:"doc-refs",children:[n&&e.jsxs("div",{className:"doc-refs-list-wrap",children:[e.jsx("h4",{children:"References"}),u.length===0?e.jsx("p",{className:"doc-refs-empty",children:"This chunk has no links."}):e.jsx("ul",{className:"doc-refs-list",children:u.map((y,h)=>e.jsx(Mt,{edge:y,selectedId:n,documentId:s,onSelectChunk:a},`${y.from_id}-${y.to_id}-${y.kind}-${h}`))})]}),e.jsxs("div",{className:"doc-graph",children:[e.jsxs("button",{type:"button",className:"doc-graph-toggle",onClick:()=>i(y=>!y),children:[r?"▼":"▶"," relationship graph (",t.length,")"]}),r&&e.jsxs(e.Fragment,{children:[e.jsx(ie,{code:m}),t.length>fe&&e.jsx("button",{type:"button",className:"doc-graph-more",onClick:()=>l(y=>!y),children:o?`show top ${fe}`:`show all ${t.length}`})]})]})]})}function Mt({edge:t,selectedId:s,documentId:n,onSelectChunk:a}){const r=t.from_id===s,i=r?t.to_id:t.from_id,o=(r?t.to_title:t.from_title)||i.slice(0,8),l=r?t.to_document_id:t.from_document_id,u=!l||l===n;return e.jsxs("li",{className:"doc-ref",children:[e.jsx("span",{className:"doc-ref-kind",children:t.kind}),e.jsx("span",{className:"doc-ref-arrow","aria-hidden":!0,children:r?"→":"←"}),u?e.jsx("button",{type:"button",className:"doc-ref-target",onClick:()=>a(i),children:o}):e.jsxs("span",{className:"doc-ref-target external",title:"In another document",children:[o," ↗"]})]})}function Dt(t){const s=["graph LR"];for(const n of t){const a=`${we(n.from_id)}["${Ce(n.from_title,n.from_id)}"]`,r=`${we(n.to_id)}["${Ce(n.to_title,n.to_id)}"]`,i=(n.kind||"link").replace(/[|"]/g," ");s.push(` ${a} -->|${i}| ${r}`)}return s.join(`
2
+ `)}function we(t){return"n"+t.replace(/[^a-zA-Z0-9]/g,"")}function Ce(t,s){const a=(t??"").replace(/["[\]{}|<>]/g," ").replace(/\s+/g," ").trim()||s.slice(0,6);return a.length>30?a.slice(0,29)+"…":a}function Rt(t){const s=typeof t=="number"?t/1e6:Date.parse(String(t));return!Number.isFinite(s)||s<=0?String(t??""):new Date(s).toLocaleString()}function $t({chunkId:t,chunkTitle:s,scope:n,browse:a,onClose:r}){const i=X(),[o,l]=c.useState([]),[u,p]=c.useState(!0),[m,y]=c.useState(null),[h,L]=c.useState("none"),[v,R]=c.useState(null),[O,A]=c.useState(""),[T,M]=c.useState(!1),[U,D]=c.useState(null),[F,E]=c.useState(null),[x,_]=c.useState("");c.useEffect(()=>{let b=!1;return p(!0),y(null),i.documentHistory(t,n,a).then(g=>{if(b)return;const f=g.revisions??[];if(l(f),f.length>=2){const k=f.map(w=>w.revision);D(Math.min(...k)),E(Math.max(...k))}}).catch(g=>!b&&y(g instanceof Error?g.message:String(g))).finally(()=>!b&&p(!1)),()=>{b=!0}},[i,t,n,a]);const W=async b=>{y(null),M(!0),R(b),L("version");try{const g=await i.documentGetVersion(t,b,n,a);A(g.body??"")}catch(g){y(g instanceof Error?g.message:String(g))}finally{M(!1)}},H=async()=>{if(!(U===null||F===null)){y(null),M(!0),L("diff");try{const b=await i.documentDiff(t,U,F,n,a);_(b.diff??"")}catch(b){y(b instanceof Error?b.message:String(b))}finally{M(!1)}}};return e.jsx("div",{className:"modal-overlay",onClick:r,children:e.jsxs("div",{className:"modal history-modal",onClick:b=>b.stopPropagation(),children:[e.jsxs("div",{className:"modal-header sticky-top",children:[e.jsxs("h3",{children:["History",s?` — ${s}`:""]}),e.jsx("div",{className:"modal-buttons modal-buttons-top",children:e.jsx("button",{type:"button",onClick:r,children:"close"})})]}),m&&e.jsx("div",{className:"modal-err",children:m}),u?e.jsx("p",{className:"doc-empty-body",children:"loading…"}):o.length===0?e.jsx("p",{className:"doc-empty-body",children:"No history recorded for this chunk."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"doc-hist-revs",children:o.map(b=>e.jsxs("button",{type:"button",className:"doc-hist-rev"+(h==="version"&&v===b.revision?" active":""),onClick:()=>{W(b.revision)},children:[e.jsxs("span",{className:"doc-hist-rev-num",children:["rev ",b.revision]}),e.jsx("span",{className:"doc-hist-rev-time",children:Rt(b.created_at)}),e.jsx("span",{className:"doc-hist-rev-actor",children:b.actor||"unknown"})]},b.revision))}),o.length>=2&&e.jsxs("div",{className:"doc-hist-diffbar",children:[e.jsx("span",{children:"Compare"}),e.jsx("select",{value:U??"",onChange:b=>D(b.target.value===""?null:Number(b.target.value)),"aria-label":"diff from revision",children:o.map(b=>e.jsxs("option",{value:b.revision,children:["rev ",b.revision]},b.revision))}),e.jsx("span",{"aria-hidden":!0,children:"→"}),e.jsx("select",{value:F??"",onChange:b=>E(b.target.value===""?null:Number(b.target.value)),"aria-label":"diff to revision",children:o.map(b=>e.jsxs("option",{value:b.revision,children:["rev ",b.revision]},b.revision))}),e.jsx("button",{type:"button",onClick:()=>{H()},disabled:T||U===null||F===null,children:"diff"})]}),e.jsx("div",{className:"doc-hist-output",children:T?e.jsx("p",{className:"doc-empty-body",children:"loading…"}):h==="diff"?e.jsx(Lt,{text:x}):h==="version"?e.jsx("pre",{className:"md-pre doc-hist-version",children:e.jsx("code",{children:O||"(empty)"})}):e.jsx("p",{className:"doc-empty-body",children:"Select a revision to view it, or compare two."})})]})]})})}function Lt({text:t}){if(!t.trim())return e.jsx("p",{className:"doc-empty-body",children:"(no differences)"});const s=t.split(`
3
3
  `);return e.jsx("pre",{className:"md-pre doc-hist-diff",children:s.map((n,a)=>{const r=n.startsWith("+")&&!n.startsWith("+++")?"diff-add":n.startsWith("-")&&!n.startsWith("---")?"diff-del":n.startsWith("@@")?"diff-hunk":"";return e.jsxs("span",{className:r,children:[n,`
4
- `]},a)})})}function Se({source:t}){return e.jsx("div",{className:"md",children:e.jsx(lt,{remarkPlugins:[dt],components:Lt,children:t})})}const Lt={a({href:t,children:s}){const n=t??"",a=/^https?:\/\//i.test(n);return e.jsx("a",{href:n,target:a?"_blank":void 0,rel:a?"noopener noreferrer":void 0,children:s})},pre({children:t}){return e.jsx(e.Fragment,{children:t})},code({className:t,children:s}){const n=/language-(\w+)/.exec(t??"")?.[1],a=String(s??"");return n==="mermaid"?e.jsx(ie,{code:a.replace(/\n$/,"")}):n||a.includes(`
5
- `)?e.jsx("pre",{className:"md-pre",children:e.jsx("code",{className:t,children:s})}):e.jsx("code",{children:s})}};function Tt(t){const s=t.fields??{};return typeof s.alt=="string"&&s.alt.trim()!==""?s.alt:t.title||"image"}function Ie({documentId:t,scope:s,titleHint:n,browse:a,principal:r,renderAssistant:i}){const c=X(),l=o.useMemo(()=>a&&(a.scopeId||a.tenant)?{scopeId:a.scopeId,tenant:a.tenant}:void 0,[a?.scopeId,a?.tenant]),[d,p]=o.useState([]),[h,y]=o.useState(void 0),[m,L]=o.useState(null),[v,R]=o.useState("chunks"),[O,A]=o.useState(null),[T,M]=o.useState(null),[U,D]=o.useState(null),F=o.useRef(null),[E,x]=o.useState(null),[_,W]=o.useState(!1),[G,b]=o.useState(!1),[g,f]=o.useState(null),[k,w]=o.useState(!1),[$,Z]=o.useState(0),[K,ee]=o.useState(!1),[V,Y]=o.useState(null),[S,I]=o.useState(!1),[B,q]=o.useState([]),H=o.useCallback(()=>Z(u=>u+1),[]),le=o.useMemo(()=>xt(d),[d]),te=o.useMemo(()=>d.find(j=>!j.parent_id)?.title||n||"document",[d,n]),Q=o.useMemo(()=>!!m&&!m.parent_id,[m]),z=o.useMemo(()=>V?.root_chunk_id??d.find(u=>!u.parent_id)?.id,[V,d]),He=o.useMemo(()=>[...new Set(d.map(u=>u.status).filter(u=>!!u))],[d]),ne=!!V?.color_enabled,We=o.useMemo(()=>{const u=new Set;for(const j of B)u.add(j.from_id),u.add(j.to_id);return u},[B]),Ve=o.useMemo(()=>ne?ce(ge(V?.type,V?.status,oe(V?.color_scheme))):void 0,[ne,V?.type,V?.status,V?.color_scheme]);o.useEffect(()=>{let u=!1;return w(!0),f(null),c.documentQueryChunks(t,s,l).then(j=>{if(u)return;const N=j.chunks??[];p(N),y(C=>C??N.find(P=>!P.parent_id)?.id)}).catch(j=>!u&&f(j instanceof Error?j.message:String(j))).finally(()=>!u&&w(!1)),()=>{u=!0}},[c,t,s,$,l]),o.useEffect(()=>{let u=!1;return c.documentGet(t,s,l).then(j=>!u&&Y(j)).catch(()=>!u&&Y(null)),()=>{u=!0}},[c,t,s,$,l]),o.useEffect(()=>{let u=!1;return c.documentGetEdges(t,s,l).then(j=>!u&&q(j.edges??[])).catch(()=>!u&&q([])),()=>{u=!0}},[c,t,s,$,l]),o.useEffect(()=>{y(void 0),L(null),A(null),R("chunks"),Y(null),q([])},[t,s]),o.useEffect(()=>{if(!h){L(null);return}let u=!1;return c.documentGetChunk(h,s,l).then(j=>!u&&L(j)).catch(j=>!u&&f(j instanceof Error?j.message:String(j))),()=>{u=!0}},[c,h,s,$,l]),o.useEffect(()=>{const u=m?.type==="image"||!!m?.asset;if(!m||!u||!c.documentAssetObjectUrl){M(null),D(null);return}let j=!1,N=null;return D(null),c.documentAssetObjectUrl(m.id,s,l).then(C=>{if(j){URL.revokeObjectURL(C);return}N=C,M(C)}).catch(C=>!j&&D(C instanceof Error?C.message:String(C))),()=>{j=!0,N&&URL.revokeObjectURL(N)}},[c,m,s,l]),o.useEffect(()=>{if(v!=="markdown"||!h){A(null);return}const u=Oe(le,h);if(!u)return;let j=!1;const N=[],C=(P,se)=>{N.push({node:P,depth:se}),P.children.forEach(ae=>C(ae,se+1))};return C(u,0),Promise.all(N.map(P=>c.documentGetChunk(P.node.row.id,s,l))).then(P=>{if(j)return;const se=N.map((ae,Ye)=>{const Ke=Math.min(ae.depth+1,6),J=P[Ye],me="#".repeat(Ke)+" "+ae.node.row.title;if(J.type==="mermaid"&&J.body)return me+"\n\n```mermaid\n"+J.body+"\n```\n";if(J.type==="image"||J.asset){const et=J.body?" — "+J.body:"";return me+`
4
+ `]},a)})})}function Se({source:t}){return e.jsx("div",{className:"md",children:e.jsx(dt,{remarkPlugins:[ut],components:Tt,children:t})})}const Tt={a({href:t,children:s}){const n=t??"",a=/^https?:\/\//i.test(n);return e.jsx("a",{href:n,target:a?"_blank":void 0,rel:a?"noopener noreferrer":void 0,children:s})},pre({children:t}){return e.jsx(e.Fragment,{children:t})},code({className:t,children:s}){const n=/language-(\w+)/.exec(t??"")?.[1],a=String(s??"");return n==="mermaid"?e.jsx(ie,{code:a.replace(/\n$/,"")}):n||a.includes(`
5
+ `)?e.jsx("pre",{className:"md-pre",children:e.jsx("code",{className:t,children:s})}):e.jsx("code",{children:s})}};function Pt(t){const s=t.fields??{};return typeof s.alt=="string"&&s.alt.trim()!==""?s.alt:t.title||"image"}function Ie({documentId:t,scope:s,titleHint:n,browse:a,principal:r,renderAssistant:i}){const o=X(),l=c.useMemo(()=>a&&(a.scopeId||a.tenant)?{scopeId:a.scopeId,tenant:a.tenant}:void 0,[a?.scopeId,a?.tenant]),[u,p]=c.useState([]),[m,y]=c.useState(void 0),[h,L]=c.useState(null),[v,R]=c.useState("chunks"),[O,A]=c.useState(null),[T,M]=c.useState(null),[U,D]=c.useState(null),F=c.useRef(null),[E,x]=c.useState(null),[_,W]=c.useState(!1),[H,b]=c.useState(!1),[g,f]=c.useState(null),[k,w]=c.useState(!1),[$,Z]=c.useState(0),[K,ee]=c.useState(!1),[V,Y]=c.useState(null),[S,I]=c.useState(!1),[B,q]=c.useState([]),G=c.useCallback(()=>Z(d=>d+1),[]),le=c.useMemo(()=>gt(u),[u]),te=c.useMemo(()=>u.find(j=>!j.parent_id)?.title||n||"document",[u,n]),Q=c.useMemo(()=>!!h&&!h.parent_id,[h]),z=c.useMemo(()=>V?.root_chunk_id??u.find(d=>!d.parent_id)?.id,[V,u]),He=c.useMemo(()=>[...new Set(u.map(d=>d.status).filter(d=>!!d))],[u]),ne=!!V?.color_enabled,We=c.useMemo(()=>{const d=new Set;for(const j of B)d.add(j.from_id),d.add(j.to_id);return d},[B]),Ve=c.useMemo(()=>ne?oe(ge(V?.type,V?.status,ce(V?.color_scheme))):void 0,[ne,V?.type,V?.status,V?.color_scheme]);c.useEffect(()=>{let d=!1;return w(!0),f(null),o.documentQueryChunks(t,s,l).then(j=>{if(d)return;const N=j.chunks??[];p(N),y(C=>C??N.find(P=>!P.parent_id)?.id)}).catch(j=>!d&&f(j instanceof Error?j.message:String(j))).finally(()=>!d&&w(!1)),()=>{d=!0}},[o,t,s,$,l]),c.useEffect(()=>{let d=!1;return o.documentGet(t,s,l).then(j=>!d&&Y(j)).catch(()=>!d&&Y(null)),()=>{d=!0}},[o,t,s,$,l]),c.useEffect(()=>{let d=!1;return o.documentGetEdges(t,s,l).then(j=>!d&&q(j.edges??[])).catch(()=>!d&&q([])),()=>{d=!0}},[o,t,s,$,l]),c.useEffect(()=>{y(void 0),L(null),A(null),R("chunks"),Y(null),q([])},[t,s]),c.useEffect(()=>{if(!m){L(null);return}let d=!1;return o.documentGetChunk(m,s,l).then(j=>!d&&L(j)).catch(j=>!d&&f(j instanceof Error?j.message:String(j))),()=>{d=!0}},[o,m,s,$,l]),c.useEffect(()=>{const d=h?.type==="image"||!!h?.asset;if(!h||!d||!o.documentAssetObjectUrl){M(null),D(null);return}let j=!1,N=null;return D(null),o.documentAssetObjectUrl(h.id,s,l).then(C=>{if(j){URL.revokeObjectURL(C);return}N=C,M(C)}).catch(C=>!j&&D(C instanceof Error?C.message:String(C))),()=>{j=!0,N&&URL.revokeObjectURL(N)}},[o,h,s,l]),c.useEffect(()=>{if(v!=="markdown"||!m){A(null);return}const d=Oe(le,m);if(!d)return;let j=!1;const N=[],C=(P,se)=>{N.push({node:P,depth:se}),P.children.forEach(ae=>C(ae,se+1))};return C(d,0),Promise.all(N.map(P=>o.documentGetChunk(P.node.row.id,s,l))).then(P=>{if(j)return;const se=N.map((ae,Ke)=>{const et=Math.min(ae.depth+1,6),J=P[Ke],me="#".repeat(et)+" "+ae.node.row.title;if(J.type==="mermaid"&&J.body)return me+"\n\n```mermaid\n"+J.body+"\n```\n";if(J.type==="image"||J.asset){const tt=J.body?" — "+J.body:"";return me+`
6
6
 
7
- _🖼 image chunk_`+et+`
7
+ _🖼 image chunk_`+tt+`
8
8
  `}return me+(J.body?`
9
9
 
10
10
  `+J.body:"")+`
11
11
  `}).join(`
12
- `);A(se)}).catch(P=>!j&&f(P instanceof Error?P.message:String(P))),()=>{j=!0}},[c,v,h,le,s,$,l]);const qe=o.useCallback(u=>y(u.row.id),[]),ze=o.useCallback(async()=>{try{const u=await c.documentExportMd(t,s,!0,l),j=new Blob([u.markdown],{type:"text/markdown"}),N=URL.createObjectURL(j),C=document.createElement("a");C.href=N,C.download=(u.title||"document").replace(/[^\w.-]+/g,"_")+".md",C.click(),URL.revokeObjectURL(N)}catch(u){f(u instanceof Error?u.message:String(u))}},[c,t,s,l]),Je=o.useCallback(async()=>{try{const u=await c.documentExportCanvas(t,s,l),j=new Blob([JSON.stringify(u.canvas,null,2)],{type:"application/json"}),N=URL.createObjectURL(j),C=document.createElement("a");C.href=N,C.download=(te||"document").replace(/[^\w.-]+/g,"_")+".canvas",C.click(),URL.revokeObjectURL(N)}catch(u){f(u instanceof Error?u.message:String(u))}},[c,t,s,l,te]),de=!!c.documentCreateChunk&&!!z,ue=o.useCallback(async u=>{if(!c.documentCreateChunk||!c.documentSetAsset)return;const j=h||z;if(j){f(null);try{const{mediaType:N,data:C}=await Pe(u),P=await c.documentCreateChunk(t,j,{title:u.name||"image",type:"image"},s,l);await c.documentSetAsset(P.id,N,C,u.name,s,l),H(),y(P.id)}catch(N){f(N instanceof Error?N.message:String(N))}}},[c,t,s,l,h,z,H]),Ze=o.useCallback(async()=>{if(!c.documentCreateChunk)return;const u=h||z;if(u){f(null);try{const j=await c.documentCreateChunk(t,u,{title:"Diagram",type:"mermaid",body:`graph TD
13
- A[Start] --> B[End]`},s,l);H(),y(j.id),x(j)}catch(j){f(j instanceof Error?j.message:String(j))}}},[c,t,s,l,h,z,H]),Qe=o.useCallback(async()=>{if(!c.documentCreateChunk)return;const u=h&&!Q?h:void 0,j=h||z;if(j){f(null);try{const N=await c.documentCreateChunk(t,u?"":j,{title:"Text",body:""},s,l,u);H(),y(N.id),x(N)}catch(N){f(N instanceof Error?N.message:String(N))}}},[c,t,s,l,h,Q,z,H]),je=o.useMemo(()=>{if(!m||Q)return{canUp:!1,canDown:!1};const u=m.parent_id??"",j=d.filter(C=>(C.parent_id??"")===u).sort((C,P)=>C.position-P.position||C.id.localeCompare(P.id)),N=j.findIndex(C=>C.id===m.id);return{canUp:N>0,canDown:N>=0&&N<j.length-1}},[d,m,Q]),ye=o.useCallback(async u=>{if(!(!c.documentReorderChunk||!h)){f(null);try{await c.documentReorderChunk(h,u,s,l),H()}catch(j){f(j instanceof Error?j.message:String(j))}}},[c,h,s,l,H]),Xe=o.useCallback(async()=>{if(!c.documentDeleteChunk||!m)return;f(null);const u=m.parent_id;try{await c.documentDeleteChunk(m.id,s,l),b(!1),y(u||z),H()}catch(j){f(j instanceof Error?j.message:String(j)),b(!1)}},[c,m,s,l,z,H]);return o.useEffect(()=>{if(!de)return;const u=j=>{if(E||S)return;const N=document.activeElement,C=N?.tagName;if(C==="INPUT"||C==="TEXTAREA"||N?.isContentEditable)return;const P=ft(j.clipboardData?.items);P&&(j.preventDefault(),ue(P))};return window.addEventListener("paste",u),()=>window.removeEventListener("paste",u)},[de,E,S,ue]),e.jsxs("div",{className:"doc-viewer",children:[e.jsx("input",{ref:F,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},onChange:u=>{const j=u.target.files?.[0];u.target.value="",j&&ue(j)}}),e.jsxs("div",{className:"doc-toolbar",style:Ve,children:[e.jsx("strong",{className:"doc-title",title:te,children:te}),e.jsxs("div",{className:"doc-toolbar-actions",children:[de&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>{Qe()},title:"Add a text chunk after the selected chunk",children:"+ text"}),e.jsx("button",{type:"button",onClick:()=>F.current?.click(),title:"Add an image chunk (upload — or paste a screenshot into the view)",children:"+ image"}),e.jsx("button",{type:"button",onClick:()=>{Ze()},title:"Add a Mermaid diagram chunk",children:"+ diagram"})]}),e.jsx("button",{type:"button",className:ne?"active":"",onClick:()=>I(!0),disabled:!z,title:"Colors — tint chunk tiles + the Path tree by type/status",children:"colors"}),e.jsx("button",{type:"button",onClick:()=>{ze()},title:"Download the whole document as Markdown (.md)",children:"↓ .md"}),e.jsx("button",{type:"button",onClick:()=>{Je()},title:"Download the whole document as a node/edge canvas graph (.canvas)",children:"↓ .canvas"}),i&&e.jsx("button",{type:"button",className:K?"active":"",onClick:()=>ee(u=>!u),title:"Document Assistant — instruct an agent to restructure/import/link chunks",children:"assistant"}),e.jsx("button",{type:"button",onClick:H,title:"Reload",children:"↻"})]})]}),g&&e.jsx("div",{className:"paths-err",children:g}),e.jsxs("div",{className:"doc-split",children:[e.jsx("div",{className:"doc-chunktree",children:k&&d.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Loading…"})}):e.jsx(gt,{tree:le,selectedId:h,onSelect:qe,colorEnabled:ne,scheme:V?.color_scheme,linkedIds:We})}),e.jsx("div",{className:"doc-content",children:m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"doc-content-head",children:[e.jsx("h3",{children:m.title||"(untitled)"}),e.jsxs("div",{className:"doc-content-meta",children:[m.type&&e.jsx("span",{className:"chunk-badge",children:m.type}),m.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:m.status}),e.jsxs("span",{className:"chunk-rev",children:["rev ",m.revision]}),m.tags?.map(u=>e.jsx("span",{className:"chunk-tag",children:u},u))]}),e.jsxs("div",{className:"doc-content-controls",children:[e.jsxs("div",{className:"doc-mode-toggle",children:[e.jsx("button",{type:"button",className:v==="chunks"?"active":"",onClick:()=>R("chunks"),title:"This chunk's own content",children:"chunk"}),e.jsx("button",{type:"button",className:v==="markdown"?"active":"",onClick:()=>R("markdown"),title:Q?"Whole document as Markdown":"This chunk + its sub-chunks as Markdown",children:"markdown"})]}),e.jsx("button",{type:"button",onClick:()=>x(m),children:"edit"}),e.jsx("button",{type:"button",onClick:()=>W(!0),title:"View this chunk's edit history + diffs",children:"history"}),!Q&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>{ye("up")},disabled:!je.canUp,title:"Move this chunk up within its level",children:"↑"}),e.jsx("button",{type:"button",onClick:()=>{ye("down")},disabled:!je.canDown,title:"Move this chunk down within its level",children:"↓"})]}),!Q&&e.jsx("button",{type:"button",className:"danger",onClick:()=>b(!0),title:"Delete this chunk and its sub-chunks",children:"delete"})]})]}),e.jsx("div",{className:"doc-content-body",children:m.type==="mermaid"?m.body?e.jsxs(e.Fragment,{children:[e.jsx(ie,{code:m.body}),v==="markdown"&&e.jsx("pre",{className:"md-pre doc-mermaid-source",children:e.jsx("code",{children:m.body})})]}):e.jsx("p",{className:"doc-empty-body",children:"(empty diagram)"}):m.type==="image"||m.asset?U?e.jsxs("p",{className:"doc-empty-body",children:["Image failed to load: ",U]}):T?e.jsxs("figure",{className:"doc-image",children:[e.jsx("img",{src:T,alt:Tt(m)}),m.body&&e.jsx("figcaption",{children:m.body})]}):e.jsx("p",{className:"doc-empty-body",children:"Loading image…"}):v==="markdown"?O!==null?e.jsx(Se,{source:O}):e.jsx("p",{className:"doc-empty-body",children:"Assembling Markdown…"}):m.body?e.jsx(Se,{source:m.body}):e.jsx("p",{className:"doc-empty-body",children:"(empty chunk)"})}),e.jsx(_t,{edges:B,documentId:t,selectedId:h,onSelectChunk:y}),e.jsx(St,{documentId:t,selectedId:h,scope:s,browse:l,onSelectChunk:y})]}):e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Select a chunk on the left."})})})]}),K&&i&&e.jsx("div",{className:"doc-assistant",children:i({documentId:t,scope:s,subject:r?.subject,onChanged:H})}),E&&e.jsx(bt,{chunk:E,scope:s,browse:l,onClose:()=>x(null),onSaved:H}),_&&m&&e.jsx(Rt,{chunkId:m.id,chunkTitle:m.title,scope:s,browse:l,onClose:()=>W(!1)}),S&&z&&e.jsx(vt,{documentId:t,rootChunkId:z,docType:V?.type,docStatus:V?.status,chunkStatuses:He,scope:s,browse:l,onClose:()=>I(!1),onSaved:H}),G&&m&&e.jsx("div",{className:"modal-overlay",onClick:()=>b(!1),children:e.jsxs("div",{className:"modal chunk-delete-confirm",onClick:u=>u.stopPropagation(),children:[e.jsx("h3",{children:"Delete chunk"}),e.jsxs("p",{className:"modal-context",children:["Delete “",m.title||"(untitled)","” and all of its sub-chunks? This cannot be undone."]}),e.jsxs("div",{className:"modal-buttons",children:[e.jsx("button",{type:"button",onClick:()=>b(!1),children:"cancel"}),e.jsx("button",{type:"button",className:"danger",onClick:()=>{Xe()},children:"delete"})]})]})})]})}function Pt(t){const s={name:"",fullPath:"",kind:"directory",explicit:!0,children:[]},n=new Map([["",s]]),a=i=>{const c=n.get(i);if(c)return c;const l=i.lastIndexOf("/"),d=l<=0?"":i.slice(0,l),p=i.slice(l+1),h=a(d),y={name:p,fullPath:i,kind:"directory",explicit:!1,children:[]};return h.children.push(y),n.set(i,y),y};for(const i of t){const c=a(i.full_path);c.kind=i.kind,c.explicit=!0,c.resourceRef=i.resource_ref}const r=i=>{i.sort((c,l)=>{const d=c.kind==="directory",p=l.kind==="directory";return d!==p?d?-1:1:c.name.localeCompare(l.name)}),i.forEach(c=>r(c.children))};return r(s.children),s.children}function xe(t){const s=t.lastIndexOf("/");return s<=0?"":t.slice(0,s)}function At(t){const s=[],n=a=>{if(a.kind==="document"){const r=a.resourceRef;r?.document_id&&s.push(r.document_id)}a.children.forEach(n)};return n(t),s}const Ut={directory:"📁",document:"📄",volume_mount:"💾",memory_entry:"🧠"};function Ot({tree:t,selectedPath:s,onSelect:n,summaries:a}){const[r,i]=o.useState(()=>new Map),c=o.useCallback(l=>{i(d=>{const p=new Map(d);return p.set(l,d.get(l)===!1),p})},[]);return o.useEffect(()=>{s&&i(l=>{let d=!1;const p=new Map(l);let h=xe(s);for(;h!=="";)p.get(h)===!1&&(p.set(h,!0),d=!0),h=xe(h);return d?p:l})},[s]),t.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"This tree is empty. Create a folder or document to begin."})}):e.jsx("ul",{className:"tree path-tree",children:t.map(l=>e.jsx(Be,{node:l,expanded:r,toggle:c,selectedPath:s,onSelect:n,summaries:a},l.fullPath))})}function Ft(t,s){if(t.kind!=="document"||!s)return;const n=t.resourceRef;return n?.document_id?s.get(n.document_id):void 0}function Be({node:t,expanded:s,toggle:n,selectedPath:a,onSelect:r,summaries:i}){const c=t.children.length>0,l=s.get(t.fullPath)!==!1,d=a===t.fullPath,p=Ft(t,i),h=p&&p.color_enabled?ce(ge(p.type,p.status,oe(p.color_scheme))):void 0;return e.jsxs("li",{className:`node path-node kind-${t.kind} ${d?"selected":""}`,children:[e.jsxs("div",{className:"row path-row",style:h,children:[e.jsx("button",{type:"button",className:"tree-caret","aria-label":l?"collapse":"expand",disabled:!c,onClick:y=>{y.stopPropagation(),c&&n(t.fullPath)},children:c?l?"▼":"▶":"·"}),e.jsxs("button",{type:"button",className:"path-link",onClick:()=>r(t),title:t.fullPath,children:[e.jsx("span",{className:"path-kind-icon","aria-hidden":!0,children:Ut[t.kind]??"•"}),e.jsx("span",{className:"path-name",children:t.name}),p?.type&&e.jsx("span",{className:"chunk-badge",children:p.type}),p?.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:p.status}),!t.explicit&&e.jsx("span",{className:"path-implicit",title:"Implicit directory (no stored entry)",children:"implicit"})]})]}),c&&l&&e.jsx("ul",{className:"children path-children",children:t.children.map(y=>e.jsx(Be,{node:y,expanded:s,toggle:n,selectedPath:a,onSelect:r,summaries:i},y.fullPath))})]})}const _e=/^[A-Za-z0-9._-]+$/;function Ee(t,s){return`${t}/${s}`}function Ge(t,s){for(const n of t){if(n.fullPath===s)return n;const a=Ge(n.children,s);if(a)return a}}function It(t){const{theme:s,defaultScope:n,path:a,onPathChange:r,browse:i,principal:c,renderAssistant:l,onError:d}=t,p=$e(t);return e.jsx(Le,{theme:s,dataLayer:p,children:e.jsx(Bt,{defaultScope:n,path:a,onPathChange:r,browse:i,principal:c,renderAssistant:l,onError:d})})}function Bt({defaultScope:t,path:s,onPathChange:n,browse:a,principal:r,renderAssistant:i,onError:c}){const l=X(),[d,p]=o.useState(t??"user"),[h,y]=o.useState([]),[m,L]=o.useState(void 0),[v,R]=o.useState(null),[O,A]=o.useState(!1),[T,M]=o.useState(null),U=s!==void 0?s:m,D=o.useRef(n);o.useEffect(()=>{D.current=n},[n]);const F=o.useRef(c);o.useEffect(()=>{F.current=c},[c]);const E=o.useCallback(S=>{D.current?.(S),L(S)},[]),x=o.useMemo(()=>a&&(a.scopeId||a.tenant)?{scopeId:a.scopeId,tenant:a.tenant}:void 0,[a?.scopeId,a?.tenant]),_=o.useCallback(async()=>{A(!0),R(null);try{const S=await l.pathLs("/",d,!0,x);y(S.entries??[])}catch(S){R(S instanceof Error?S.message:String(S)),y([]),F.current?.(S)}finally{A(!1)}},[l,d,x]),W=o.useRef(!0);o.useEffect(()=>{W.current?W.current=!1:E(void 0),_()},[_,E]);const G=o.useMemo(()=>Pt(h),[h]),[b,g]=o.useState(()=>new Map);o.useEffect(()=>{if(d==="tenant"){g(new Map);return}const S=h.filter(B=>B.kind==="document").map(B=>B.resource_ref?.document_id).filter(B=>!!B);if(S.length===0){g(new Map);return}let I=!1;return l.documentsSummary({documentIds:S},d,x).then(B=>{if(I)return;const q=new Map;for(const H of B.documents??[])q.set(H.document_id,H);g(q)}).catch(()=>{I||g(new Map)}),()=>{I=!0}},[l,h,d,x]);const f=o.useMemo(()=>U?Ge(G,U):void 0,[G,U]),k=o.useMemo(()=>f?f.kind==="directory"?f.fullPath:xe(f.fullPath):"",[f]),w=k||"/",$=d!=="tenant",Z=o.useCallback(()=>{M({title:`New folder in ${w}`,fields:[{key:"name",label:"Folder name",placeholder:"e.g. launches"}],submitLabel:"Create",onSubmit:async S=>{const I=S.name.trim();if(!_e.test(I))throw new Error("name may contain only [A-Za-z0-9._-]");const B=Ee(k,I);await l.pathMkdir(B,d,x),await _(),E(B)}})},[l,k,w,d,x,_,E]),K=o.useCallback(()=>{M({title:`New document in ${w}`,fields:[{key:"name",label:"Path name",placeholder:"e.g. launch-plan"},{key:"title",label:"Title",placeholder:"e.g. Launch Plan"}],submitLabel:"Create",onSubmit:async S=>{const I=S.name.trim();if(!_e.test(I))throw new Error("name may contain only [A-Za-z0-9._-]");const B=S.title.trim()||I,q=Ee(k,I);await l.documentCreate(B,q,d,x),await _(),E(q)}})},[l,k,w,d,x,_,E]),ee=o.useCallback(()=>{f&&M({title:`Rename / move ${f.fullPath}`,fields:[{key:"to",label:"New path",value:f.fullPath}],submitLabel:"Move",onSubmit:async S=>{const I=S.to.trim();if(!I.startsWith("/"))throw new Error("path must start with /");await l.pathMv(f.fullPath,I,d,x),await _(),E(I)}})},[l,f,d,x,_,E]),V=o.useCallback(()=>{if(!f)return;if(f.kind==="document"){const q=f.resourceRef?.document_id;M({title:`Delete document ${f.fullPath}`,message:"This deletes the document, all its chunks, and its path entry. This cannot be undone.",fields:[],submitLabel:"Delete",danger:!0,onSubmit:async()=>{if(!q)throw new Error("this document dirent has no document_id");await l.documentDelete(q,d,x),await _(),E(void 0)}});return}const S=d==="tenant"?[]:At(f),I=f.children.length;M({title:`Delete branch ${f.fullPath}`,message:I===0?"This removes the (empty) folder.":"This removes the folder and everything under it"+(S.length>0?` — including ${S.length} document(s), whose chunks are deleted.`:"."),fields:[],submitLabel:"Delete",danger:!0,onSubmit:async()=>{for(const B of S)await l.documentDelete(B,d,x);await l.pathRm(f.fullPath,d,!0,x),await _(),E(void 0)}})},[l,f,d,x,_,E]),Y=f&&(f.kind==="directory"||f.kind==="document");return e.jsxs(e.Fragment,{children:[e.jsxs(mt,{className:"paths-view",defaultLeftWidth:420,minLeftWidth:280,minRightWidth:300,storageKey:"loomcycle.explorer.split.paths",children:[e.jsxs("div",{className:"left",children:[e.jsxs("div",{className:"paths-toolbar",children:[e.jsxs("label",{className:"paths-scope",children:[e.jsx("span",{children:"scope"}),e.jsxs("select",{value:d,onChange:S=>p(S.target.value),children:[e.jsx("option",{value:"user",children:"user"}),e.jsx("option",{value:"agent",children:"agent"}),e.jsx("option",{value:"tenant",children:"tenant"})]})]}),e.jsxs("div",{className:"paths-toolbar-actions",children:[e.jsx("button",{type:"button",onClick:Z,title:`New folder in ${w}`,children:"+ folder"}),e.jsx("button",{type:"button",onClick:K,disabled:!$,title:$?`New document in ${w}`:"Documents are agent/user scope only",children:"+ document"}),e.jsx("button",{type:"button",onClick:()=>{_()},title:"Reload the tree",children:"↻"})]})]}),e.jsxs("p",{className:"paths-context",children:["new items → ",e.jsx("code",{children:w}),x?.scopeId&&e.jsxs(e.Fragment,{children:[" · ","subject ",e.jsx("code",{children:x.scopeId})]}),x?.tenant&&e.jsxs(e.Fragment,{children:[" · ","tenant ",e.jsx("code",{children:x.tenant})]})]}),v&&e.jsx("div",{className:"paths-err",children:v}),O&&h.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Loading…"})}):e.jsx(Ot,{tree:G,selectedPath:U,onSelect:S=>E(S.fullPath),summaries:b})]}),e.jsx("div",{className:"right",children:f?f.kind==="document"?e.jsxs("div",{className:"paths-doc",children:[e.jsxs("div",{className:"paths-doc-head",children:[e.jsx("code",{className:"paths-doc-path",children:f.fullPath}),e.jsxs("div",{className:"paths-detail-actions",children:[e.jsx("button",{type:"button",onClick:ee,children:"rename / move"}),e.jsx("button",{type:"button",className:"danger",onClick:V,children:"delete"})]})]}),e.jsx(Ie,{documentId:f.resourceRef?.document_id??"",scope:d,titleHint:f.name,browse:x,principal:r,renderAssistant:i})]}):e.jsxs("div",{className:"paths-detail",children:[e.jsxs("h2",{children:[e.jsx("span",{className:"paths-detail-kind",children:f.kind}),e.jsx("code",{children:f.fullPath})]}),e.jsxs("dl",{className:"paths-detail-meta",children:[e.jsx("dt",{children:"scope"}),e.jsx("dd",{children:d}),e.jsx("dt",{children:"stored"}),e.jsx("dd",{children:f.explicit?"yes":"implicit (no entry)"})]}),Y?e.jsxs("div",{className:"paths-detail-actions",children:[e.jsx("button",{type:"button",onClick:ee,children:"rename / move"}),e.jsx("button",{type:"button",className:"danger",onClick:V,children:"delete"})]}):e.jsxs("p",{className:"paths-readonly",children:["Read-only — ",f.kind," entries are managed by their own tool."]})]}):e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Select a path on the left, or create a folder / document."})})})]}),T&&e.jsx(Gt,{state:T,onClose:()=>M(null)})]})}function Gt({state:t,onClose:s}){const[n,a]=o.useState(()=>Object.fromEntries(t.fields.map(p=>[p.key,p.value??""]))),[r,i]=o.useState(!1),[c,l]=o.useState(null),d=async p=>{p.preventDefault(),i(!0),l(null);try{await t.onSubmit(n),s()}catch(h){l(h instanceof Error?h.message:String(h)),i(!1)}};return e.jsx("div",{className:"modal-overlay",onClick:s,children:e.jsxs("form",{className:"modal",onClick:p=>p.stopPropagation(),onSubmit:d,children:[e.jsxs("div",{className:"modal-header sticky-top",children:[e.jsx("h3",{children:t.title}),e.jsxs("div",{className:"modal-buttons modal-buttons-top",children:[e.jsx("button",{type:"button",onClick:s,disabled:r,children:"cancel"}),e.jsx("button",{type:"submit",className:t.danger?"danger":"primary",disabled:r,children:r?"working…":t.submitLabel})]})]}),t.message&&e.jsx("p",{className:"modal-context",children:t.message}),t.fields.map((p,h)=>e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:p.label}),e.jsx("input",{className:"path-modal-input",value:n[p.key],placeholder:p.placeholder,autoFocus:h===0,onChange:y=>a(m=>({...m,[p.key]:y.target.value}))})]},p.key)),c&&e.jsx("div",{className:"modal-err",children:c})]})})}function Ht(t){const{documentId:s,scope:n,titleHint:a,browse:r,theme:i,principal:c,renderAssistant:l}=t,d=$e(t);return e.jsx(Le,{theme:i,dataLayer:d,children:e.jsx(Ie,{documentId:s,scope:n,titleHint:a,browse:r,principal:c,renderAssistant:l})})}exports.DEFAULT_SCHEME=re;exports.DocumentViewer=Ht;exports.PathExplorer=It;exports.assetFetchFromConnection=Re;exports.chunkColor=Ae;exports.createLoomcycleClient=De;exports.dataLayerFromClient=pe;exports.docColor=ge;exports.effectiveScheme=oe;exports.hexToTint=Ue;exports.tintStyle=ce;
12
+ `);A(se)}).catch(P=>!j&&f(P instanceof Error?P.message:String(P))),()=>{j=!0}},[o,v,m,le,s,$,l]);const qe=c.useCallback(d=>y(d.row.id),[]),ze=c.useCallback(async()=>{try{const d=await o.documentExportMd(t,s,!0,l),j=new Blob([d.markdown],{type:"text/markdown"}),N=URL.createObjectURL(j),C=document.createElement("a");C.href=N,C.download=(d.title||"document").replace(/[^\w.-]+/g,"_")+".md",C.click(),URL.revokeObjectURL(N)}catch(d){f(d instanceof Error?d.message:String(d))}},[o,t,s,l]),Je=c.useCallback(async()=>{try{const d=await o.documentExportCanvas(t,s,l),j=new Blob([JSON.stringify(d.canvas,null,2)],{type:"application/json"}),N=URL.createObjectURL(j),C=document.createElement("a");C.href=N,C.download=(te||"document").replace(/[^\w.-]+/g,"_")+".canvas",C.click(),URL.revokeObjectURL(N)}catch(d){f(d instanceof Error?d.message:String(d))}},[o,t,s,l,te]),de=!!o.documentCreateChunk&&!!z,ue=c.useCallback(async d=>{if(!o.documentCreateChunk||!o.documentSetAsset)return;const j=m||z;if(j){f(null);try{const{mediaType:N,data:C}=await Pe(d),P=await o.documentCreateChunk(t,j,{title:d.name||"image",type:"image"},s,l);await o.documentSetAsset(P.id,N,C,d.name,s,l),G(),y(P.id)}catch(N){f(N instanceof Error?N.message:String(N))}}},[o,t,s,l,m,z,G]),Ze=c.useCallback(async()=>{if(!o.documentCreateChunk)return;const d=m||z;if(d){f(null);try{const j=await o.documentCreateChunk(t,d,{title:"Diagram",type:"mermaid",body:`graph TD
13
+ A[Start] --> B[End]`},s,l);G(),y(j.id),x(j)}catch(j){f(j instanceof Error?j.message:String(j))}}},[o,t,s,l,m,z,G]),Qe=c.useCallback(async()=>{if(!o.documentCreateChunk)return;const d=m&&!Q?m:void 0,j=m||z;if(j){f(null);try{const N=await o.documentCreateChunk(t,d?"":j,{title:"Text",body:""},s,l,d);G(),y(N.id),x(N)}catch(N){f(N instanceof Error?N.message:String(N))}}},[o,t,s,l,m,Q,z,G]),Xe=c.useCallback(async()=>{if(!(!o.documentCreateChunk||!m)){f(null);try{const d=await o.documentCreateChunk(t,m,{title:"Text",body:""},s,l);G(),y(d.id),x(d)}catch(d){f(d instanceof Error?d.message:String(d))}}},[o,t,s,l,m,G]),je=c.useMemo(()=>{if(!h||Q)return{canUp:!1,canDown:!1};const d=h.parent_id??"",j=u.filter(C=>(C.parent_id??"")===d).sort((C,P)=>C.position-P.position||C.id.localeCompare(P.id)),N=j.findIndex(C=>C.id===h.id);return{canUp:N>0,canDown:N>=0&&N<j.length-1}},[u,h,Q]),ye=c.useCallback(async d=>{if(!(!o.documentReorderChunk||!m)){f(null);try{await o.documentReorderChunk(m,d,s,l),G()}catch(j){f(j instanceof Error?j.message:String(j))}}},[o,m,s,l,G]),Ye=c.useCallback(async()=>{if(!o.documentDeleteChunk||!h)return;f(null);const d=h.parent_id;try{await o.documentDeleteChunk(h.id,s,l),b(!1),y(d||z),G()}catch(j){f(j instanceof Error?j.message:String(j)),b(!1)}},[o,h,s,l,z,G]);return c.useEffect(()=>{if(!de)return;const d=j=>{if(E||S)return;const N=document.activeElement,C=N?.tagName;if(C==="INPUT"||C==="TEXTAREA"||N?.isContentEditable)return;const P=pt(j.clipboardData?.items);P&&(j.preventDefault(),ue(P))};return window.addEventListener("paste",d),()=>window.removeEventListener("paste",d)},[de,E,S,ue]),e.jsxs("div",{className:"doc-viewer",children:[e.jsx("input",{ref:F,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},onChange:d=>{const j=d.target.files?.[0];d.target.value="",j&&ue(j)}}),e.jsxs("div",{className:"doc-toolbar",style:Ve,children:[e.jsx("strong",{className:"doc-title",title:te,children:te}),e.jsxs("div",{className:"doc-toolbar-actions",children:[de&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>{Qe()},title:"Add a text chunk AFTER the selected chunk, at the same level",children:"+ text"}),e.jsx("button",{type:"button",onClick:()=>{Xe()},disabled:!m,title:m?"Add a chunk NESTED UNDER the selected chunk (in the ontology, a child is a subclass)":"Select a chunk first — this nests a new chunk under it",children:"+ child"}),e.jsx("button",{type:"button",onClick:()=>F.current?.click(),title:"Add an image chunk (upload — or paste a screenshot into the view)",children:"+ image"}),e.jsx("button",{type:"button",onClick:()=>{Ze()},title:"Add a Mermaid diagram chunk",children:"+ diagram"})]}),e.jsx("button",{type:"button",className:ne?"active":"",onClick:()=>I(!0),disabled:!z,title:"Colors — tint chunk tiles + the Path tree by type/status",children:"colors"}),e.jsx("button",{type:"button",onClick:()=>{ze()},title:"Download the whole document as Markdown (.md)",children:"↓ .md"}),e.jsx("button",{type:"button",onClick:()=>{Je()},title:"Download the whole document as a node/edge canvas graph (.canvas)",children:"↓ .canvas"}),i&&e.jsx("button",{type:"button",className:K?"active":"",onClick:()=>ee(d=>!d),title:"Document Assistant — instruct an agent to restructure/import/link chunks",children:"assistant"}),e.jsx("button",{type:"button",onClick:G,title:"Reload",children:"↻"})]})]}),g&&e.jsx("div",{className:"paths-err",children:g}),e.jsxs("div",{className:"doc-split",children:[e.jsx("div",{className:"doc-chunktree",children:k&&u.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Loading…"})}):e.jsx(jt,{tree:le,selectedId:m,onSelect:qe,colorEnabled:ne,scheme:V?.color_scheme,linkedIds:We})}),e.jsx("div",{className:"doc-content",children:h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"doc-content-head",children:[e.jsx("h3",{children:h.title||"(untitled)"}),e.jsxs("div",{className:"doc-content-meta",children:[h.type&&e.jsx("span",{className:"chunk-badge",children:h.type}),h.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:h.status}),e.jsxs("span",{className:"chunk-rev",children:["rev ",h.revision]}),h.tags?.map(d=>e.jsx("span",{className:"chunk-tag",children:d},d))]}),e.jsxs("div",{className:"doc-content-controls",children:[e.jsxs("div",{className:"doc-mode-toggle",children:[e.jsx("button",{type:"button",className:v==="chunks"?"active":"",onClick:()=>R("chunks"),title:"This chunk's own content",children:"chunk"}),e.jsx("button",{type:"button",className:v==="markdown"?"active":"",onClick:()=>R("markdown"),title:Q?"Whole document as Markdown":"This chunk + its sub-chunks as Markdown",children:"markdown"})]}),e.jsx("button",{type:"button",onClick:()=>x(h),children:"edit"}),e.jsx("button",{type:"button",onClick:()=>W(!0),title:"View this chunk's edit history + diffs",children:"history"}),!Q&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>{ye("up")},disabled:!je.canUp,title:"Move this chunk up within its level",children:"↑"}),e.jsx("button",{type:"button",onClick:()=>{ye("down")},disabled:!je.canDown,title:"Move this chunk down within its level",children:"↓"})]}),!Q&&e.jsx("button",{type:"button",className:"danger",onClick:()=>b(!0),title:"Delete this chunk and its sub-chunks",children:"delete"})]})]}),e.jsx("div",{className:"doc-content-body",children:h.type==="mermaid"?h.body?e.jsxs(e.Fragment,{children:[e.jsx(ie,{code:h.body}),v==="markdown"&&e.jsx("pre",{className:"md-pre doc-mermaid-source",children:e.jsx("code",{children:h.body})})]}):e.jsx("p",{className:"doc-empty-body",children:"(empty diagram)"}):h.type==="image"||h.asset?U?e.jsxs("p",{className:"doc-empty-body",children:["Image failed to load: ",U]}):T?e.jsxs("figure",{className:"doc-image",children:[e.jsx("img",{src:T,alt:Pt(h)}),h.body&&e.jsx("figcaption",{children:h.body})]}):e.jsx("p",{className:"doc-empty-body",children:"Loading image…"}):v==="markdown"?O!==null?e.jsx(Se,{source:O}):e.jsx("p",{className:"doc-empty-body",children:"Assembling Markdown…"}):h.body?e.jsx(Se,{source:h.body}):e.jsx("p",{className:"doc-empty-body",children:"(empty chunk)"})}),e.jsx(Et,{edges:B,documentId:t,selectedId:m,onSelectChunk:y}),e.jsx(_t,{documentId:t,selectedId:m,scope:s,browse:l,onSelectChunk:y})]}):e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Select a chunk on the left."})})})]}),K&&i&&e.jsx("div",{className:"doc-assistant",children:i({documentId:t,scope:s,subject:r?.subject,onChanged:G})}),E&&e.jsx(kt,{chunk:E,scope:s,browse:l,onClose:()=>x(null),onSaved:G}),_&&h&&e.jsx($t,{chunkId:h.id,chunkTitle:h.title,scope:s,browse:l,onClose:()=>W(!1)}),S&&z&&e.jsx(Nt,{documentId:t,rootChunkId:z,docType:V?.type,docStatus:V?.status,chunkStatuses:He,scope:s,browse:l,onClose:()=>I(!1),onSaved:G}),H&&h&&e.jsx("div",{className:"modal-overlay",onClick:()=>b(!1),children:e.jsxs("div",{className:"modal chunk-delete-confirm",onClick:d=>d.stopPropagation(),children:[e.jsx("h3",{children:"Delete chunk"}),e.jsxs("p",{className:"modal-context",children:["Delete “",h.title||"(untitled)","” and all of its sub-chunks? This cannot be undone."]}),e.jsxs("div",{className:"modal-buttons",children:[e.jsx("button",{type:"button",onClick:()=>b(!1),children:"cancel"}),e.jsx("button",{type:"button",className:"danger",onClick:()=>{Ye()},children:"delete"})]})]})})]})}function At(t){const s={name:"",fullPath:"",kind:"directory",explicit:!0,children:[]},n=new Map([["",s]]),a=i=>{const o=n.get(i);if(o)return o;const l=i.lastIndexOf("/"),u=l<=0?"":i.slice(0,l),p=i.slice(l+1),m=a(u),y={name:p,fullPath:i,kind:"directory",explicit:!1,children:[]};return m.children.push(y),n.set(i,y),y};for(const i of t){const o=a(i.full_path);o.kind=i.kind,o.explicit=!0,o.resourceRef=i.resource_ref}const r=i=>{i.sort((o,l)=>{const u=o.kind==="directory",p=l.kind==="directory";return u!==p?u?-1:1:o.name.localeCompare(l.name)}),i.forEach(o=>r(o.children))};return r(s.children),s.children}function xe(t){const s=t.lastIndexOf("/");return s<=0?"":t.slice(0,s)}function Ut(t){const s=[],n=a=>{if(a.kind==="document"){const r=a.resourceRef;r?.document_id&&s.push(r.document_id)}a.children.forEach(n)};return n(t),s}const Ot={directory:"📁",document:"📄",volume_mount:"💾",memory_entry:"🧠"};function Ft({tree:t,selectedPath:s,onSelect:n,summaries:a}){const[r,i]=c.useState(()=>new Map),o=c.useCallback(l=>{i(u=>{const p=new Map(u);return p.set(l,u.get(l)===!1),p})},[]);return c.useEffect(()=>{s&&i(l=>{let u=!1;const p=new Map(l);let m=xe(s);for(;m!=="";)p.get(m)===!1&&(p.set(m,!0),u=!0),m=xe(m);return u?p:l})},[s]),t.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"This tree is empty. Create a folder or document to begin."})}):e.jsx("ul",{className:"tree path-tree",children:t.map(l=>e.jsx(Be,{node:l,expanded:r,toggle:o,selectedPath:s,onSelect:n,summaries:a},l.fullPath))})}function It(t,s){if(t.kind!=="document"||!s)return;const n=t.resourceRef;return n?.document_id?s.get(n.document_id):void 0}function Be({node:t,expanded:s,toggle:n,selectedPath:a,onSelect:r,summaries:i}){const o=t.children.length>0,l=s.get(t.fullPath)!==!1,u=a===t.fullPath,p=It(t,i),m=p&&p.color_enabled?oe(ge(p.type,p.status,ce(p.color_scheme))):void 0;return e.jsxs("li",{className:`node path-node kind-${t.kind} ${u?"selected":""}`,children:[e.jsxs("div",{className:"row path-row",style:m,children:[e.jsx("button",{type:"button",className:"tree-caret","aria-label":l?"collapse":"expand",disabled:!o,onClick:y=>{y.stopPropagation(),o&&n(t.fullPath)},children:o?l?"▼":"▶":"·"}),e.jsxs("button",{type:"button",className:"path-link",onClick:()=>r(t),title:t.fullPath,children:[e.jsx("span",{className:"path-kind-icon","aria-hidden":!0,children:Ot[t.kind]??"•"}),e.jsx("span",{className:"path-name",children:t.name}),p?.type&&e.jsx("span",{className:"chunk-badge",children:p.type}),p?.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:p.status}),!t.explicit&&e.jsx("span",{className:"path-implicit",title:"Implicit directory (no stored entry)",children:"implicit"})]})]}),o&&l&&e.jsx("ul",{className:"children path-children",children:t.children.map(y=>e.jsx(Be,{node:y,expanded:s,toggle:n,selectedPath:a,onSelect:r,summaries:i},y.fullPath))})]})}const _e=/^[A-Za-z0-9._-]+$/;function Ee(t,s){return`${t}/${s}`}function Ge(t,s){for(const n of t){if(n.fullPath===s)return n;const a=Ge(n.children,s);if(a)return a}}function Bt(t){const{theme:s,defaultScope:n,path:a,onPathChange:r,browse:i,principal:o,renderAssistant:l,onError:u}=t,p=$e(t);return e.jsx(Le,{theme:s,dataLayer:p,children:e.jsx(Gt,{defaultScope:n,path:a,onPathChange:r,browse:i,principal:o,renderAssistant:l,onError:u})})}function Gt({defaultScope:t,path:s,onPathChange:n,browse:a,principal:r,renderAssistant:i,onError:o}){const l=X(),[u,p]=c.useState(t??"user"),[m,y]=c.useState([]),[h,L]=c.useState(void 0),[v,R]=c.useState(null),[O,A]=c.useState(!1),[T,M]=c.useState(null),U=s!==void 0?s:h,D=c.useRef(n);c.useEffect(()=>{D.current=n},[n]);const F=c.useRef(o);c.useEffect(()=>{F.current=o},[o]);const E=c.useCallback(S=>{D.current?.(S),L(S)},[]),x=c.useMemo(()=>a&&(a.scopeId||a.tenant)?{scopeId:a.scopeId,tenant:a.tenant}:void 0,[a?.scopeId,a?.tenant]),_=c.useCallback(async()=>{A(!0),R(null);try{const S=await l.pathLs("/",u,!0,x);y(S.entries??[])}catch(S){R(S instanceof Error?S.message:String(S)),y([]),F.current?.(S)}finally{A(!1)}},[l,u,x]),W=c.useRef(!0);c.useEffect(()=>{W.current?W.current=!1:E(void 0),_()},[_,E]);const H=c.useMemo(()=>At(m),[m]),[b,g]=c.useState(()=>new Map);c.useEffect(()=>{if(u==="tenant"){g(new Map);return}const S=m.filter(B=>B.kind==="document").map(B=>B.resource_ref?.document_id).filter(B=>!!B);if(S.length===0){g(new Map);return}let I=!1;return l.documentsSummary({documentIds:S},u,x).then(B=>{if(I)return;const q=new Map;for(const G of B.documents??[])q.set(G.document_id,G);g(q)}).catch(()=>{I||g(new Map)}),()=>{I=!0}},[l,m,u,x]);const f=c.useMemo(()=>U?Ge(H,U):void 0,[H,U]),k=c.useMemo(()=>f?f.kind==="directory"?f.fullPath:xe(f.fullPath):"",[f]),w=k||"/",$=u!=="tenant",Z=c.useCallback(()=>{M({title:`New folder in ${w}`,fields:[{key:"name",label:"Folder name",placeholder:"e.g. launches"}],submitLabel:"Create",onSubmit:async S=>{const I=S.name.trim();if(!_e.test(I))throw new Error("name may contain only [A-Za-z0-9._-]");const B=Ee(k,I);await l.pathMkdir(B,u,x),await _(),E(B)}})},[l,k,w,u,x,_,E]),K=c.useCallback(()=>{M({title:`New document in ${w}`,fields:[{key:"name",label:"Path name",placeholder:"e.g. launch-plan"},{key:"title",label:"Title",placeholder:"e.g. Launch Plan"}],submitLabel:"Create",onSubmit:async S=>{const I=S.name.trim();if(!_e.test(I))throw new Error("name may contain only [A-Za-z0-9._-]");const B=S.title.trim()||I,q=Ee(k,I);await l.documentCreate(B,q,u,x),await _(),E(q)}})},[l,k,w,u,x,_,E]),ee=c.useCallback(()=>{f&&M({title:`Rename / move ${f.fullPath}`,fields:[{key:"to",label:"New path",value:f.fullPath}],submitLabel:"Move",onSubmit:async S=>{const I=S.to.trim();if(!I.startsWith("/"))throw new Error("path must start with /");await l.pathMv(f.fullPath,I,u,x),await _(),E(I)}})},[l,f,u,x,_,E]),V=c.useCallback(()=>{if(!f)return;if(f.kind==="document"){const q=f.resourceRef?.document_id;M({title:`Delete document ${f.fullPath}`,message:"This deletes the document, all its chunks, and its path entry. This cannot be undone.",fields:[],submitLabel:"Delete",danger:!0,onSubmit:async()=>{if(!q)throw new Error("this document dirent has no document_id");await l.documentDelete(q,u,x),await _(),E(void 0)}});return}const S=u==="tenant"?[]:Ut(f),I=f.children.length;M({title:`Delete branch ${f.fullPath}`,message:I===0?"This removes the (empty) folder.":"This removes the folder and everything under it"+(S.length>0?` — including ${S.length} document(s), whose chunks are deleted.`:"."),fields:[],submitLabel:"Delete",danger:!0,onSubmit:async()=>{for(const B of S)await l.documentDelete(B,u,x);await l.pathRm(f.fullPath,u,!0,x),await _(),E(void 0)}})},[l,f,u,x,_,E]),Y=f&&(f.kind==="directory"||f.kind==="document");return e.jsxs(e.Fragment,{children:[e.jsxs(ht,{className:"paths-view",defaultLeftWidth:420,minLeftWidth:280,minRightWidth:300,storageKey:"loomcycle.explorer.split.paths",children:[e.jsxs("div",{className:"left",children:[e.jsxs("div",{className:"paths-toolbar",children:[e.jsxs("label",{className:"paths-scope",children:[e.jsx("span",{children:"scope"}),e.jsxs("select",{value:u,onChange:S=>p(S.target.value),children:[e.jsx("option",{value:"user",children:"user"}),e.jsx("option",{value:"agent",children:"agent"}),e.jsx("option",{value:"tenant",children:"tenant"})]})]}),e.jsxs("div",{className:"paths-toolbar-actions",children:[e.jsx("button",{type:"button",onClick:Z,title:`New folder in ${w}`,children:"+ folder"}),e.jsx("button",{type:"button",onClick:K,disabled:!$,title:$?`New document in ${w}`:"Documents are agent/user scope only",children:"+ document"}),e.jsx("button",{type:"button",onClick:()=>{_()},title:"Reload the tree",children:"↻"})]})]}),e.jsxs("p",{className:"paths-context",children:["new items → ",e.jsx("code",{children:w}),x?.scopeId&&e.jsxs(e.Fragment,{children:[" · ","subject ",e.jsx("code",{children:x.scopeId})]}),x?.tenant&&e.jsxs(e.Fragment,{children:[" · ","tenant ",e.jsx("code",{children:x.tenant})]})]}),v&&e.jsx("div",{className:"paths-err",children:v}),O&&m.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Loading…"})}):e.jsx(Ft,{tree:H,selectedPath:U,onSelect:S=>E(S.fullPath),summaries:b})]}),e.jsx("div",{className:"right",children:f?f.kind==="document"?e.jsxs("div",{className:"paths-doc",children:[e.jsxs("div",{className:"paths-doc-head",children:[e.jsx("code",{className:"paths-doc-path",children:f.fullPath}),e.jsxs("div",{className:"paths-detail-actions",children:[e.jsx("button",{type:"button",onClick:ee,children:"rename / move"}),e.jsx("button",{type:"button",className:"danger",onClick:V,children:"delete"})]})]}),e.jsx(Ie,{documentId:f.resourceRef?.document_id??"",scope:u,titleHint:f.name,browse:x,principal:r,renderAssistant:i})]}):e.jsxs("div",{className:"paths-detail",children:[e.jsxs("h2",{children:[e.jsx("span",{className:"paths-detail-kind",children:f.kind}),e.jsx("code",{children:f.fullPath})]}),e.jsxs("dl",{className:"paths-detail-meta",children:[e.jsx("dt",{children:"scope"}),e.jsx("dd",{children:u}),e.jsx("dt",{children:"stored"}),e.jsx("dd",{children:f.explicit?"yes":"implicit (no entry)"})]}),Y?e.jsxs("div",{className:"paths-detail-actions",children:[e.jsx("button",{type:"button",onClick:ee,children:"rename / move"}),e.jsx("button",{type:"button",className:"danger",onClick:V,children:"delete"})]}):e.jsxs("p",{className:"paths-readonly",children:["Read-only — ",f.kind," entries are managed by their own tool."]})]}):e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Select a path on the left, or create a folder / document."})})})]}),T&&e.jsx(Ht,{state:T,onClose:()=>M(null)})]})}function Ht({state:t,onClose:s}){const[n,a]=c.useState(()=>Object.fromEntries(t.fields.map(p=>[p.key,p.value??""]))),[r,i]=c.useState(!1),[o,l]=c.useState(null),u=async p=>{p.preventDefault(),i(!0),l(null);try{await t.onSubmit(n),s()}catch(m){l(m instanceof Error?m.message:String(m)),i(!1)}};return e.jsx("div",{className:"modal-overlay",onClick:s,children:e.jsxs("form",{className:"modal",onClick:p=>p.stopPropagation(),onSubmit:u,children:[e.jsxs("div",{className:"modal-header sticky-top",children:[e.jsx("h3",{children:t.title}),e.jsxs("div",{className:"modal-buttons modal-buttons-top",children:[e.jsx("button",{type:"button",onClick:s,disabled:r,children:"cancel"}),e.jsx("button",{type:"submit",className:t.danger?"danger":"primary",disabled:r,children:r?"working…":t.submitLabel})]})]}),t.message&&e.jsx("p",{className:"modal-context",children:t.message}),t.fields.map((p,m)=>e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:p.label}),e.jsx("input",{className:"path-modal-input",value:n[p.key],placeholder:p.placeholder,autoFocus:m===0,onChange:y=>a(h=>({...h,[p.key]:y.target.value}))})]},p.key)),o&&e.jsx("div",{className:"modal-err",children:o})]})})}function Wt(t){const{documentId:s,scope:n,titleHint:a,browse:r,theme:i,principal:o,renderAssistant:l}=t,u=$e(t);return e.jsx(Le,{theme:i,dataLayer:u,children:e.jsx(Ie,{documentId:s,scope:n,titleHint:a,browse:r,principal:o,renderAssistant:l})})}exports.DEFAULT_SCHEME=re;exports.DocumentViewer=Wt;exports.PathExplorer=Bt;exports.assetFetchFromConnection=Re;exports.chunkColor=Ae;exports.createLoomcycleClient=De;exports.dataLayerFromClient=pe;exports.docColor=ge;exports.effectiveScheme=ce;exports.hexToTint=Ue;exports.tintStyle=oe;
14
14
  //# sourceMappingURL=index.cjs.map