@loomcycle/explorer 0.6.0 → 0.9.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/DocumentViewer.d.ts +6 -0
- package/dist/components/ChunkTarget.d.ts +9 -0
- package/dist/components/Connections.d.ts +2 -1
- package/dist/components/CrossReferences.d.ts +15 -1
- package/dist/components/DocTrail.d.ts +6 -0
- package/dist/components/DocUnavailable.d.ts +6 -0
- package/dist/components/DocumentViewerBody.d.ts +5 -1
- package/dist/components/IdCopy.d.ts +7 -0
- package/dist/components/Mermaid.d.ts +3 -1
- package/dist/components/PathTree.d.ts +9 -6
- package/dist/index.cjs +10 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1791 -1228
- package/dist/index.js.map +1 -1
- package/dist/lib/clipboard.d.ts +1 -0
- package/dist/lib/dataLayer.d.ts +13 -4
- package/dist/lib/docTrail.d.ts +26 -0
- package/dist/lib/lazyPathTree.d.ts +43 -0
- package/dist/styles.css +192 -0
- package/package.json +2 -2
package/dist/DocumentViewer.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
2
|
import type { AssistantContext, BrowseScope, DocScope, Principal } from "./types";
|
|
3
3
|
import { type ExplorerDataSource } from "./components/ExplorerRoot";
|
|
4
|
+
import { type DocLocation } from "./lib/docTrail";
|
|
4
5
|
export interface DocumentViewerProps extends ExplorerDataSource {
|
|
5
6
|
documentId: string;
|
|
6
7
|
scope: DocScope;
|
|
@@ -16,5 +17,10 @@ export interface DocumentViewerProps extends ExplorerDataSource {
|
|
|
16
17
|
/** Optional Document Assistant slot. Provide it to show an "assistant" toggle
|
|
17
18
|
* that renders the returned node into the panel; omit → no assistant. */
|
|
18
19
|
renderAssistant?: (ctx: AssistantContext) => ReactNode;
|
|
20
|
+
/** Take over "open another document" (a followed cross-document reference),
|
|
21
|
+
* e.g. to route to it. `target` is the document + chunk to open; `from` is
|
|
22
|
+
* the document being left, with the chunk selected in it. Omit → the viewer
|
|
23
|
+
* swaps the document itself and keeps a breadcrumb trail back. */
|
|
24
|
+
onOpenDocument?: (target: DocLocation, from: DocLocation) => void;
|
|
19
25
|
}
|
|
20
26
|
export default function DocumentViewer(props: DocumentViewerProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface ChunkTargetProps {
|
|
2
|
+
id: string;
|
|
3
|
+
title?: string;
|
|
4
|
+
targetDocumentId?: string;
|
|
5
|
+
documentId: string;
|
|
6
|
+
onSelectChunk: (id: string) => void;
|
|
7
|
+
onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;
|
|
8
|
+
}
|
|
9
|
+
export default function ChunkTarget({ id, title, targetDocumentId, documentId, onSelectChunk, onOpenDocument, }: ChunkTargetProps): import("react").JSX.Element;
|
|
@@ -5,5 +5,6 @@ export interface ConnectionsProps {
|
|
|
5
5
|
scope: DocScope;
|
|
6
6
|
browse?: BrowseScope;
|
|
7
7
|
onSelectChunk: (id: string) => void;
|
|
8
|
+
onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;
|
|
8
9
|
}
|
|
9
|
-
export default function Connections({ documentId, selectedId, scope, browse, onSelectChunk, }: ConnectionsProps): import("react").JSX.Element;
|
|
10
|
+
export default function Connections({ documentId, selectedId, scope, browse, onSelectChunk, onOpenDocument, }: ConnectionsProps): import("react").JSX.Element;
|
|
@@ -4,5 +4,19 @@ export interface CrossReferencesProps {
|
|
|
4
4
|
documentId: string;
|
|
5
5
|
selectedId?: string;
|
|
6
6
|
onSelectChunk: (id: string) => void;
|
|
7
|
+
onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;
|
|
7
8
|
}
|
|
8
|
-
export default function CrossReferences({ edges, documentId, selectedId, onSelectChunk, }: CrossReferencesProps): import("react").JSX.Element | null;
|
|
9
|
+
export default function CrossReferences({ edges, documentId, selectedId, onSelectChunk, onOpenDocument, }: CrossReferencesProps): import("react").JSX.Element | null;
|
|
10
|
+
export declare function RefRow({ edge, selectedId, documentId, onSelectChunk, onOpenDocument, }: {
|
|
11
|
+
edge: DocEdge;
|
|
12
|
+
selectedId: string;
|
|
13
|
+
documentId: string;
|
|
14
|
+
onSelectChunk: (id: string) => void;
|
|
15
|
+
onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;
|
|
16
|
+
}): import("react").JSX.Element;
|
|
17
|
+
export declare function graphEndpoint(edges: DocEdge[], node: string): {
|
|
18
|
+
id: string;
|
|
19
|
+
documentId?: string;
|
|
20
|
+
title?: string;
|
|
21
|
+
} | undefined;
|
|
22
|
+
export declare function nodeId(id: string): string;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
2
|
import type { AssistantContext, BrowseScope, DocScope, Principal } from "../types";
|
|
3
|
+
import { type DocLocation } from "../lib/docTrail";
|
|
3
4
|
export interface DocumentViewerBodyProps {
|
|
4
5
|
documentId: string;
|
|
5
6
|
scope: DocScope;
|
|
@@ -7,5 +8,8 @@ export interface DocumentViewerBodyProps {
|
|
|
7
8
|
browse?: BrowseScope;
|
|
8
9
|
principal?: Principal;
|
|
9
10
|
renderAssistant?: (ctx: AssistantContext) => ReactNode;
|
|
11
|
+
initialChunkId?: string;
|
|
12
|
+
onOpenDocument?: (target: DocLocation, from: DocLocation) => void;
|
|
13
|
+
onTitle?: (documentId: string, title: string) => void;
|
|
10
14
|
}
|
|
11
|
-
export default function DocumentViewerBody({ documentId, scope, titleHint, browse: browseProp, principal, renderAssistant, }: DocumentViewerBodyProps): import("react").JSX.Element;
|
|
15
|
+
export default function DocumentViewerBody({ documentId, scope, titleHint, browse: browseProp, principal, renderAssistant, initialChunkId, onOpenDocument, onTitle, }: DocumentViewerBodyProps): import("react").JSX.Element;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
|
-
export
|
|
2
|
+
export declare function flowchartNode(target: Element | null): string | undefined;
|
|
3
|
+
export default function MermaidDiagram({ code, onNodeClick, }: {
|
|
3
4
|
code: string;
|
|
5
|
+
onNodeClick?: (nodeId: string) => void;
|
|
4
6
|
}): ReactNode;
|
|
@@ -1,20 +1,23 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { DirListing, DirMap } from "../lib/lazyPathTree";
|
|
2
2
|
import { type DocSummary } from "../lib/colorScheme";
|
|
3
3
|
export interface PathNode {
|
|
4
4
|
name: string;
|
|
5
5
|
fullPath: string;
|
|
6
6
|
kind: string;
|
|
7
7
|
resourceRef?: unknown;
|
|
8
|
-
|
|
8
|
+
listing?: DirListing;
|
|
9
9
|
children: PathNode[];
|
|
10
10
|
}
|
|
11
|
-
export declare function
|
|
12
|
-
export declare function parentPathOf(fullPath: string): string;
|
|
13
|
-
export declare function collectDocumentIds(node: PathNode): string[];
|
|
11
|
+
export declare function buildLazyTree(dirs: DirMap, dir?: string): PathNode[];
|
|
14
12
|
export interface PathTreeProps {
|
|
15
13
|
tree: PathNode[];
|
|
14
|
+
root?: DirListing;
|
|
15
|
+
expanded: ReadonlySet<string>;
|
|
16
|
+
onToggle: (dir: string) => void;
|
|
17
|
+
onLoadMore: (dir: string) => void;
|
|
18
|
+
onRetry: (dir: string) => void;
|
|
16
19
|
selectedPath?: string;
|
|
17
20
|
onSelect: (node: PathNode) => void;
|
|
18
21
|
summaries?: Map<string, DocSummary>;
|
|
19
22
|
}
|
|
20
|
-
export default function PathTree(
|
|
23
|
+
export default function PathTree(props: PathTreeProps): import("react").JSX.Element;
|
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
|
|
3
|
-
`);return e.jsx("pre",{className:"md-pre doc-hist-diff",children:
|
|
4
|
-
`]},a)})})}function
|
|
5
|
-
`)?e.jsx("pre",{className:"md-pre",children:e.jsx("code",{className:t,children:
|
|
1
|
+
"use strict";var Mt=Object.create;var Ge=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,Dt=Object.prototype.hasOwnProperty;var Lt=(t,n,s,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Tt(n))!Dt.call(t,r)&&r!==s&&Ge(t,r,{get:()=>n[r],enumerable:!(a=$t(n,r))||a.enumerable});return t};var Pt=(t,n,s)=>(s=t!=null?Mt(Rt(t)):{},Lt(n||!t||!t.__esModule?Ge(s,"default",{value:t,enumerable:!0}):s,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),o=require("react"),It=require("@loomcycle/client"),At=require("react-markdown"),Ot=require("remark-gfm"),Ft=4,Ut=5e3;function Le(t,n){return{pathLs:(s,a,r,c,i)=>t.path({op:"ls",path:s,scope:a,recursive:r,...i?.limit?{limit:i.limit}:{},...i?.cursor?{cursor:i.cursor}:{}},c),pathIsStored:(s,a,r)=>t.path({op:"stat",path:s,scope:a},r).then(()=>!0,c=>{if(c?.name==="SubstrateToolRefusedError")return!1;throw c}),documentPath:async(s,a,r)=>{let c;for(let i=0;i<Ft;i++){const l=await t.path({op:"ls",path:"/",scope:a,recursive:!0,kind_filter:"document",limit:Ut,...c?{cursor:c}:{}},r),f=(l.entries??[]).find(d=>d.resource_ref?.document_id===s);if(f)return f.full_path;if(c=l.next_cursor||void 0,!c)return}},pathMkdir:(s,a,r)=>t.path({op:"mkdir",path:s,scope:a},r),pathMv:(s,a,r,c)=>t.path({op:"mv",path:s,to:a,scope:r},c),pathRm:(s,a,r,c)=>t.path({op:"rm",path:s,scope:a,recursive:r},c),documentCreate:(s,a,r,c)=>t.document({op:"create_document",title:s,path:a,scope:r},c),documentDelete:(s,a,r)=>t.document({op:"delete_document",id:s,scope:a},r),documentGet:(s,a,r)=>t.document({op:"get_document",id:s,scope:a},r),documentsSummary:(s,a,r)=>t.document({op:"documents_summary",scope:a,...s.documentIds?{document_ids:s.documentIds}:{},...s.underPath?{under_path:s.underPath}:{}},r),documentQueryChunks:(s,a,r)=>t.document({op:"query_chunks",document_id:s,scope:a,limit:1e3},r),documentGetChunk:(s,a,r)=>t.document({op:"get_chunk",id:s,scope:a},r),documentCreateChunk:(s,a,r,c,i,l)=>t.document({op:"create_chunk",document_id:s,parent_id:a,scope:c,...l?{after_id:l}:{},...r},i),documentReorderChunk:(s,a,r,c)=>t.document({op:"reorder_chunk",id:s,direction:a,scope:r},c),documentDeleteChunk:(s,a,r)=>t.document({op:"delete_chunk",id:s,scope:a},r),documentSetAsset:(s,a,r,c,i,l)=>t.document({op:"set_asset",id:s,media_type:a,data:r,...c?{filename:c}:{},scope:i},l),documentGetEdges:(s,a,r)=>t.document({op:"get_edges",document_id:s,scope:a},r),documentUpdateChunk:(s,a,r,c,i)=>t.document({op:"update_chunk",id:s,revision:a,scope:c,...r},i),documentExportMd:(s,a,r,c)=>t.document({op:"export_md",document_id:s,scope:a,include_metadata:r},c),documentBacklinks:(s,a,r)=>t.document({op:"backlinks",id:s,scope:a},r),documentRelated:(s,a,r,c)=>t.document({op:"related",id:s,scope:a,...c?{limit:c}:{}},r),documentUnlinkedMentions:(s,a,r,c)=>t.document({op:"unlinked_mentions",id:s,scope:a,...c?{limit:c}:{}},r),documentHistory:(s,a,r,c)=>t.document({op:"history",id:s,scope:a,...c?{limit:c}:{}},r),documentGetVersion:(s,a,r,c)=>t.document({op:"get_version",id:s,revision:a,scope:r},c),documentDiff:(s,a,r,c,i)=>t.document({op:"diff",id:s,from_revision:a,to_revision:r,scope:c},i),documentExportCanvas:(s,a,r)=>t.document({op:"export_canvas",document_id:s,scope:a},r),...n?{documentAssetObjectUrl:async(s,a,r)=>{const c=new URLSearchParams({scope:a});r?.scopeId&&c.set("scope_id",r.scopeId),r?.tenant&&c.set("tenant",r.tenant);const i=await n(`/v1/_document/asset/${encodeURIComponent(s)}?${c.toString()}`);if(!i.ok)throw new Error(`asset fetch failed: ${i.status}`);const l=await i.blob();return URL.createObjectURL(l)}}:{}}}const Ke=o.createContext(null);function Bt({value:t,children:n}){return e.jsx(Ke.Provider,{value:t,children:n})}function he(){const t=o.useContext(Ke);if(!t)throw new Error("useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)");return t}const Pe=500,et=5e3;function Ie(t){return t===""?"/":t}function Gt(t){const n=t.lastIndexOf("/");return n<=0?"":t.slice(0,n)}function tt(t){const n=[""],s=t.split("/").filter(Boolean);let a="";for(let r=0;r<s.length-1;r++)a=`${a}/${s[r]}`,n.push(a);return n}function He(t){return t instanceof Error?t.message:String(t)}function We(t,n){return{entries:[...n,...t.entries??[]],nextCursor:t.next_cursor||void 0,loaded:!0,loading:!1}}class Ht{constructor(n,s,a,r=Pe){this.data=n,this.scope=s,this.browse=a,this.pageLimit=r}data;scope;browse;pageLimit;dirs=new Map;snapshot=new Map;listeners=new Set;inflight=new Map;epoch=new Map;getSnapshot=()=>this.snapshot;subscribe=n=>(this.listeners.add(n),()=>{this.listeners.delete(n)});publish(){this.snapshot=new Map(this.dirs),this.listeners.forEach(n=>n())}set(n,s){this.dirs.set(n,s),this.publish()}track(n,s){const a=s.finally(()=>{this.inflight.get(n)===a&&this.inflight.delete(n)});return this.inflight.set(n,a),a}loadDir(n){const s=this.inflight.get(n);return s||(this.dirs.get(n)?.loaded?Promise.resolve():this.fetchFirst(n,this.pageLimit))}reload(n){const s=this.dirs.get(n),a=s?.entries.length??0,r=s?.loaded&&!s.nextCursor?a+this.pageLimit:a;return this.fetchFirst(n,Math.min(et,Math.max(this.pageLimit,r)))}fetchFirst(n,s){const a=(this.epoch.get(n)??0)+1;this.epoch.set(n,a);const r=this.dirs.get(n);this.set(n,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!0});const c=this.data.pathLs(Ie(n),this.scope,!1,this.browse,{limit:s}).then(i=>{this.epoch.get(n)===a&&this.set(n,We(i,[]))},i=>{throw this.epoch.get(n)===a&&this.set(n,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!1,error:He(i)}),i});return this.track(n,c)}loadMore(n){const s=this.inflight.get(n);if(s)return s;const a=this.dirs.get(n);if(!a?.nextCursor)return Promise.resolve();const r=this.epoch.get(n)??0;this.set(n,{...a,loading:!0,error:void 0});const c=this.data.pathLs(Ie(n),this.scope,!1,this.browse,{limit:this.pageLimit,cursor:a.nextCursor}).then(i=>{this.epoch.get(n)===r&&this.set(n,We(i,a.entries))},i=>{throw this.epoch.get(n)===r&&this.set(n,{...a,loading:!1,error:He(i)}),i});return this.track(n,c)}async reveal(n){const s=n.split("/").filter(Boolean);let a="";for(const r of s){for(await this.loadDir(a);;){const c=this.dirs.get(a);if(!c)return!1;if(c.entries.some(f=>f.name===r))break;const i=c.entries[c.entries.length-1];if(!c.nextCursor||i&&i.name>r)return!1;const l=c.nextCursor;if(await this.loadMore(a),this.dirs.get(a)?.nextCursor===l)return!1}a=`${a}/${r}`}return!0}async invalidate(n,s){if(s?.dropSubtree){for(const r of[...this.dirs.keys()])(r===n||r.startsWith(`${n}/`))&&(this.dirs.delete(r),this.epoch.set(r,(this.epoch.get(r)??0)+1),this.inflight.delete(r));this.publish()}const a=tt(n).filter(r=>this.dirs.has(r));await Promise.all(a.map(r=>this.reload(r)))}async refresh(n){const s=new Set(n);s.add("");for(const r of[...this.dirs.keys()])s.has(r)||(this.dirs.delete(r),this.epoch.set(r,(this.epoch.get(r)??0)+1),this.inflight.delete(r));this.publish();const a=[...s].filter(r=>r===""||this.dirs.has(r));await Promise.all(a.map(r=>this.reload(r)))}}async function Wt(t,n,s,a){const r=[];let c;for(;;){const i=await t.pathLs(Ie(n),s,!0,a,{limit:et,cursor:c});r.push(...i.entries??[]);const l=i.next_cursor||void 0;if(!l||l===c)return r;c=l}}function Ve(t){const n=[];for(const s of t){if(s.kind!=="document")continue;const a=s.resource_ref?.document_id;a&&n.push(a)}return n}function nt(t){const n=t.fetch;return new It.LoomcycleClient({baseUrl:t.baseUrl,authToken:t.token||void 0,fetch:(s,a)=>n?n(s,a):fetch(s,a)})}function st(t){const n=t.fetch,s=(a,r)=>n?n(a,r):fetch(a,r);return a=>{const r={};return t.token&&(r.Authorization=`Bearer ${t.token}`),s(t.baseUrl+a,{headers:r})}}function at(t){const{dataLayer:n,client:s,connection:a}=t;return o.useMemo(()=>n||(s?Le(s):a?Le(nt(a),st(a)):null),[n,s,a?.baseUrl,a?.token,a?.fetch])}function rt({theme:t,dataLayer:n,children:s}){const a=t?{"data-theme":t}:{};return n?e.jsx("div",{className:"loomcycle-explorer",...a,children:e.jsx(Bt,{value:n,children:s})}):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."]})})}function ot(t,n,s){const a=t[t.length-1];return[...a&&a.documentId===n.documentId?[...t.slice(0,-1),{...a,...it(n)}]:[...t,n],s]}function ct(t,n){return n<0||n>=t.length-1?t:t.slice(0,n+1)}function Ae(t,n,s){const a=t[t.length-1];if(!a||a.documentId!==n)return t;const r={...a,...it(s)};return r.title===a.title&&r.path===a.path?t:[...t.slice(0,-1),r]}function it(t){return Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))}function oe(t){return t.title?t.title:t.path?t.path.slice(t.path.lastIndexOf("/")+1)||t.path:t.documentId.slice(0,8)}const Vt=4;function qt(t,n=Vt){const s=Array.from({length:t},(c,i)=>({kind:"crumb",index:i}));if(t<=n||n<3)return s;const a=n-1,r=Array.from({length:t-1-a},(c,i)=>i+1);return[s[0],{kind:"gap",hidden:r},...s.slice(t-a)]}function zt(t,n){for(const s of t.values()){const a=s.entries.find(r=>Jt(r)===n);if(a)return a.full_path}}function Jt(t){if(t.kind==="document")return t.resource_ref?.document_id||void 0}function Zt(t,n){return n&&t.some(s=>s.id===n)?n:t.find(s=>!s.parent_id)?.id}function lt({trail:t,onJump:n}){const[s,a]=o.useState(!1);if(t.length<2)return null;const r=t.length-1,c=t[r-1],i=qt(t.length,s?t.length:void 0);return e.jsxs("nav",{className:"doc-trail","aria-label":"Documents you came through",children:[e.jsx("button",{type:"button",className:"doc-trail-back",onClick:()=>n(r-1),title:`Back to ${oe(c)}`,children:"← Back"}),e.jsx("ol",{className:"doc-trail-list",children:i.map(l=>l.kind==="gap"?e.jsx("li",{className:"doc-trail-item",children:e.jsx("button",{type:"button",className:"doc-trail-gap",onClick:()=>a(!0),title:`Show ${l.hidden.length} more: ${l.hidden.map(f=>oe(t[f])).join(" › ")}`,"aria-label":`Show ${l.hidden.length} hidden documents`,children:"…"})},"gap"):l.index===r?e.jsx("li",{className:"doc-trail-item",children:e.jsx("span",{className:"doc-trail-current","aria-current":"page",title:oe(t[r]),children:oe(t[r])})},l.index):e.jsx("li",{className:"doc-trail-item",children:e.jsx("button",{type:"button",className:"doc-trail-crumb",onClick:()=>n(l.index),title:oe(t[l.index]),children:oe(t[l.index])})},l.index))})]})}const qe=6;function Xt({children:t,defaultLeftWidth:n=380,minLeftWidth:s=180,minRightWidth:a=240,storageKey:r,className:c}){const[i,l]=o.useState(()=>{if(r){const y=localStorage.getItem(r),x=y?parseInt(y,10):NaN;if(Number.isFinite(x)&&x>=s)return x}return n}),f=o.useRef(null),[d,h]=o.useState(!1);o.useEffect(()=>{!r||d||localStorage.setItem(r,String(Math.round(i)))},[r,i,d]);const v=o.useCallback(y=>{y.preventDefault(),h(!0),y.target.setPointerCapture(y.pointerId)},[]),w=o.useCallback(y=>{if(!d||!f.current)return;const x=f.current.getBoundingClientRect(),A=y.clientX-x.left,O=x.width-a-qe,P=Math.max(s,Math.min(A,O));l(P)},[d,s,a]),p=o.useCallback(y=>{h(!1);try{y.target.releasePointerCapture(y.pointerId)}catch{}},[]);return e.jsxs("div",{ref:f,className:`splitter ${c??""} ${d?"dragging":""}`,style:{gridTemplateColumns:`${i}px ${qe}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(i),onPointerDown:v,onPointerMove:w,onPointerUp:p,onPointerCancel:p}),e.jsx("div",{className:"splitter-pane splitter-right",children:t[1]})]})}const Qt=["image/png","image/jpeg","image/gif","image/webp"];function dt(t){return Qt.includes(t)}function ut(t){return new Promise((n,s)=>{if(!dt(t.type)){s(new Error(`unsupported image type "${t.type||"unknown"}" (png, jpeg, gif, webp only)`));return}const a=new FileReader;a.onerror=()=>s(a.error??new Error("failed to read file")),a.onload=()=>{const r=String(a.result??""),c=r.indexOf(",");if(c<0){s(new Error("could not decode image data"));return}n({mediaType:t.type,data:r.slice(c+1)})},a.readAsDataURL(t)})}function Yt(t){if(!t)return null;for(let n=0;n<t.length;n++){const s=t[n];if(s.kind==="file"&&dt(s.type)){const a=s.getAsFile();if(a)return a}}return null}const Ne={"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"},Kt=.16;function Ce(t){return t&&Object.keys(t).length>0?t:Ne}function Fe(t,n,s){const a=t??"",r=n??"";if(a&&r&&s[`doc.${a}.${r}`])return s[`doc.${a}.${r}`];if(a&&s[`doc.${a}`])return s[`doc.${a}`]}function ht(t,n){const s=t??"";return s?n[`chunk.${s}`]:void 0}function mt(t){const n=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!n)return;let s=n[1];s.length===3&&(s=s[0]+s[0]+s[1]+s[1]+s[2]+s[2]);const a=parseInt(s.slice(0,2),16),r=parseInt(s.slice(2,4),16),c=parseInt(s.slice(4,6),16);return`rgba(${a}, ${r}, ${c}, ${Kt})`}function Se(t){if(!t)return;const n=mt(t);if(n)return{background:n,borderLeft:`3px solid ${t}`}}async function en(t){try{return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(t),!0)}catch{return!1}}function Oe({value:t,label:n,compact:s,title:a}){const[r,c]=o.useState("idle"),i=async h=>{h.stopPropagation(),h.preventDefault();const v=await en(t);c(v?"copied":"error"),window.setTimeout(()=>c("idle"),v?1200:1500)},l=r==="copied"?"✓":r==="error"?"✗":"⎘",f=a??`Copy ${n??"id"}: ${t}`,d=e.jsx("button",{type:"button",className:`id-copy-btn id-copy-${r}`,onClick:i,title:f,"aria-label":f,children:l});return s?d:e.jsxs("span",{className:"id-copy",children:[n&&e.jsx("span",{className:"id-copy-label",children:n}),e.jsx("code",{className:"id-copy-value",title:t,children:t}),d]})}function tn(t){const n=new Map;t.forEach(r=>n.set(r.id,{row:r,children:[]}));const s=[];t.forEach(r=>{const c=n.get(r.id);r.parent_id&&n.has(r.parent_id)?n.get(r.parent_id).children.push(c):s.push(c)});const a=r=>{r.sort((c,i)=>c.row.position-i.row.position),r.forEach(c=>a(c.children))};return a(s),s}function ze(t){return t==="image"?"🖼":t==="mermaid"?"📊":""}function ft(t,n){for(const s of t){if(s.row.id===n)return s;const a=ft(s.children,n);if(a)return a}}function nn({tree:t,selectedId:n,onSelect:s,colorEnabled:a,scheme:r,linkedIds:c}){const[i,l]=o.useState(()=>new Map),f=o.useCallback(h=>{l(v=>{const w=new Map(v);return w.set(h,v.get(h)===!1),w})},[]);o.useEffect(()=>{if(!n)return;const h=sn(t,n);h.length!==0&&l(v=>{let w=!1;const p=new Map(v);for(const y of h)p.get(y)===!1&&(p.set(y,!0),w=!0);return w?p:v})},[t,n]);const d=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(h=>e.jsx(pt,{node:h,expanded:i,toggle:f,selectedId:n,onSelect:s,tintScheme:d,linkedIds:c},h.row.id))})}function sn(t,n){const s=[],a=(r,c)=>{for(const i of r){if(i.row.id===n)return s.push(...c),!0;if(a(i.children,[...c,i.row.id]))return!0}return!1};return a(t,[]),s}function pt({node:t,expanded:n,toggle:s,selectedId:a,onSelect:r,tintScheme:c,linkedIds:i}){const l=t.children.length>0,f=n.get(t.row.id)!==!1,d=a===t.row.id,h=c?Se(ht(t.row.status,c)):void 0,v=i?.has(t.row.id);return e.jsxs("li",{className:`node chunk-node ${d?"selected":""}`,children:[e.jsxs("div",{className:"row chunk-row",style:h,children:[e.jsx("button",{type:"button",className:"tree-caret","aria-label":f?"collapse":"expand",disabled:!l,onClick:w=>{w.stopPropagation(),l&&s(t.row.id)},children:l?f?"▼":"▶":"·"}),e.jsxs("button",{type:"button",className:"chunk-link",onClick:()=>r(t),title:t.row.title,children:[ze(t.row.type)&&e.jsx("span",{className:"chunk-type-icon","aria-hidden":!0,children:ze(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}),v&&e.jsx("span",{className:"chunk-link-badge",title:"Has cross-reference links","aria-label":"linked",children:"🔗"})]}),e.jsx(Oe,{value:t.row.id,compact:!0,title:`Copy chunk id: ${t.row.id}`})]}),l&&f&&e.jsx("ul",{className:"children chunk-children",children:t.children.map(w=>e.jsx(pt,{node:w,expanded:n,toggle:s,selectedId:a,onSelect:r,tintScheme:c,linkedIds:i},w.row.id))})]})}let an=0;function rn(t){const n=t?.closest("g.node");return n?/flowchart-(.+)-\d+$/.exec(n.id)?.[1]:void 0}function _e({code:t,onNodeClick:n}){const s=o.useRef(null),[a,r]=o.useState({});return o.useEffect(()=>{let c=!1;return(async()=>{try{const i=(await import("mermaid")).default,l=s.current?.closest("[data-theme]")?.getAttribute("data-theme"),f=l?l==="dark":!0;i.initialize({startOnLoad:!1,theme:f?"dark":"default",securityLevel:"strict"});const{svg:d}=await i.render(`lc-mmd-${an++}`,t);c||r({svg:d})}catch{c||r({err:!0})}})(),()=>{c=!0}},[t]),a.err?e.jsx("pre",{className:"md-pre md-mermaid-error",title:"diagram failed to render",children:e.jsx("code",{children:t})}):a.svg?e.jsx("div",{ref:s,className:n?"md-mermaid md-mermaid-nav":"md-mermaid",onClick:n&&(c=>{const i=rn(c.target);i&&n(i)}),dangerouslySetInnerHTML:{__html:a.svg}}):e.jsx("div",{ref:s,className:"md-mermaid md-mermaid-loading",children:"rendering diagram…"})}function on({chunk:t,scope:n,browse:s,onClose:a,onSaved:r}){const c=he(),[i,l]=o.useState(t.title),[f,d]=o.useState(t.type??""),[h,v]=o.useState(t.status??""),[w,p]=o.useState(t.body??""),[y,x]=o.useState(t.fields?JSON.stringify(t.fields,null,2):""),[A,O]=o.useState((t.tags??[]).join(", ")),[P,B]=o.useState(!1),[W,D]=o.useState(null),[G,H]=o.useState(!1),V=f==="mermaid",N=f==="image"||!!t.asset,[R,C]=o.useState(w);o.useEffect(()=>{if(!V)return;const S=setTimeout(()=>C(w),400);return()=>clearTimeout(S)},[w,V]);const m=async S=>{D(null),B(!0);try{const{mediaType:I,data:T}=await ut(S),X=await c.documentSetAsset(t.id,I,T,S.name,n,s);r(X),a()}catch(I){D(I instanceof Error?I.message:String(I)),B(!1)}},g=V?"Mermaid source":N?"Caption (optional)":"Body (Markdown)",k=async S=>{S.preventDefault(),D(null),H(!1);const I={body:w,title:i,type:f,status:h,tags:A.split(",").map(T=>T.trim()).filter(T=>T!=="")};if(y.trim()!=="")try{I.fields=JSON.parse(y)}catch{D("fields must be valid JSON");return}B(!0);try{const T=await c.documentUpdateChunk(t.id,t.revision,I,n,s);r(T),a()}catch(T){const X=T instanceof Error?T.message:String(T);D(X),H(/revision conflict/i.test(X)),B(!1)}};return e.jsx("div",{className:"modal-overlay",onClick:a,children:e.jsxs("form",{className:"modal chunk-editor",onClick:S=>S.stopPropagation(),onSubmit:k,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:P,children:"cancel"}),e.jsx("button",{type:"submit",className:"primary",disabled:P,children:P?"saving…":"save"})]})]}),W&&e.jsxs("div",{className:"modal-err",children:[W,G&&" — 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:i,onChange:S=>l(S.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:f,placeholder:"(none)",onChange:S=>d(S.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:S=>v(S.target.value)})]})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:"Tags"}),e.jsx("input",{className:"path-modal-input",value:A,placeholder:"comma-separated, nest with a slash: area/sub, priority/high",onChange:S=>O(S.target.value)})]}),N&&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:P,onChange:S=>{const I=S.target.files?.[0];I&&m(I)}})]}),e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:g}),e.jsx("textarea",{className:"modal-textarea chunk-body-input",rows:V?8:12,value:w,onChange:S=>p(S.target.value)})]}),V&&e.jsxs("div",{className:"path-field",children:[e.jsx("span",{children:"Preview"}),e.jsx("div",{className:"chunk-mermaid-preview",children:R.trim()?e.jsx(_e,{code:R}):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:y,placeholder:"{}",onChange:S=>x(S.target.value)})]})]})})}function cn(t){const n=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((t??"").trim());if(!n)return"#888888";let s=n[1];return s.length===3&&(s=s[0]+s[0]+s[1]+s[1]+s[2]+s[2]),"#"+s.toLowerCase()}function ln({documentId:t,rootChunkId:n,docType:s,docStatus:a,chunkStatuses:r,scope:c,browse:i,onClose:l,onSaved:f}){const d=he(),[h,v]=o.useState(null),[w,p]=o.useState(!1),[y,x]=o.useState({}),[A,O]=o.useState(!1),[P,B]=o.useState(null),[W,D]=o.useState(null),G=o.useMemo(()=>{const g=new Set(Object.keys(Ne));s&&g.add(`doc.${s}.${a||"draft"}`);for(const k of r)k&&g.add(`chunk.${k}`);return[...g].sort()},[s,a,r]);o.useEffect(()=>{let g=!1;return d.documentGetChunk(n,c,i).then(k=>{if(g)return;v(k);const S=k.fields??{};p(S.color_enabled===!0);const I=S.color_scheme??{};x({...Ne,...I})}).catch(k=>!g&&D(k instanceof Error?k.message:String(k))),()=>{g=!0}},[d,n,c,i]);const H=(g,k)=>x(S=>({...S,[g]:k})),V=g=>({...g??{},color_enabled:w,color_scheme:y}),N=async()=>{if(h){O(!0),D(null),B(null);try{await d.documentUpdateChunk(n,h.revision,{fields:V(h.fields)},c,i),f(),l()}catch(g){D(g instanceof Error?g.message:String(g)),O(!1)}}},R=async()=>{if(!s){D("this document has no type to match");return}O(!0),D(null),B(null);try{const{documents:g}=await d.documentsSummary({underPath:"/"},c,i),k=(g??[]).filter(I=>I.type===s&&I.document_id!==t&&I.root_chunk_id);let S=0;for(const I of k)try{const T=await d.documentGetChunk(I.root_chunk_id,c,i);await d.documentUpdateChunk(I.root_chunk_id,T.revision,{fields:V(T.fields)},c,i),S++}catch{}B(`Applied to ${S} other ${s} document(s).`),f()}catch(g){D(g instanceof Error?g.message:String(g))}finally{O(!1)}},C=G.filter(g=>g.startsWith("doc.")),m=G.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:A,children:"cancel"}),e.jsx("button",{type:"button",className:"primary",onClick:()=>{N()},disabled:A||!h,children:A?"saving…":"save"})]})]}),W&&e.jsx("div",{className:"modal-err",children:W}),h?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"scheme-toggle",children:[e.jsx("input",{type:"checkbox",checked:w,onChange:g=>p(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)"}),C.map(g=>e.jsx(Je,{label:g.slice(4),value:y[g],onChange:k=>H(g,k)},g))]}),e.jsxs("div",{className:"scheme-group",children:[e.jsx("h4",{children:"Chunks (status)"}),m.map(g=>e.jsx(Je,{label:g.slice(6),value:y[g],onChange:k=>H(g,k)},g))]}),e.jsxs("div",{className:"scheme-editor-foot",children:[e.jsxs("button",{type:"button",onClick:()=>{R()},disabled:A||!s,title:s?`Apply this palette to every other ${s} document`:"This document has no type",children:["copy to all ",s||"same-type"," documents"]}),P&&e.jsx("span",{className:"scheme-status",children:P})]})]}):e.jsx("p",{className:"modal-context",children:"Loading…"})]})})}function Je({label:t,value:n,onChange:s}){const a=cn(n);return e.jsxs("label",{className:"scheme-row",children:[e.jsx("input",{type:"color",value:a,onChange:r=>s(r.target.value)}),e.jsx("span",{className:"scheme-key",children:t}),e.jsx("code",{className:"scheme-hex",children:a})]})}function xt({id:t,title:n,targetDocumentId:s,documentId:a,onSelectChunk:r,onOpenDocument:c}){const i=n||t.slice(0,8);return!s||s===a?e.jsx("button",{type:"button",className:"doc-ref-target",onClick:()=>r(t),children:i}):c?e.jsxs("button",{type:"button",className:"doc-ref-target external",title:"In another document — opens it at this chunk",onClick:()=>c(s,t,n),children:[i," ↗"]}):e.jsxs("span",{className:"doc-ref-target external",title:"In another document",children:[i," ↗"]})}const dn=8,un=20;function hn(t){return/embedder|embedding|vector|semantic|not configured/i.test(t)}function mn({documentId:t,selectedId:n,scope:s,browse:a,onSelectChunk:r,onOpenDocument:c}){const i=he(),[l,f]=o.useState(!1),[d,h]=o.useState(!1),[v,w]=o.useState(void 0),[p,y]=o.useState([]),[x,A]=o.useState([]),[O,P]=o.useState(null),[B,W]=o.useState([]),[D,G]=o.useState(!1);o.useEffect(()=>{if(!l||!n)return;const N=n;let R=!1;return h(!0),Promise.allSettled([i.documentBacklinks(N,s,a),i.documentRelated(N,s,a,dn),i.documentUnlinkedMentions(N,s,a,un)]).then(([C,m,g])=>{if(!R){if(y(C.status==="fulfilled"?C.value.backlinks??[]:[]),m.status==="fulfilled")A(m.value.related??[]),P(null);else{A([]);const k=m.reason instanceof Error?m.reason.message:String(m.reason);P(hn(k)?"semantic search not configured":k)}g.status==="fulfilled"?(W(g.value.unlinked_mentions??[]),G(!!g.value.truncated)):(W([]),G(!1)),w(N),h(!1)}}),()=>{R=!0}},[i,l,n,s,a]);const H=(N,R,C)=>e.jsx(xt,{id:N,title:R,targetDocumentId:C,documentId:t,onSelectChunk:r,onOpenDocument:c}),V=!!(l&&n&&!d&&v===n);return e.jsxs("div",{className:"doc-conn",children:[e.jsxs("button",{type:"button",className:"doc-conn-toggle",onClick:()=>f(N=>!N),children:[l?"▼":"▶"," Connections"]}),l&&e.jsx("div",{className:"doc-conn-body",children:n?V?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Backlinks"}),p.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsx("ul",{className:"doc-conn-list",children:p.map((N,R)=>e.jsxs("li",{className:"doc-conn-row",children:[H(N.from_id,N.from_title,N.from_document_id),e.jsx("span",{className:"doc-ref-kind",children:N.kind}),N.auto&&e.jsx("span",{className:"doc-conn-auto",title:"Auto-linked from a [[wikilink]]",children:"auto"})]},`${N.from_id}-${N.kind}-${R}`))})]}),e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Related"}),O?e.jsx("p",{className:"doc-conn-empty",children:O}):x.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsx("ul",{className:"doc-conn-list",children:x.map((N,R)=>e.jsxs("li",{className:"doc-conn-row",children:[H(N.chunk_id,N.title,N.document_id),e.jsx("span",{className:"doc-conn-score",title:"similarity score",children:N.score.toFixed(2)})]},`${N.chunk_id}-${R}`))})]}),e.jsxs("div",{className:"doc-conn-group",children:[e.jsx("h5",{children:"Unlinked mentions"}),B.length===0?e.jsx("p",{className:"doc-conn-empty",children:"none"}):e.jsxs("ul",{className:"doc-conn-list",children:[B.map((N,R)=>e.jsx("li",{className:"doc-conn-row",children:H(N.chunk_id,N.title,N.document_id)},`${N.chunk_id}-${R}`)),D&&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."})})]})}const De=24;function fn({edges:t,documentId:n,selectedId:s,onSelectChunk:a,onOpenDocument:r}){const[c,i]=o.useState(!1),[l,f]=o.useState(!1);if(t.length===0)return null;const d=s?t.filter(p=>p.from_id===s||p.to_id===s):[],h=l?t:t.slice(0,De),v=xn(h),w=p=>{const y=gn(h,p);y&&(!y.documentId||y.documentId===n?a(y.id):r?.(y.documentId,y.id,y.title))};return e.jsxs("div",{className:"doc-refs",children:[s&&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((p,y)=>e.jsx(pn,{edge:p,selectedId:s,documentId:n,onSelectChunk:a,onOpenDocument:r},`${p.from_id}-${p.to_id}-${p.kind}-${y}`))})]}),e.jsxs("div",{className:"doc-graph",children:[e.jsxs("button",{type:"button",className:"doc-graph-toggle",onClick:()=>i(p=>!p),children:[c?"▼":"▶"," relationship graph (",t.length,")"]}),c&&e.jsxs(e.Fragment,{children:[e.jsx(_e,{code:v,onNodeClick:w}),t.length>De&&e.jsx("button",{type:"button",className:"doc-graph-more",onClick:()=>f(p=>!p),children:l?`show top ${De}`:`show all ${t.length}`})]})]})]})}function pn({edge:t,selectedId:n,documentId:s,onSelectChunk:a,onOpenDocument:r}){const c=t.from_id===n,i=c?t.to_id:t.from_id,l=c?t.to_title:t.from_title,f=c?t.to_document_id:t.from_document_id;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:c?"→":"←"}),e.jsx(xt,{id:i,title:l,targetDocumentId:f,documentId:s,onSelectChunk:a,onOpenDocument:r})]})}function xn(t){const n=["graph LR"];for(const s of t){const a=`${we(s.from_id)}["${Ze(s.from_title,s.from_id)}"]`,r=`${we(s.to_id)}["${Ze(s.to_title,s.to_id)}"]`,c=(s.kind||"link").replace(/[|"]/g," ");n.push(` ${a} -->|${c}| ${r}`)}return n.join(`
|
|
2
|
+
`)}function gn(t,n){for(const s of t){if(we(s.from_id)===n)return{id:s.from_id,documentId:s.from_document_id,title:s.from_title};if(we(s.to_id)===n)return{id:s.to_id,documentId:s.to_document_id,title:s.to_title}}}function we(t){return"n"+t.replace(/[^a-zA-Z0-9]/g,"")}function Ze(t,n){const a=(t??"").replace(/["[\]{}|<>]/g," ").replace(/\s+/g," ").trim()||n.slice(0,6);return a.length>30?a.slice(0,29)+"…":a}function jn({documentId:t,scope:n,detail:s}){return e.jsxs("div",{className:"doc-unavailable",role:"alert",children:[e.jsx("p",{className:"doc-unavailable-lead",children:"This document can’t be opened."}),e.jsxs("p",{children:["It may have been deleted, live in a scope other than ",e.jsx("code",{children:n}),", or not be yours to read."]}),e.jsxs("p",{className:"doc-unavailable-detail",children:[e.jsx("code",{children:t}),s&&e.jsxs(e.Fragment,{children:[" — ",s]})]})]})}function bn(t){const n=typeof t=="number"?t/1e6:Date.parse(String(t));return!Number.isFinite(n)||n<=0?String(t??""):new Date(n).toLocaleString()}function yn({chunkId:t,chunkTitle:n,scope:s,browse:a,onClose:r}){const c=he(),[i,l]=o.useState([]),[f,d]=o.useState(!0),[h,v]=o.useState(null),[w,p]=o.useState("none"),[y,x]=o.useState(null),[A,O]=o.useState(""),[P,B]=o.useState(!1),[W,D]=o.useState(null),[G,H]=o.useState(null),[V,N]=o.useState("");o.useEffect(()=>{let m=!1;return d(!0),v(null),c.documentHistory(t,s,a).then(g=>{if(m)return;const k=g.revisions??[];if(l(k),k.length>=2){const S=k.map(I=>I.revision);D(Math.min(...S)),H(Math.max(...S))}}).catch(g=>!m&&v(g instanceof Error?g.message:String(g))).finally(()=>!m&&d(!1)),()=>{m=!0}},[c,t,s,a]);const R=async m=>{v(null),B(!0),x(m),p("version");try{const g=await c.documentGetVersion(t,m,s,a);O(g.body??"")}catch(g){v(g instanceof Error?g.message:String(g))}finally{B(!1)}},C=async()=>{if(!(W===null||G===null)){v(null),B(!0),p("diff");try{const m=await c.documentDiff(t,W,G,s,a);N(m.diff??"")}catch(m){v(m instanceof Error?m.message:String(m))}finally{B(!1)}}};return e.jsx("div",{className:"modal-overlay",onClick:r,children:e.jsxs("div",{className:"modal history-modal",onClick:m=>m.stopPropagation(),children:[e.jsxs("div",{className:"modal-header sticky-top",children:[e.jsxs("h3",{children:["History",n?` — ${n}`:""]}),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}),f?e.jsx("p",{className:"doc-empty-body",children:"loading…"}):i.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:i.map(m=>e.jsxs("button",{type:"button",className:"doc-hist-rev"+(w==="version"&&y===m.revision?" active":""),onClick:()=>{R(m.revision)},children:[e.jsxs("span",{className:"doc-hist-rev-num",children:["rev ",m.revision]}),e.jsx("span",{className:"doc-hist-rev-time",children:bn(m.created_at)}),e.jsx("span",{className:"doc-hist-rev-actor",children:m.actor||"unknown"})]},m.revision))}),i.length>=2&&e.jsxs("div",{className:"doc-hist-diffbar",children:[e.jsx("span",{children:"Compare"}),e.jsx("select",{value:W??"",onChange:m=>D(m.target.value===""?null:Number(m.target.value)),"aria-label":"diff from revision",children:i.map(m=>e.jsxs("option",{value:m.revision,children:["rev ",m.revision]},m.revision))}),e.jsx("span",{"aria-hidden":!0,children:"→"}),e.jsx("select",{value:G??"",onChange:m=>H(m.target.value===""?null:Number(m.target.value)),"aria-label":"diff to revision",children:i.map(m=>e.jsxs("option",{value:m.revision,children:["rev ",m.revision]},m.revision))}),e.jsx("button",{type:"button",onClick:()=>{C()},disabled:P||W===null||G===null,children:"diff"})]}),e.jsx("div",{className:"doc-hist-output",children:P?e.jsx("p",{className:"doc-empty-body",children:"loading…"}):w==="diff"?e.jsx(kn,{text:V}):w==="version"?e.jsx("pre",{className:"md-pre doc-hist-version",children:e.jsx("code",{children:A||"(empty)"})}):e.jsx("p",{className:"doc-empty-body",children:"Select a revision to view it, or compare two."})})]})]})})}function kn({text:t}){if(!t.trim())return e.jsx("p",{className:"doc-empty-body",children:"(no differences)"});const n=t.split(`
|
|
3
|
+
`);return e.jsx("pre",{className:"md-pre doc-hist-diff",children:n.map((s,a)=>{const r=s.startsWith("+")&&!s.startsWith("+++")?"diff-add":s.startsWith("-")&&!s.startsWith("---")?"diff-del":s.startsWith("@@")?"diff-hunk":"";return e.jsxs("span",{className:r,children:[s,`
|
|
4
|
+
`]},a)})})}function Xe({source:t}){return e.jsx("div",{className:"md",children:e.jsx(At,{remarkPlugins:[Ot],components:vn,children:t})})}const vn={a({href:t,children:n}){const s=t??"",a=/^https?:\/\//i.test(s);return e.jsx("a",{href:s,target:a?"_blank":void 0,rel:a?"noopener noreferrer":void 0,children:n})},pre({children:t}){return e.jsx(e.Fragment,{children:t})},code({className:t,children:n}){const s=/language-(\w+)/.exec(t??"")?.[1],a=String(n??"");return s==="mermaid"?e.jsx(_e,{code:a.replace(/\n$/,"")}):s||a.includes(`
|
|
5
|
+
`)?e.jsx("pre",{className:"md-pre",children:e.jsx("code",{className:t,children:n})}):e.jsx("code",{children:n})}};function Nn(t){const n=t.fields??{};return typeof n.alt=="string"&&n.alt.trim()!==""?n.alt:t.title||"image"}function gt({documentId:t,scope:n,titleHint:s,browse:a,principal:r,renderAssistant:c,initialChunkId:i,onOpenDocument:l,onTitle:f}){const d=he(),h=o.useMemo(()=>a&&(a.scopeId||a.tenant)?{scopeId:a.scopeId,tenant:a.tenant}:void 0,[a?.scopeId,a?.tenant]),[v,w]=o.useState([]),[p,y]=o.useState(void 0),[x,A]=o.useState(null),[O,P]=o.useState("chunks"),[B,W]=o.useState(null),[D,G]=o.useState(null),[H,V]=o.useState(null),N=o.useRef(null),[R,C]=o.useState(null),[m,g]=o.useState(!1),[k,S]=o.useState(!1),[I,T]=o.useState(null),[X,ae]=o.useState(!1),[xe,me]=o.useState(void 0),[ce,ge]=o.useState(null),[re,Ee]=o.useState(0),[je,E]=o.useState(!1),[z,ne]=o.useState(null),[ie,be]=o.useState(!1),[le,K]=o.useState([]),F=o.useCallback(()=>Ee(u=>u+1),[]),fe=o.useRef(i);fe.current=i;const ye=o.useRef(f);ye.current=f;const pe=o.useMemo(()=>tn(v),[v]),ee=o.useMemo(()=>v.find(j=>!j.parent_id)?.title||s||"document",[v,s]),Y=o.useMemo(()=>!!x&&!x.parent_id,[x]),J=o.useMemo(()=>z?.root_chunk_id??v.find(u=>!u.parent_id)?.id,[z,v]),Z=o.useMemo(()=>[...new Set(v.map(u=>u.status).filter(u=>!!u))],[v]),de=!!z?.color_enabled,Me=o.useMemo(()=>{const u=new Set;for(const j of le)u.add(j.from_id),u.add(j.to_id);return u},[le]),$e=o.useMemo(()=>de?Se(Fe(z?.type,z?.status,Ce(z?.color_scheme))):void 0,[de,z?.type,z?.status,z?.color_scheme]);o.useEffect(()=>{let u=!1;return ae(!0),T(null),ge(null),d.documentQueryChunks(t,n,h).then(j=>{if(u)return;const M=j.chunks??[];w(M),me(`${n}:${t}`),y(L=>L??Zt(M,fe.current))}).catch(j=>{u||(w([]),ge(j instanceof Error?j.message:String(j)))}).finally(()=>!u&&ae(!1)),()=>{u=!0}},[d,t,n,re,h]);const Te=!X&&(ce!==null||xe===`${n}:${t}`&&v.length===0),b=o.useMemo(()=>v.find(u=>!u.parent_id&&u.document_id===t)?.title,[v,t]);o.useEffect(()=>{b&&ye.current?.(t,b)},[t,b]),o.useEffect(()=>{let u=!1;return d.documentGet(t,n,h).then(j=>!u&&ne(j)).catch(()=>!u&&ne(null)),()=>{u=!0}},[d,t,n,re,h]),o.useEffect(()=>{let u=!1;return d.documentGetEdges(t,n,h).then(j=>!u&&K(j.edges??[])).catch(()=>!u&&K([])),()=>{u=!0}},[d,t,n,re,h]),o.useEffect(()=>{y(void 0),A(null),W(null),P("chunks"),ne(null),K([])},[t,n]),o.useEffect(()=>{if(!p){A(null);return}let u=!1;return d.documentGetChunk(p,n,h).then(j=>!u&&A(j)).catch(j=>!u&&T(j instanceof Error?j.message:String(j))),()=>{u=!0}},[d,p,n,re,h]),o.useEffect(()=>{const u=x?.type==="image"||!!x?.asset;if(!x||!u||!d.documentAssetObjectUrl){G(null),V(null);return}let j=!1,M=null;return V(null),d.documentAssetObjectUrl(x.id,n,h).then(L=>{if(j){URL.revokeObjectURL(L);return}M=L,G(L)}).catch(L=>!j&&V(L instanceof Error?L.message:String(L))),()=>{j=!0,M&&URL.revokeObjectURL(M)}},[d,x,n,h]),o.useEffect(()=>{if(O!=="markdown"||!p){W(null);return}const u=ft(pe,p);if(!u)return;let j=!1;const M=[],L=(q,ke)=>{M.push({node:q,depth:ke}),q.children.forEach(ve=>L(ve,ke+1))};return L(u,0),Promise.all(M.map(q=>d.documentGetChunk(q.node.row.id,n,h))).then(q=>{if(j)return;const ke=M.map((ve,St)=>{const _t=Math.min(ve.depth+1,6),te=q[St],Re="#".repeat(_t)+" "+ve.node.row.title;if(te.type==="mermaid"&&te.body)return Re+"\n\n```mermaid\n"+te.body+"\n```\n";if(te.type==="image"||te.asset){const Et=te.body?" — "+te.body:"";return Re+`
|
|
6
6
|
|
|
7
|
-
_🖼 image chunk_`+
|
|
8
|
-
`}return
|
|
7
|
+
_🖼 image chunk_`+Et+`
|
|
8
|
+
`}return Re+(te.body?`
|
|
9
9
|
|
|
10
|
-
`+
|
|
10
|
+
`+te.body:"")+`
|
|
11
11
|
`}).join(`
|
|
12
|
-
`);
|
|
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
|
+
`);W(ke)}).catch(q=>!j&&T(q instanceof Error?q.message:String(q))),()=>{j=!0}},[d,O,p,pe,n,re,h]);const _=o.useCallback(u=>y(u.row.id),[]),$=o.useCallback((u,j,M)=>l?.({documentId:u,chunkId:j,title:M},{documentId:t,chunkId:p,title:ee}),[l,t,p,ee]),U=o.useCallback(async()=>{try{const u=await d.documentExportMd(t,n,!0,h),j=new Blob([u.markdown],{type:"text/markdown"}),M=URL.createObjectURL(j),L=document.createElement("a");L.href=M,L.download=(u.title||"document").replace(/[^\w.-]+/g,"_")+".md",L.click(),URL.revokeObjectURL(M)}catch(u){T(u instanceof Error?u.message:String(u))}},[d,t,n,h]),Q=o.useCallback(async()=>{try{const u=await d.documentExportCanvas(t,n,h),j=new Blob([JSON.stringify(u.canvas,null,2)],{type:"application/json"}),M=URL.createObjectURL(j),L=document.createElement("a");L.href=M,L.download=(ee||"document").replace(/[^\w.-]+/g,"_")+".canvas",L.click(),URL.revokeObjectURL(M)}catch(u){T(u instanceof Error?u.message:String(u))}},[d,t,n,h,ee]),se=!!d.documentCreateChunk&&!!J,ue=o.useCallback(async u=>{if(!d.documentCreateChunk||!d.documentSetAsset)return;const j=p||J;if(j){T(null);try{const{mediaType:M,data:L}=await ut(u),q=await d.documentCreateChunk(t,j,{title:u.name||"image",type:"image"},n,h);await d.documentSetAsset(q.id,M,L,u.name,n,h),F(),y(q.id)}catch(M){T(M instanceof Error?M.message:String(M))}}},[d,t,n,h,p,J,F]),vt=o.useCallback(async()=>{if(!d.documentCreateChunk)return;const u=p||J;if(u){T(null);try{const j=await d.documentCreateChunk(t,u,{title:"Diagram",type:"mermaid",body:`graph TD
|
|
13
|
+
A[Start] --> B[End]`},n,h);F(),y(j.id),C(j)}catch(j){T(j instanceof Error?j.message:String(j))}}},[d,t,n,h,p,J,F]),Nt=o.useCallback(async()=>{if(!d.documentCreateChunk)return;const u=p&&!Y?p:void 0,j=p||J;if(j){T(null);try{const M=await d.documentCreateChunk(t,u?"":j,{title:"Text",body:""},n,h,u);F(),y(M.id),C(M)}catch(M){T(M instanceof Error?M.message:String(M))}}},[d,t,n,h,p,Y,J,F]),wt=o.useCallback(async()=>{if(!(!d.documentCreateChunk||!p)){T(null);try{const u=await d.documentCreateChunk(t,p,{title:"Text",body:""},n,h);F(),y(u.id),C(u)}catch(u){T(u instanceof Error?u.message:String(u))}}},[d,t,n,h,p,F]),Ue=o.useMemo(()=>{if(!x||Y)return{canUp:!1,canDown:!1};const u=x.parent_id??"",j=v.filter(L=>(L.parent_id??"")===u).sort((L,q)=>L.position-q.position||L.id.localeCompare(q.id)),M=j.findIndex(L=>L.id===x.id);return{canUp:M>0,canDown:M>=0&&M<j.length-1}},[v,x,Y]),Be=o.useCallback(async u=>{if(!(!d.documentReorderChunk||!p)){T(null);try{await d.documentReorderChunk(p,u,n,h),F()}catch(j){T(j instanceof Error?j.message:String(j))}}},[d,p,n,h,F]),Ct=o.useCallback(async()=>{if(!d.documentDeleteChunk||!x)return;T(null);const u=x.parent_id;try{await d.documentDeleteChunk(x.id,n,h),S(!1),y(u||J),F()}catch(j){T(j instanceof Error?j.message:String(j)),S(!1)}},[d,x,n,h,J,F]);return o.useEffect(()=>{if(!se)return;const u=j=>{if(R||ie)return;const M=document.activeElement,L=M?.tagName;if(L==="INPUT"||L==="TEXTAREA"||M?.isContentEditable)return;const q=Yt(j.clipboardData?.items);q&&(j.preventDefault(),ue(q))};return window.addEventListener("paste",u),()=>window.removeEventListener("paste",u)},[se,R,ie,ue]),e.jsxs("div",{className:"doc-viewer",children:[e.jsx("input",{ref:N,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:$e,children:[e.jsx("strong",{className:"doc-title",title:ee,children:ee}),e.jsx(Oe,{value:t,label:"doc"}),e.jsxs("div",{className:"doc-toolbar-actions",children:[se&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>{Nt()},title:"Add a text chunk AFTER the selected chunk, at the same level",children:"+ text"}),e.jsx("button",{type:"button",onClick:()=>{wt()},disabled:!p,title:p?"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:()=>N.current?.click(),title:"Add an image chunk (upload — or paste a screenshot into the view)",children:"+ image"}),e.jsx("button",{type:"button",onClick:()=>{vt()},title:"Add a Mermaid diagram chunk",children:"+ diagram"})]}),e.jsx("button",{type:"button",className:de?"active":"",onClick:()=>be(!0),disabled:!J,title:"Colors — tint chunk tiles + the Path tree by type/status",children:"colors"}),e.jsx("button",{type:"button",onClick:()=>{U()},title:"Download the whole document as Markdown (.md)",children:"↓ .md"}),e.jsx("button",{type:"button",onClick:()=>{Q()},title:"Download the whole document as a node/edge canvas graph (.canvas)",children:"↓ .canvas"}),c&&e.jsx("button",{type:"button",className:je?"active":"",onClick:()=>E(u=>!u),title:"Document Assistant — instruct an agent to restructure/import/link chunks",children:"assistant"}),e.jsx("button",{type:"button",onClick:F,title:"Reload",children:"↻"})]})]}),I&&e.jsx("div",{className:"paths-err",children:I}),Te?e.jsx(jn,{documentId:t,scope:n,detail:ce??void 0}):e.jsxs("div",{className:"doc-split",children:[e.jsx("div",{className:"doc-chunktree",children:X&&v.length===0?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Loading…"})}):e.jsx(nn,{tree:pe,selectedId:p,onSelect:_,colorEnabled:de,scheme:z?.color_scheme,linkedIds:Me})}),e.jsx("div",{className:"doc-content",children:x?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"doc-content-head",children:[e.jsx("h3",{children:x.title||"(untitled)"}),e.jsxs("div",{className:"doc-content-meta",children:[x.type&&e.jsx("span",{className:"chunk-badge",children:x.type}),x.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:x.status}),e.jsxs("span",{className:"chunk-rev",children:["rev ",x.revision]}),x.tags?.map(u=>e.jsx("span",{className:"chunk-tag",children:u},u)),e.jsx(Oe,{value:x.id,label:"chunk"})]}),e.jsxs("div",{className:"doc-content-controls",children:[e.jsxs("div",{className:"doc-mode-toggle",children:[e.jsx("button",{type:"button",className:O==="chunks"?"active":"",onClick:()=>P("chunks"),title:"This chunk's own content",children:"chunk"}),e.jsx("button",{type:"button",className:O==="markdown"?"active":"",onClick:()=>P("markdown"),title:Y?"Whole document as Markdown":"This chunk + its sub-chunks as Markdown",children:"markdown"})]}),e.jsx("button",{type:"button",onClick:()=>C(x),children:"edit"}),e.jsx("button",{type:"button",onClick:()=>g(!0),title:"View this chunk's edit history + diffs",children:"history"}),!Y&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>{Be("up")},disabled:!Ue.canUp,title:"Move this chunk up within its level",children:"↑"}),e.jsx("button",{type:"button",onClick:()=>{Be("down")},disabled:!Ue.canDown,title:"Move this chunk down within its level",children:"↓"})]}),!Y&&e.jsx("button",{type:"button",className:"danger",onClick:()=>S(!0),title:"Delete this chunk and its sub-chunks",children:"delete"})]})]}),e.jsx("div",{className:"doc-content-body",children:x.type==="mermaid"?x.body?e.jsxs(e.Fragment,{children:[e.jsx(_e,{code:x.body}),O==="markdown"&&e.jsx("pre",{className:"md-pre doc-mermaid-source",children:e.jsx("code",{children:x.body})})]}):e.jsx("p",{className:"doc-empty-body",children:"(empty diagram)"}):x.type==="image"||x.asset?H?e.jsxs("p",{className:"doc-empty-body",children:["Image failed to load: ",H]}):D?e.jsxs("figure",{className:"doc-image",children:[e.jsx("img",{src:D,alt:Nn(x)}),x.body&&e.jsx("figcaption",{children:x.body})]}):e.jsx("p",{className:"doc-empty-body",children:"Loading image…"}):O==="markdown"?B!==null?e.jsx(Xe,{source:B}):e.jsx("p",{className:"doc-empty-body",children:"Assembling Markdown…"}):x.body?e.jsx(Xe,{source:x.body}):e.jsx("p",{className:"doc-empty-body",children:"(empty chunk)"})}),e.jsx(fn,{edges:le,documentId:t,selectedId:p,onSelectChunk:y,onOpenDocument:l?$:void 0}),e.jsx(mn,{documentId:t,selectedId:p,scope:n,browse:h,onSelectChunk:y,onOpenDocument:l?$:void 0})]}):e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Select a chunk on the left."})})})]}),je&&c&&e.jsx("div",{className:"doc-assistant",children:c({documentId:t,scope:n,subject:r?.subject,onChanged:F})}),R&&e.jsx(on,{chunk:R,scope:n,browse:h,onClose:()=>C(null),onSaved:F}),m&&x&&e.jsx(yn,{chunkId:x.id,chunkTitle:x.title,scope:n,browse:h,onClose:()=>g(!1)}),ie&&J&&e.jsx(ln,{documentId:t,rootChunkId:J,docType:z?.type,docStatus:z?.status,chunkStatuses:Z,scope:n,browse:h,onClose:()=>be(!1),onSaved:F}),k&&x&&e.jsx("div",{className:"modal-overlay",onClick:()=>S(!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 “",x.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:()=>S(!1),children:"cancel"}),e.jsx("button",{type:"button",className:"danger",onClick:()=>{Ct()},children:"delete"})]})]})})]})}function jt(t,n=""){const s=t.get(n);if(!s)return[];const a=s.entries.map(r=>{const c=r.kind==="directory"&&r.full_path.startsWith(`${n}/`);return{name:r.name,fullPath:r.full_path,kind:r.kind,resourceRef:r.resource_ref,listing:c?t.get(r.full_path):void 0,children:c?jt(t,r.full_path):[]}});return a.sort((r,c)=>{const i=r.kind==="directory",l=c.kind==="directory";return i!==l?i?-1:1:r.name.localeCompare(c.name)}),a}const wn={directory:"📁",document:"📄",volume_mount:"💾",memory_entry:"🧠"};function Cn(t){const{tree:n,root:s}=t;return!s||!s.loaded&&s.loading?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"Loading…"})}):s.loaded&&n.length===0&&!s.nextCursor?e.jsx("div",{className:"empty",children:e.jsx("p",{children:"This tree is empty. Create a folder or document to begin."})}):e.jsxs("ul",{className:"tree path-tree",children:[n.map(a=>e.jsx(yt,{node:a,...t},a.fullPath)),e.jsx(bt,{dir:"",listing:s,...t})]})}function bt({dir:t,listing:n,onLoadMore:s,onRetry:a}){const r=[];return!n||n.loading&&n.entries.length===0?r.push(e.jsx("li",{className:"node path-status",children:e.jsx("span",{className:"path-implicit",children:"loading…"})},"status")):n.error?r.push(e.jsxs("li",{className:"node path-status",children:[t!==""&&e.jsxs("span",{className:"path-err",children:["failed to load: ",n.error]})," ",e.jsx("button",{type:"button",className:"path-more",onClick:()=>a(t),children:"retry"})]},"status")):n.loaded&&n.entries.length===0&&t!==""&&r.push(e.jsx("li",{className:"node path-status",children:e.jsx("span",{className:"path-implicit",children:"empty"})},"status")),n?.nextCursor&&!n.error&&r.push(e.jsx("li",{className:"node path-status",children:e.jsx("button",{type:"button",className:"path-more",disabled:n.loading,onClick:()=>s(t),children:n.loading?"loading…":`Load more (${n.entries.length} shown)`})},"more")),e.jsx(e.Fragment,{children:r})}function Sn(t,n){if(t.kind!=="document"||!n)return;const s=t.resourceRef;return s?.document_id?n.get(s.document_id):void 0}function yt(t){const{node:n,expanded:s,onToggle:a,selectedPath:r,onSelect:c,summaries:i}=t,l=n.kind==="directory",f=l&&s.has(n.fullPath),d=r===n.fullPath,h=Sn(n,i),v=h&&h.color_enabled?Se(Fe(h.type,h.status,Ce(h.color_scheme))):void 0;return e.jsxs("li",{className:`node path-node kind-${n.kind} ${d?"selected":""}`,children:[e.jsxs("div",{className:"row path-row",style:v,children:[e.jsx("button",{type:"button",className:"tree-caret","aria-label":f?"collapse":"expand","aria-expanded":l?f:void 0,disabled:!l,onClick:w=>{w.stopPropagation(),l&&a(n.fullPath)},children:l?f?"▼":"▶":"·"}),e.jsxs("button",{type:"button",className:"path-link",onClick:()=>c(n),title:n.fullPath,children:[e.jsx("span",{className:"path-kind-icon","aria-hidden":!0,children:wn[n.kind]??"•"}),e.jsx("span",{className:"path-name",children:n.name}),h?.type&&e.jsx("span",{className:"chunk-badge",children:h.type}),h?.status&&e.jsx("span",{className:"chunk-badge chunk-status",children:h.status})]})]}),f&&e.jsxs("ul",{className:"children path-children",children:[n.children.map(w=>e.jsx(yt,{...t,node:w},w.fullPath)),e.jsx(bt,{...t,dir:n.fullPath,listing:n.listing})]})]})}const Qe=/^[A-Za-z0-9._-]+$/;function Ye(t,n){return`${t}/${n}`}function kt(t,n){for(const s of t){if(s.fullPath===n)return s;const a=kt(s.children,n);if(a)return a}}function _n(t){const{theme:n,defaultScope:s,path:a,onPathChange:r,browse:c,principal:i,renderAssistant:l,onError:f}=t,d=at(t);return e.jsx(rt,{theme:n,dataLayer:d,children:e.jsx(En,{defaultScope:s,path:a,onPathChange:r,browse:c,principal:i,renderAssistant:l,onError:f})})}function En({defaultScope:t,path:n,onPathChange:s,browse:a,principal:r,renderAssistant:c,onError:i}){const l=he(),[f,d]=o.useState(t??"user"),[h,v]=o.useState(void 0),[w,p]=o.useState(null),[y,x]=o.useState(null),[A,O]=o.useState(()=>new Set),P=n!==void 0?n:h,B=o.useRef(s);o.useEffect(()=>{B.current=s},[s]);const W=o.useRef(i);o.useEffect(()=>{W.current=i},[i]);const[D,G]=o.useState([]),H=o.useRef(0),V=o.useRef(void 0),N=o.useCallback(b=>{V.current=b,B.current?.(b),v(b)},[]),R=o.useCallback(b=>{H.current++,G(_=>_.length>0?[]:_),N(b)},[N]);o.useEffect(()=>{n===void 0||n===V.current||(H.current++,G(b=>b.length>0?[]:b))},[n]);const C=o.useMemo(()=>a&&(a.scopeId||a.tenant)?{scopeId:a.scopeId,tenant:a.tenant}:void 0,[a?.scopeId,a?.tenant]),m=o.useMemo(()=>new Ht(l,f,C),[l,f,C]),g=o.useSyncExternalStore(m.subscribe,m.getSnapshot),k=o.useCallback(b=>{W.current?.(b)},[]),[S,I]=o.useState(()=>new Map),T=o.useRef(new Set),X=o.useRef(0),ae=o.useCallback(()=>{X.current++,T.current=new Set,I(new Map)},[]),xe=o.useRef(!0);o.useEffect(()=>{xe.current?xe.current=!1:(R(void 0),p(null),O(new Set),ae()),m.loadDir("").catch(k)},[m,R,ae,k]),o.useEffect(()=>{for(const b of A)g.has(b)||m.loadDir(b).catch(k)},[m,A,g,k]);const me=o.useRef(null);o.useEffect(()=>{const b=me.current!==null&&me.current!==m;if(me.current=m,!P||b)return;const _=tt(P).filter($=>$!=="");O($=>{if(_.every(Q=>$.has(Q)))return $;const U=new Set($);return _.forEach(Q=>U.add(Q)),U}),m.reveal(P).catch(k)},[m,P,k]),o.useEffect(()=>{if(f==="tenant")return;const b=[];for(const $ of g.values())for(const U of Ve($.entries))T.current.has(U)||(T.current.add(U),b.push(U));const _=X.current;for(let $=0;$<b.length;$+=Pe)l.documentsSummary({documentIds:b.slice($,$+Pe)},f,C).then(U=>{X.current===_&&I(Q=>{const se=new Map(Q);for(const ue of U.documents??[])se.set(ue.document_id,ue);return se})}).catch(()=>{})},[l,g,f,C]);const ce=o.useMemo(()=>jt(g),[g]),ge=o.useCallback(async()=>{p(null),ae(),await m.refresh(A).catch(k),P&&await m.reveal(P).catch(k)},[m,A,P,ae,k]),re=o.useCallback(b=>{O(_=>{const $=new Set(_);return $.has(b)?$.delete(b):$.add(b),$})},[]),Ee=o.useCallback(b=>m.loadMore(b).catch(k),[m,k]),je=o.useCallback(b=>{(m.getSnapshot().get(b)?.loaded?m.loadMore(b):m.loadDir(b)).catch(k)},[m,k]),E=o.useMemo(()=>P?kt(ce,P):void 0,[ce,P]),z=g.get("")?.error,ne=E?.kind==="directory"?E.fullPath:void 0,[ie,be]=o.useState(null);o.useEffect(()=>{if(!ne||!l.pathIsStored)return;let b=!1;return l.pathIsStored(ne,f,C).then(_=>{b||be({path:ne,explicit:_})},()=>{}),()=>{b=!0}},[l,ne,f,C]);const le=E?E.kind!=="directory"?"yes":ie?.path===E.fullPath?ie.explicit?"yes":"implicit (no entry)":void 0:void 0,K=o.useMemo(()=>E?E.kind==="directory"?E.fullPath:Gt(E.fullPath):"",[E]),F=K||"/",fe=f!=="tenant",ye=o.useCallback(()=>{x({title:`New folder in ${F}`,fields:[{key:"name",label:"Folder name",placeholder:"e.g. launches"}],submitLabel:"Create",onSubmit:async b=>{const _=b.name.trim();if(!Qe.test(_))throw new Error("name may contain only [A-Za-z0-9._-]");const $=Ye(K,_);await l.pathMkdir($,f,C),await m.invalidate($).catch(k),R($)}})},[l,m,K,F,f,C,k,R]),pe=o.useCallback(()=>{x({title:`New document in ${F}`,fields:[{key:"name",label:"Path name",placeholder:"e.g. launch-plan"},{key:"title",label:"Title",placeholder:"e.g. Launch Plan"}],submitLabel:"Create",onSubmit:async b=>{const _=b.name.trim();if(!Qe.test(_))throw new Error("name may contain only [A-Za-z0-9._-]");const $=b.title.trim()||_,U=Ye(K,_);await l.documentCreate($,U,f,C),await m.invalidate(U).catch(k),R(U)}})},[l,m,K,F,f,C,k,R]),ee=o.useCallback(()=>{E&&x({title:`Rename / move ${E.fullPath}`,fields:[{key:"to",label:"New path",value:E.fullPath}],submitLabel:"Move",onSubmit:async b=>{const _=b.to.trim();if(!_.startsWith("/"))throw new Error("path must start with /");await l.pathMv(E.fullPath,_,f,C),await Promise.all([m.invalidate(E.fullPath,{dropSubtree:!0}),m.invalidate(_)]).catch(k),R(_)}})},[l,m,E,f,C,k,R]),Y=o.useCallback(()=>{if(!E)return;if(E.kind==="document"){const $=E.resourceRef?.document_id;x({title:`Delete document ${E.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(!$)throw new Error("this document dirent has no document_id");await l.documentDelete($,f,C),await m.invalidate(E.fullPath).catch(k),R(void 0)}});return}const b=E;p(null),(async()=>{let _;try{_=await Wt(l,b.fullPath,f,C)}catch(U){p(`could not list ${b.fullPath} for delete: ${U instanceof Error?U.message:String(U)}`);return}const $=f==="tenant"?[]:Ve(_);x({title:`Delete branch ${b.fullPath}`,message:_.length===0?"This removes the (empty) folder.":"This removes the folder and everything under it"+($.length>0?` — including ${$.length} document(s), whose chunks are deleted.`:"."),fields:[],submitLabel:"Delete",danger:!0,onSubmit:async()=>{for(const U of $)await l.documentDelete(U,f,C);await l.pathRm(b.fullPath,f,!0,C),await m.invalidate(b.fullPath,{dropSubtree:!0}).catch(k),R(void 0)}})})()},[l,m,E,f,C,k,R]),J=E&&(E.kind==="directory"||E.kind==="document"),Z=o.useMemo(()=>{if(D.length>0)return D[D.length-1];if(E?.kind==="document")return{documentId:E.resourceRef?.document_id??"",path:E.fullPath,title:E.name}},[D,E]),de=o.useCallback((b,_)=>{const $=++H.current,U=zt(m.getSnapshot(),b.documentId);G(ot(D,{..._,path:Z?.path},{...b,path:U})),N(U),!(U||!l.documentPath)&&l.documentPath(b.documentId,f,C).then(Q=>{!Q||H.current!==$||(G(se=>Ae(se,b.documentId,{path:Q})),N(Q))},()=>{})},[l,m,D,Z?.path,f,C,N]),Me=o.useCallback(b=>{const _=ct(D,b);_!==D&&(H.current++,G(_),N(_[_.length-1].path))},[D,N]),$e=o.useCallback((b,_)=>G($=>Ae($,b,{title:_})),[]),Te=!!Z?.path&&E?.kind==="document"&&E.fullPath===Z.path;return e.jsxs(e.Fragment,{children:[e.jsxs(Xt,{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:f,onChange:b=>d(b.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:ye,title:`New folder in ${F}`,children:"+ folder"}),e.jsx("button",{type:"button",onClick:pe,disabled:!fe,title:fe?`New document in ${F}`:"Documents are agent/user scope only",children:"+ document"}),e.jsx("button",{type:"button",onClick:()=>{ge()},title:"Reload the tree",children:"↻"})]})]}),e.jsxs("p",{className:"paths-context",children:["new items → ",e.jsx("code",{children:F}),C?.scopeId&&e.jsxs(e.Fragment,{children:[" · ","subject ",e.jsx("code",{children:C.scopeId})]}),C?.tenant&&e.jsxs(e.Fragment,{children:[" · ","tenant ",e.jsx("code",{children:C.tenant})]})]}),(w||z)&&e.jsx("div",{className:"paths-err",children:w||z}),e.jsx(Cn,{tree:ce,root:g.get(""),expanded:A,onToggle:re,onLoadMore:Ee,onRetry:je,selectedPath:P,onSelect:b=>R(b.fullPath),summaries:S})]}),e.jsx("div",{className:"right",children:Z?e.jsxs("div",{className:"paths-doc",children:[e.jsx(lt,{trail:D,onJump:Me}),e.jsxs("div",{className:"paths-doc-head",children:[Z.path?e.jsx("code",{className:"paths-doc-path",children:Z.path}):e.jsxs("span",{className:"paths-doc-path paths-doc-unfiled",title:"Opened by id — no entry for this document was found in the Path tree",children:[oe(Z)," ",e.jsx("em",{children:"· opened by id, not in the tree"})]}),Te&&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:Y,children:"delete"})]})]}),e.jsx(gt,{documentId:Z.documentId,scope:f,titleHint:Z.title,browse:C,principal:r,renderAssistant:c,initialChunkId:Z.chunkId,onOpenDocument:de,onTitle:$e},D.length)]}):E?e.jsxs("div",{className:"paths-detail",children:[e.jsxs("h2",{children:[e.jsx("span",{className:"paths-detail-kind",children:E.kind}),e.jsx("code",{children:E.fullPath})]}),e.jsxs("dl",{className:"paths-detail-meta",children:[e.jsx("dt",{children:"scope"}),e.jsx("dd",{children:f}),le&&e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"stored"}),e.jsx("dd",{children:le})]})]}),J?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:Y,children:"delete"})]}):e.jsxs("p",{className:"paths-readonly",children:["Read-only — ",E.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."})})})]}),y&&e.jsx(Mn,{state:y,onClose:()=>x(null)})]})}function Mn({state:t,onClose:n}){const[s,a]=o.useState(()=>Object.fromEntries(t.fields.map(d=>[d.key,d.value??""]))),[r,c]=o.useState(!1),[i,l]=o.useState(null),f=async d=>{d.preventDefault(),c(!0),l(null);try{await t.onSubmit(s),n()}catch(h){l(h instanceof Error?h.message:String(h)),c(!1)}};return e.jsx("div",{className:"modal-overlay",onClick:n,children:e.jsxs("form",{className:"modal",onClick:d=>d.stopPropagation(),onSubmit:f,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:n,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((d,h)=>e.jsxs("label",{className:"path-field",children:[e.jsx("span",{children:d.label}),e.jsx("input",{className:"path-modal-input",value:s[d.key],placeholder:d.placeholder,autoFocus:h===0,onChange:v=>a(w=>({...w,[d.key]:v.target.value}))})]},d.key)),i&&e.jsx("div",{className:"modal-err",children:i})]})})}function $n(t){const{documentId:n,scope:s,browse:a,theme:r}=t,c=at(t);return e.jsx(rt,{theme:r,dataLayer:c,children:e.jsx(Tn,{...t},`${s}:${n}:${a?.scopeId??""}:${a?.tenant??""}`)})}function Tn({documentId:t,scope:n,titleHint:s,browse:a,principal:r,renderAssistant:c,onOpenDocument:i}){const[l,f]=o.useState([]),d=l[l.length-1],h=o.useCallback((p,y)=>{i?i(p,y):f(x=>ot(x,y,p))},[i]),v=o.useCallback(p=>f(y=>ct(y,p)),[]),w=o.useCallback((p,y)=>f(x=>Ae(x,p,{title:y})),[]);return e.jsxs(e.Fragment,{children:[e.jsx(lt,{trail:l,onJump:v}),e.jsx(gt,{documentId:d?.documentId??t,scope:n,titleHint:d?d.title:s,browse:a,principal:r,renderAssistant:c,initialChunkId:d?.chunkId,onOpenDocument:h,onTitle:w},l.length)]})}exports.DEFAULT_SCHEME=Ne;exports.DocumentViewer=$n;exports.PathExplorer=_n;exports.assetFetchFromConnection=st;exports.chunkColor=ht;exports.createLoomcycleClient=nt;exports.dataLayerFromClient=Le;exports.docColor=Fe;exports.effectiveScheme=Ce;exports.hexToTint=mt;exports.tintStyle=Se;
|
|
14
14
|
//# sourceMappingURL=index.cjs.map
|