Manages document tree navigation state, content fetching, and sidebar expansion for `DocViewer` components across all doc-source consumers. ## Key Components ### `useDocumentTree(config, initialPath?)` Primary hook that orchestrates structure and content loading in parallel, handles URL synchronization, and manages sidebar tree expansion state. **Config options (`UseDocumentTreeConfig`):** | Property | Type | Description | |---|---|---| | `structureEndpoint` | `string` | API endpoint for the document tree structure | | `contentEndpoint` | `string` | API endpoint for document content | | `baseRoute` | `string` | Base URL path (e.g., `'/knowledge-base'`) | | `folderIndexFile` | `string?` | Folder index filename (defaults to `'README.md'`) | **Returns:** | State | Type | Description | |---|---|---| | `structure` | `DocNode[]` | Full document tree | | `selectedPath` | `string` | Currently active document path | | `content` | `DocContent \| null` | Fetched document content | | `isLoadingStructure` | `boolean` | Structure fetch in progress | | `isLoadingContent` | `boolean` | Content fetch in progress | | `error` | `string \| null` | Error message if fetch failed | | `expandedNodes` | `Set` | IDs of expanded sidebar nodes | ### `findFirstDocPath(folder)` Internal helper. Depth-first search for the first non-Mermaid file in a folder. Used to auto-display content for folders without a README. ### `scrollToContent()` Internal helper. Scrolls the `
` element (or document root as fallback) into view after navigation, accounting for the hub header offset. ## Usage Example ```typescript import { useDocumentTree } from './use-document-tree' function KnowledgeBaseViewer({ slug }: { slug?: string }) { const { structure, selectedPath, content, isLoadingStructure, isLoadingContent, error, expandedNodes, } = useDocumentTree( { structureEndpoint: '/api/kb/structure', contentEndpoint: '/api/kb/content', baseRoute: '/knowledge-base', folderIndexFile: 'README.md', }, slug, ) if (isLoadingStructure) return if (error) return return ( ) } ``` ## Navigation Behavior - **Parallel fetches:** Structure and a speculative content fetch fire simultaneously on mount to minimize time-to-first-content. - **No-README folders:** Auto-selects the first child document via `findFirstDocPath`; the sidebar remains the directory browser. - **Browser back/forward:** Synced via `popstate` listener. - **Client-side router navigation:** Synced via `cleanInitialPath` prop change (covers `history.pushState` which does not fire `popstate`). - **Stale fetch guard:** A `lastFetchedPath` ref prevents late in-flight responses from overwriting newer content. **Source:** [`use-document-tree.ts`](https://github.com/flamingo-stack/openframe-oss-lib/blob/main/use-document-tree.ts)