Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(docs): the public documentation page at /docs?key=

Pouzor4fedea7b0ebe
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 65dff2d..c8df312 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -102,6 +102,32 @@ export const liveviewApi = {
getConfig: () => api.get<{ enabled: boolean; key: string | null }>('/liveview/config'),
}
+/**
+ * The read-only documentation space at `/docs?key=…`.
+ *
+ * On `publicApi`, like live view: no JWT rides along, and a 401 must not bounce
+ * a reader towards a login they do not have. Reads only — the public router
+ * declares no write for this to call.
+ */
+export const docsviewApi = {
+ tree: (key: string) =>
+ publicApi.get<import('@/documentation/types').DocumentSummary[]>('/docsview/tree', {
+ params: { key },
+ }),
+ get: (key: string, id: string) =>
+ publicApi.get<import('@/documentation/types').Doc>(`/docsview/${id}`, { params: { key } }),
+ revisions: (key: string, id: string) =>
+ publicApi.get<import('@/documentation/types').DocRevision[]>(`/docsview/${id}/revisions`, {
+ params: { key },
+ }),
+ revision: (key: string, revisionId: string) =>
+ publicApi.get<import('@/documentation/types').DocRevision & { body: string }>(
+ `/docsview/revisions/${revisionId}`,
+ { params: { key } },
+ ),
+ getConfig: () => api.get<{ enabled: boolean; key: string | null }>('/docsview/config'),
+}
+
export interface DeepScanConfig {
http_ranges: string[]
http_probe_enabled: boolean
diff --git a/frontend/src/documentation/__tests__/PublicDocs.test.tsx b/frontend/src/documentation/__tests__/PublicDocs.test.tsx
new file mode 100644
index 0000000..78c9fec
--- /dev/null
+++ b/frontend/src/documentation/__tests__/PublicDocs.test.tsx
@@ -0,0 +1,170 @@
+/**
+ * The page served at `/docs?key=…`.
+ *
+ * It boots with no session, so every test here renders it exactly as a reader
+ * gets it: a URL, and whatever the public endpoints answer.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+import { docsviewApi } from '@/api/client'
+import PublicDocs from '../components/PublicDocs'
+import { usePublicDocsStore } from '../publicStore'
+import type { Doc, DocumentSummary } from '../types'
+
+vi.mock('@/api/client', () => ({
+ docsviewApi: {
+ tree: vi.fn(),
+ get: vi.fn(),
+ revisions: vi.fn(),
+ revision: vi.fn(),
+ getConfig: vi.fn(),
+ },
+}))
+
+const api = vi.mocked(docsviewApi)
+
+function summary(overrides: Partial<DocumentSummary> = {}): DocumentSummary {
+ return {
+ id: 'doc-1',
+ kind: 'page',
+ title: 'Offsite backups',
+ slug: 'offsite-backups',
+ sort_order: 0,
+ tags: [],
+ frontmatter: {},
+ starred: false,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+const INITIAL = usePublicDocsStore.getState()
+
+function visit(search: string) {
+ window.history.replaceState({}, '', `/docs${search}`)
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ usePublicDocsStore.setState({ ...INITIAL })
+ visit('?key=the-key')
+})
+
+describe('PublicDocs — the link itself', () => {
+ it('asks for nothing when the URL carries no key', () => {
+ visit('')
+ render(<PublicDocs />)
+
+ expect(screen.getByText('This link is missing its key')).toBeInTheDocument()
+ expect(api.tree).not.toHaveBeenCalled()
+ })
+
+ it('says what the server said when the key is refused', async () => {
+ api.tree.mockReturnValue(
+ Promise.reject({ response: { data: { detail: 'Invalid documentation view key' } } }) as never,
+ )
+ render(<PublicDocs />)
+
+ expect(await screen.findByText('Invalid documentation view key')).toBeInTheDocument()
+ })
+
+ it('keeps the page out of search engines', async () => {
+ api.tree.mockResolvedValue({ data: [] } as never)
+ render(<PublicDocs />)
+
+ await waitFor(() =>
+ expect(document.querySelector('meta[name="robots"]')?.getAttribute('content')).toContain(
+ 'noindex',
+ ),
+ )
+ })
+})
+
+describe('PublicDocs — the tree', () => {
+ it('renders the Library and the linked documents from one call', async () => {
+ api.tree.mockResolvedValue({
+ data: [
+ summary({ id: 'doc-1', title: 'Offsite backups' }),
+ summary({ id: 'doc-2', kind: 'device', title: 'nas-01' }),
+ ],
+ } as never)
+ render(<PublicDocs />)
+
+ expect(await screen.findByText('Offsite backups')).toBeInTheDocument()
+ expect(screen.getByText('nas-01')).toBeInTheDocument()
+ expect(api.tree).toHaveBeenCalledWith('the-key')
+ })
+
+ it('narrows to what the filter matches', async () => {
+ api.tree.mockResolvedValue({
+ data: [
+ summary({ id: 'doc-1', title: 'Offsite backups' }),
+ summary({ id: 'doc-2', title: 'Where mail is hosted' }),
+ ],
+ } as never)
+ render(<PublicDocs />)
+ await screen.findByText('Offsite backups')
+
+ fireEvent.change(screen.getByLabelText('Filter documents'), { target: { value: 'mail' } })
+
+ expect(screen.getByText('Where mail is hosted')).toBeInTheDocument()
+ expect(screen.queryByText('Offsite backups')).not.toBeInTheDocument()
+ })
+
+ // Every other pivot the app offers reads the inventory, the canvas or the
+ // racks — none of which this page is given.
+ it('offers only the two pivots a document can answer by itself', async () => {
+ api.tree.mockResolvedValue({ data: [summary()] } as never)
+ render(<PublicDocs />)
+ await screen.findByText('Offsite backups')
+
+ const options = Array.from(
+ screen.getByLabelText('Group by').querySelectorAll('option'),
+ ).map((option) => option.textContent)
+ expect(options).toEqual(['A–Z', 'Tag'])
+ })
+})
+
+describe('PublicDocs — reading a document', () => {
+ function doc(overrides: Partial<Doc> = {}): Doc {
+ return { ...summary(), body: '# Offsite backups\n\nThey are in the shed.\n', ...overrides } as Doc
+ }
+
+ it('opens the one that was clicked and puts it in the URL', async () => {
+ api.tree.mockResolvedValue({ data: [summary()] } as never)
+ api.get.mockResolvedValue({ data: doc() } as never)
+ render(<PublicDocs />)
+
+ fireEvent.click(await screen.findByText('Offsite backups'))
+
+ expect(await screen.findByText('They are in the shed.')).toBeInTheDocument()
+ expect(window.location.search).toContain('doc=doc-1')
+ })
+
+ it('opens the document named in the URL on arrival', async () => {
+ visit('?key=the-key&doc=doc-1')
+ api.tree.mockResolvedValue({ data: [summary()] } as never)
+ api.get.mockResolvedValue({ data: doc() } as never)
+ render(<PublicDocs />)
+
+ expect(await screen.findByText('They are in the shed.')).toBeInTheDocument()
+ expect(api.get).toHaveBeenCalledWith('the-key', 'doc-1')
+ })
+
+ it('renders it read-only — nothing on the page writes', async () => {
+ api.tree.mockResolvedValue({ data: [summary({ tags: ['prod'] })] } as never)
+ api.get.mockResolvedValue({ data: doc({ tags: ['prod'] }) } as never)
+ render(<PublicDocs />)
+ fireEvent.click(await screen.findByText('Offsite backups'))
+ await screen.findByText('They are in the shed.')
+
+ expect(screen.queryByText('Edit')).not.toBeInTheDocument()
+ expect(screen.queryByTitle('Delete this document')).not.toBeInTheDocument()
+ expect(screen.queryByLabelText('Regenerate this document')).not.toBeInTheDocument()
+ // The pivot's "Tag" option is a different thing with the same word on it.
+ expect(screen.queryByRole('button', { name: 'Tag' })).not.toBeInTheDocument()
+ expect(screen.queryByLabelText('Remove tag prod')).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/documentation/__tests__/publicStore.test.ts b/frontend/src/documentation/__tests__/publicStore.test.ts
new file mode 100644
index 0000000..aae9239
--- /dev/null
+++ b/frontend/src/documentation/__tests__/publicStore.test.ts
@@ -0,0 +1,218 @@
+/**
+ * The store behind `/docs?key=…`.
+ *
+ * Its whole reason for existing apart from `useDocsStore` is that it cannot
+ * write, so that is asserted here as plainly as the behaviour is.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { docsviewApi } from '@/api/client'
+import { usePublicDocsStore } from '../publicStore'
+import type { Doc, DocRevision, DocumentSummary } from '../types'
+
+vi.mock('@/api/client', () => ({
+ docsviewApi: {
+ tree: vi.fn(),
+ get: vi.fn(),
+ revisions: vi.fn(),
+ revision: vi.fn(),
+ getConfig: vi.fn(),
+ },
+}))
+
+const api = vi.mocked(docsviewApi)
+
+function summary(overrides: Partial<DocumentSummary> = {}): DocumentSummary {
+ return {
+ id: 'doc-1',
+ kind: 'page',
+ title: 'Offsite backups',
+ slug: 'offsite-backups',
+ sort_order: 0,
+ tags: [],
+ frontmatter: {},
+ starred: false,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+function doc(overrides: Partial<Doc> = {}): Doc {
+ return { ...summary(), body: 'the body', ...overrides } as Doc
+}
+
+function revision(overrides: Partial<DocRevision> = {}): DocRevision {
+ return {
+ id: 'rev-1',
+ document_id: 'doc-1',
+ title: 'Offsite backups',
+ reason: 'edit',
+ saved_at: '2026-01-01T00:00:00Z',
+ size: 12,
+ ...overrides,
+ }
+}
+
+/** A rejected axios call, shaped the way the store reads a detail out of it. */
+function refused(detail: string) {
+ return Promise.reject({ response: { data: { detail } } })
+}
+
+const INITIAL = usePublicDocsStore.getState()
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ usePublicDocsStore.setState({ ...INITIAL })
+})
+
+describe('publicStore — loading the tree', () => {
+ it('keeps the key it was given and the documents it was answered', async () => {
+ api.tree.mockResolvedValue({ data: [summary()] } as never)
+ await usePublicDocsStore.getState().load('the-key')
+
+ expect(api.tree).toHaveBeenCalledWith('the-key')
+ const state = usePublicDocsStore.getState()
+ expect(state.key).toBe('the-key')
+ expect(state.docs).toHaveLength(1)
+ expect(state.loaded).toBe(true)
+ expect(state.error).toBeNull()
+ })
+
+ it('surfaces what the server said when the key is refused', async () => {
+ api.tree.mockReturnValue(refused('Invalid documentation view key') as never)
+ await usePublicDocsStore.getState().load('wrong')
+
+ const state = usePublicDocsStore.getState()
+ expect(state.error).toBe('Invalid documentation view key')
+ expect(state.docs).toEqual([])
+ expect(state.loaded).toBe(true)
+ })
+
+ it('falls back to its own words when the server says nothing useful', async () => {
+ api.tree.mockReturnValue(Promise.reject(new Error('network')) as never)
+ await usePublicDocsStore.getState().load('the-key')
+ expect(usePublicDocsStore.getState().error).toBe('Could not load the documentation')
+ })
+})
+
+describe('publicStore — opening a document', () => {
+ it('replays the key and stores the body', async () => {
+ api.tree.mockResolvedValue({ data: [summary()] } as never)
+ api.get.mockResolvedValue({ data: doc() } as never)
+ await usePublicDocsStore.getState().load('the-key')
+ await usePublicDocsStore.getState().open('doc-1')
+
+ expect(api.get).toHaveBeenCalledWith('the-key', 'doc-1')
+ expect(usePublicDocsStore.getState().openDoc?.body).toBe('the body')
+ })
+
+ it('leaves the previous document’s history behind', async () => {
+ api.get.mockResolvedValue({ data: doc({ id: 'doc-2' }) } as never)
+ usePublicDocsStore.setState({
+ historyOpen: true,
+ revisions: [revision()],
+ revisionPreview: { revision: revision(), body: 'older' },
+ })
+
+ await usePublicDocsStore.getState().open('doc-2')
+
+ const state = usePublicDocsStore.getState()
+ expect(state.historyOpen).toBe(false)
+ expect(state.revisions).toEqual([])
+ expect(state.revisionPreview).toBeNull()
+ })
+})
+
+describe('publicStore — history', () => {
+ it('loads the revisions when the rail is opened', async () => {
+ api.revisions.mockResolvedValue({ data: [revision()] } as never)
+ usePublicDocsStore.setState({ key: 'the-key', openDoc: doc() })
+
+ await usePublicDocsStore.getState().toggleHistory()
+
+ expect(api.revisions).toHaveBeenCalledWith('the-key', 'doc-1')
+ expect(usePublicDocsStore.getState().revisions).toHaveLength(1)
+ expect(usePublicDocsStore.getState().historyOpen).toBe(true)
+ })
+
+ it('closing the rail drops the version being read', async () => {
+ usePublicDocsStore.setState({
+ historyOpen: true,
+ revisionPreview: { revision: revision(), body: 'older' },
+ })
+ await usePublicDocsStore.getState().toggleHistory()
+
+ expect(usePublicDocsStore.getState().historyOpen).toBe(false)
+ expect(usePublicDocsStore.getState().revisionPreview).toBeNull()
+ })
+
+ it('keeps the document on screen when its history cannot be read', async () => {
+ api.revisions.mockReturnValue(Promise.reject(new Error('nope')) as never)
+ usePublicDocsStore.setState({ key: 'the-key', openDoc: doc() })
+
+ await usePublicDocsStore.getState().toggleHistory()
+
+ const state = usePublicDocsStore.getState()
+ expect(state.revisions).toEqual([])
+ expect(state.revisionsLoading).toBe(false)
+ expect(state.openDoc).not.toBeNull()
+ expect(state.error).toBeNull()
+ })
+
+ it('previews a listed revision', async () => {
+ api.revision.mockResolvedValue({ data: { ...revision(), body: 'an older body' } } as never)
+ usePublicDocsStore.setState({ key: 'the-key', revisions: [revision()] })
+
+ await usePublicDocsStore.getState().previewRevision('rev-1')
+
+ expect(api.revision).toHaveBeenCalledWith('the-key', 'rev-1')
+ expect(usePublicDocsStore.getState().revisionPreview?.body).toBe('an older body')
+ })
+
+ it('ignores a revision it never listed', async () => {
+ usePublicDocsStore.setState({ key: 'the-key', revisions: [] })
+ await usePublicDocsStore.getState().previewRevision('rev-9')
+ expect(api.revision).not.toHaveBeenCalled()
+ })
+})
+
+describe('publicStore — view preferences', () => {
+ it('holds the filter, the pivot and the expanded keys', () => {
+ const store = usePublicDocsStore.getState()
+ store.setFilter('backup')
+ store.setGroupBy('tag')
+ store.toggleExpanded('collapsed:tag:prod')
+ expect(usePublicDocsStore.getState().filter).toBe('backup')
+ expect(usePublicDocsStore.getState().groupBy).toBe('tag')
+ expect(usePublicDocsStore.getState().expanded).toEqual(['collapsed:tag:prod'])
+
+ usePublicDocsStore.getState().toggleExpanded('collapsed:tag:prod')
+ expect(usePublicDocsStore.getState().expanded).toEqual([])
+ })
+})
+
+describe('publicStore — cannot write', () => {
+ // The separation from `useDocsStore` is the security property, so it is a
+ // test rather than a comment: nothing here can save, delete or restore.
+ it('exposes no action that changes a document', () => {
+ const state = usePublicDocsStore.getState() as Record<string, unknown>
+ for (const action of [
+ 'save',
+ 'create',
+ 'remove',
+ 'delete',
+ 'move',
+ 'rename',
+ 'setTags',
+ 'toggleStar',
+ 'markReviewed',
+ 'regenerate',
+ 'restore',
+ 'scaffold',
+ 'setDraft',
+ ]) {
+ expect(state[action]).toBeUndefined()
+ }
+ })
+})
diff --git a/frontend/src/documentation/__tests__/tree.test.ts b/frontend/src/documentation/__tests__/tree.test.ts
index 3c94b08..d4d5483 100644
--- a/frontend/src/documentation/__tests__/tree.test.ts
+++ b/frontend/src/documentation/__tests__/tree.test.ts
@@ -6,6 +6,7 @@ import {
bucketsFor,
buildDeviceTree,
buildLibraryTree,
+ buildLinkedDocTree,
canMoveInto,
deviceLabel,
docState,
@@ -59,6 +60,58 @@ function node(id: string, data: Partial<NodeData>): Node<NodeData> {
}
}
+// The public documentation view is handed no inventory, no canvas and no racks,
+// so it cannot use `buildDeviceTree`. This builder groups the same documents by
+// what they carry themselves.
+describe('buildLinkedDocTree', () => {
+ it('puts everything under one bucket when flat', () => {
+ const groups = buildLinkedDocTree([doc(), doc({ id: 'doc-2', title: 'switch-01' })], 'flat')
+ expect(groups).toHaveLength(1)
+ expect(groups[0].label).toBe('All documents')
+ expect(groups[0].items.map((i) => i.label)).toEqual(['nas-01', 'switch-01'])
+ })
+
+ it('leaves the Library out — those are filed by hand, not pivoted', () => {
+ const groups = buildLinkedDocTree(
+ [doc(), doc({ id: 'doc-2', kind: 'page' }), doc({ id: 'doc-3', kind: 'folder' })],
+ 'flat',
+ )
+ expect(groups[0].items.map((i) => i.id)).toEqual(['doc-1'])
+ })
+
+ it('files a document under each of its tags, and the untagged together', () => {
+ const groups = buildLinkedDocTree(
+ [
+ doc({ id: 'doc-1', title: 'nas-01', tags: ['storage', 'prod'] }),
+ doc({ id: 'doc-2', title: 'switch-01', tags: ['prod'] }),
+ doc({ id: 'doc-3', title: 'printer' }),
+ ],
+ 'tag',
+ )
+ const byLabel = Object.fromEntries(groups.map((g) => [g.label, g.items.map((i) => i.title ?? i.label)]))
+ expect(byLabel['prod']).toEqual(['nas-01', 'switch-01'])
+ expect(byLabel['storage']).toEqual(['nas-01'])
+ expect(byLabel['Untagged']).toEqual(['printer'])
+ })
+
+ it('sorts the last-resort bucket to the bottom', () => {
+ const groups = buildLinkedDocTree(
+ [doc({ id: 'doc-1', tags: ['zzz'] }), doc({ id: 'doc-2' })],
+ 'tag',
+ )
+ expect(groups.map((g) => g.label)).toEqual(['zzz', 'Untagged'])
+ })
+
+ it('badges an overdue document, and never a drifted one', () => {
+ // Drift is decided against the inventory row, which this view has no access
+ // to — so the badge can only ever say written / header-only / overdue.
+ const groups = buildLinkedDocTree([doc({ edited_at: '2026-01-02T00:00:00Z' })], 'flat', {
+ overdue: new Set(['doc-1']),
+ })
+ expect(groups[0].items[0].state).toBe('overdue')
+ })
+})
+
const designs: Design[] = [
{ id: 'design-1', name: 'Home network', design_type: 'network' } as Design,
]
diff --git a/frontend/src/documentation/components/PublicDocs.tsx b/frontend/src/documentation/components/PublicDocs.tsx
new file mode 100644
index 0000000..e38c736
--- /dev/null
+++ b/frontend/src/documentation/components/PublicDocs.tsx
@@ -0,0 +1,270 @@
+/**
+ * PublicDocs — the read-only documentation space at `/docs?key=<DOCS_VIEW_KEY>`.
+ *
+ * A page of its own, booted straight from `main.tsx` before any session exists,
+ * the way the live-view canvas is. It reads the same documents the app does and
+ * renders them with the same components — the tree, the filter, the viewer — in
+ * read-only mode: no editing, no restoring, no deleting, and no way to reach the
+ * inventory or a canvas from here.
+ *
+ * Standalone builds have no backend to ask, so the page says so rather than
+ * pretending to be empty.
+ */
+
+import { useEffect, useMemo, useState } from 'react'
+import { BookOpen, Search, X } from 'lucide-react'
+
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { isOverdue } from '../frontmatter'
+import { usePublicDocsStore, type PublicGroupBy } from '../publicStore'
+import { buildLibraryTree, buildLinkedDocTree, filterGroups, filterTree } from '../tree'
+import { GROUP_BY_LABELS, type TreeLeaf } from '../types'
+import { DocTreeGroups, DocTreeItem } from './DocTree'
+import { DocViewer } from './DocViewer'
+
+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
+
+const GROUP_OPTIONS: PublicGroupBy[] = ['flat', 'tag']
+
+function readUrl(): { key: string | null; docId: string | null } {
+ const params = new URLSearchParams(window.location.search)
+ return { key: params.get('key'), docId: params.get('doc') }
+}
+
+/** Keep the open document in the address bar, so a page can be linked to. */
+function writeDocInUrl(docId: string | null): void {
+ const url = new URL(window.location.href)
+ if (docId) url.searchParams.set('doc', docId)
+ else url.searchParams.delete('doc')
+ window.history.replaceState({}, '', url)
+}
+
+function Centered({ title, detail }: { title: string; detail?: string }) {
+ return (
+ <div className="flex h-screen items-center justify-center p-6 text-center">
+ <div>
+ <BookOpen className="mx-auto mb-3 opacity-30" size={26} />
+ <p className="text-sm font-medium">{title}</p>
+ {detail && <p className="mt-1 text-xs text-muted-foreground">{detail}</p>}
+ </div>
+ </div>
+ )
+}
+
+export default function PublicDocs() {
+ const {
+ docs,
+ loaded,
+ loading,
+ error,
+ openDoc,
+ historyOpen,
+ revisions,
+ revisionsLoading,
+ revisionPreview,
+ filter,
+ groupBy,
+ expanded,
+ load,
+ open,
+ toggleHistory,
+ previewRevision,
+ closeRevisionPreview,
+ setFilter,
+ setGroupBy,
+ toggleExpanded,
+ } = usePublicDocsStore()
+
+ const [boot] = useState(readUrl)
+
+ useEffect(() => {
+ // Nothing here should ever be indexed: it is somebody's homelab, published
+ // to whoever holds one link.
+ document.title = 'Documentation'
+ const meta = document.createElement('meta')
+ meta.name = 'robots'
+ meta.content = 'noindex, nofollow'
+ document.head.appendChild(meta)
+ return () => meta.remove()
+ }, [])
+
+ useEffect(() => {
+ if (STANDALONE || !boot.key) return
+ void load(boot.key).then(() => {
+ if (boot.docId) void open(boot.docId)
+ })
+ }, [boot, load, open])
+
+ const overdue = useMemo(
+ () =>
+ new Set(
+ docs
+ .filter((doc) => isOverdue(doc.frontmatter ?? {}, doc.reviewed_at, doc.created_at))
+ .map((doc) => doc.id),
+ ),
+ [docs],
+ )
+ const starred = useMemo(
+ () => new Set(docs.filter((doc) => doc.starred).map((doc) => doc.id)),
+ [docs],
+ )
+
+ const libraryItems = useMemo(
+ () => filterTree(buildLibraryTree(docs), filter),
+ [docs, filter],
+ )
+ const linkedGroups = useMemo(
+ () => filterGroups(buildLinkedDocTree(docs, groupBy, { overdue }), filter),
+ [docs, groupBy, overdue, filter],
+ )
+
+ const linkable = useMemo(
+ () => docs.map((doc) => ({ id: doc.id, slug: doc.slug, title: doc.title })),
+ [docs],
+ )
+
+ function handleSelect(leaf: TreeLeaf) {
+ if (!leaf.docId) return
+ void open(leaf.docId)
+ writeDocInUrl(leaf.docId)
+ }
+
+ if (STANDALONE) {
+ return (
+ <Centered
+ title="Documentation needs the backend"
+ detail="This build runs without one, so there is nothing to share."
+ />
+ )
+ }
+ if (!boot.key) {
+ return (
+ <Centered
+ title="This link is missing its key"
+ detail="A documentation link looks like /docs?key=…"
+ />
+ )
+ }
+ if (error) return <Centered title={error} />
+ if (loading || !loaded) return <Centered title="Loading…" />
+
+ return (
+ <div className="flex h-screen min-h-0 bg-background text-foreground">
+ <aside className="flex w-[260px] min-h-0 shrink-0 flex-col border-r border-border">
+ <div className="flex items-center gap-1 border-b border-border px-2 py-2">
+ <Search size={13} className="shrink-0 opacity-50" />
+ <Input
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ placeholder="Filter documents"
+ aria-label="Filter documents"
+ className="h-6 border-0 bg-transparent px-1 text-xs shadow-none focus-visible:ring-0"
+ />
+ {filter && (
+ <Button size="icon-xs" variant="ghost" aria-label="Clear filter" onClick={() => setFilter('')}>
+ <X />
+ </Button>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1 border-b border-border px-2 py-1.5">
+ <label
+ htmlFor="public-docs-group-by"
+ className="text-[10px] uppercase tracking-wide text-muted-foreground/70"
+ >
+ Group by
+ </label>
+ <select
+ id="public-docs-group-by"
+ value={groupBy}
+ onChange={(event) => setGroupBy(event.target.value as PublicGroupBy)}
+ className="ml-auto cursor-pointer rounded border border-border bg-transparent px-1 py-0.5 text-xs"
+ >
+ {GROUP_OPTIONS.map((option) => (
+ <option key={option} value={option}>
+ {GROUP_BY_LABELS[option]}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto py-1">
+ <p className="px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50">
+ Library
+ </p>
+ {libraryItems.length === 0 ? (
+ <p className="px-3 py-1 text-xs text-muted-foreground/60">Nothing filed here.</p>
+ ) : (
+ libraryItems.map((leaf) => (
+ <DocTreeItem
+ key={leaf.id}
+ leaf={leaf}
+ depth={0}
+ activeId={openDoc?.id ?? null}
+ expanded={expanded}
+ starred={starred}
+ onSelect={handleSelect}
+ onToggle={toggleExpanded}
+ />
+ ))
+ )}
+
+ <p className="mt-3 px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50">
+ Devices &amp; canvases
+ </p>
+ <DocTreeGroups
+ groups={linkedGroups}
+ activeId={openDoc?.id ?? null}
+ expanded={expanded}
+ starred={starred}
+ onSelect={handleSelect}
+ onToggle={toggleExpanded}
+ />
+ </div>
+
+ <p className="border-t border-border px-3 py-2 text-[10px] text-muted-foreground/60">
+ Read-only
+ </p>
+ </aside>
+
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ {openDoc ? (
+ <DocViewer
+ readOnly
+ doc={openDoc}
+ docs={linkable}
+ devices={[]}
+ drifted={false}
+ history={{
+ open: historyOpen,
+ loading: revisionsLoading,
+ revisions,
+ preview: revisionPreview,
+ onToggle: () => void toggleHistory(),
+ onSelect: (revisionId) => void previewRevision(revisionId),
+ onClosePreview: closeRevisionPreview,
+ }}
+ onDownload={() => {
+ const blob = new Blob([openDoc.body], { type: 'text/markdown' })
+ const link = document.createElement('a')
+ link.href = URL.createObjectURL(blob)
+ link.download = `${openDoc.slug || 'document'}.md`
+ link.click()
+ URL.revokeObjectURL(link.href)
+ }}
+ onOpenDoc={(id) => {
+ void open(id)
+ writeDocInUrl(id)
+ }}
+ />
+ ) : (
+ <Centered
+ title={docs.length === 0 ? 'Nothing is documented yet' : 'Pick a document'}
+ detail={docs.length === 0 ? undefined : 'Everything here is read-only.'}
+ />
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/publicStore.ts b/frontend/src/documentation/publicStore.ts
new file mode 100644
index 0000000..6400b24
--- /dev/null
+++ b/frontend/src/documentation/publicStore.ts
@@ -0,0 +1,158 @@
+import { create } from 'zustand'
+
+import { docsviewApi } from '@/api/client'
+import type { Doc, DocRevision, DocumentSummary } from './types'
+
+/**
+ * The read-only documentation space served at `/docs?key=…`.
+ *
+ * Deliberately *not* a mode flag on `useDocsStore`. That store owns every write
+ * the section has — save, create, move, delete, tags, the draft mirrored to
+ * localStorage — and the authenticated axios instance they all travel on. A
+ * flag there would leave every one of them one bug away from a page anybody
+ * holding a URL can open. This store imports none of them, so it cannot reach
+ * one by accident: what it does not have, it cannot call.
+ *
+ * The key travels in state because every request repeats it; it is the whole
+ * credential and the page has nothing else.
+ */
+
+/**
+ * How the documents that describe something elsewhere are pivoted.
+ *
+ * The app offers a dozen pivots — zone, subnet, rack, vendor, status — and each
+ * of them reads the inventory, the canvas or the racks. This page is handed
+ * none of those, on purpose: they are full of addresses and hardware, and the
+ * key grants documents only. What is left is what a document carries itself.
+ */
+export type PublicGroupBy = 'tag' | 'flat'
+
+export interface PublicDocsState {
+ /** The key from the URL, replayed on every request. */
+ key: string
+ docs: DocumentSummary[]
+ loaded: boolean
+ loading: boolean
+ /** What the server said, verbatim: disabled, or a bad key. */
+ error: string | null
+
+ openDoc: Doc | null
+ openLoading: boolean
+
+ historyOpen: boolean
+ revisions: DocRevision[]
+ revisionsLoading: boolean
+ revisionPreview: { revision: DocRevision; body: string } | null
+
+ filter: string
+ groupBy: PublicGroupBy
+ expanded: string[]
+
+ load: (key: string) => Promise<void>
+ open: (id: string) => Promise<void>
+ toggleHistory: () => Promise<void>
+ previewRevision: (revisionId: string) => Promise<void>
+ closeRevisionPreview: () => void
+ setFilter: (filter: string) => void
+ setGroupBy: (groupBy: PublicGroupBy) => void
+ toggleExpanded: (key: string) => void
+}
+
+function message(error: unknown, fallback: string): string {
+ const detail = (error as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail
+ return typeof detail === 'string' ? detail : fallback
+}
+
+export const usePublicDocsStore = create<PublicDocsState>()((set, get) => ({
+ key: '',
+ docs: [],
+ loaded: false,
+ loading: false,
+ error: null,
+
+ openDoc: null,
+ openLoading: false,
+
+ historyOpen: false,
+ revisions: [],
+ revisionsLoading: false,
+ revisionPreview: null,
+
+ filter: '',
+ groupBy: 'flat',
+ expanded: [],
+
+ load: async (key) => {
+ set({ key, loading: true, error: null })
+ try {
+ const { data } = await docsviewApi.tree(key)
+ set({ docs: data, loaded: true, loading: false })
+ } catch (error) {
+ set({
+ loading: false,
+ loaded: true,
+ docs: [],
+ error: message(error, 'Could not load the documentation'),
+ })
+ }
+ },
+
+ open: async (id) => {
+ // A new document closes whatever was being read of the old one's history:
+ // the rail and the preview belong to the document, not to the page.
+ set({
+ openLoading: true,
+ historyOpen: false,
+ revisions: [],
+ revisionsLoading: false,
+ revisionPreview: null,
+ })
+ try {
+ const { data } = await docsviewApi.get(get().key, id)
+ set({ openDoc: data, openLoading: false })
+ } catch (error) {
+ set({ openLoading: false, error: message(error, 'Could not open that document') })
+ }
+ },
+
+ toggleHistory: async () => {
+ const { historyOpen, openDoc, key } = get()
+ if (historyOpen) {
+ set({ historyOpen: false, revisionPreview: null })
+ return
+ }
+ set({ historyOpen: true })
+ if (!openDoc) return
+ set({ revisionsLoading: true })
+ try {
+ const { data } = await docsviewApi.revisions(key, openDoc.id)
+ set({ revisions: data, revisionsLoading: false })
+ } catch {
+ // An unreadable history is not worth taking the page down for: the
+ // document itself is on screen and still readable.
+ set({ revisions: [], revisionsLoading: false })
+ }
+ },
+
+ previewRevision: async (revisionId) => {
+ const revision = get().revisions.find((r) => r.id === revisionId)
+ if (!revision) return
+ try {
+ const { data } = await docsviewApi.revision(get().key, revisionId)
+ set({ revisionPreview: { revision, body: data.body } })
+ } catch {
+ set({ revisionPreview: null })
+ }
+ },
+
+ closeRevisionPreview: () => set({ revisionPreview: null }),
+
+ setFilter: (filter) => set({ filter }),
+ setGroupBy: (groupBy) => set({ groupBy }),
+ toggleExpanded: (key) => {
+ const expanded = get().expanded
+ set({
+ expanded: expanded.includes(key) ? expanded.filter((k) => k !== key) : [...expanded, key],
+ })
+ },
+}))
diff --git a/frontend/src/documentation/tree.ts b/frontend/src/documentation/tree.ts
index 1e65327..241ef59 100644
--- a/frontend/src/documentation/tree.ts
+++ b/frontend/src/documentation/tree.ts
@@ -302,6 +302,54 @@ export function buildLibraryTree(docs: DocumentSummary[]): TreeLeaf[] {
return build(null)
}
+/**
+ * The documents that describe something elsewhere — a device, a canvas node, a
+ * design — grouped without asking the inventory anything.
+ *
+ * `buildDeviceTree` pivots on the inventory rows, the canvas nodes and the
+ * racks. The public documentation view is handed none of those, and should not
+ * be: they are full of addresses and hardware. These documents still have to
+ * appear there, so they are grouped by what they carry themselves — their own
+ * frontmatter tags, or one flat bucket. The label is the document's own title,
+ * denormalized onto the row for exactly this reason: it outlives the thing it
+ * describes.
+ */
+export function buildLinkedDocTree(
+ docs: DocumentSummary[],
+ groupBy: 'tag' | 'flat',
+ opts: { overdue?: Set<string> } = {},
+): TreeGroup[] {
+ const groups = new Map<string, TreeLeaf[]>()
+ for (const doc of docs) {
+ if (doc.kind === 'page' || doc.kind === 'folder') continue
+ const leaf: TreeLeaf = {
+ id: doc.id,
+ label: doc.title,
+ docId: doc.id,
+ kind: doc.kind,
+ // No drift flag: deciding it needs the inventory row this view has no
+ // access to, so the badge says written / header-only / overdue only.
+ state: docState(doc, { overdue: opts.overdue?.has(doc.id) }),
+ icon: doc.icon,
+ }
+ const buckets =
+ groupBy === 'tag' ? (doc.tags?.length ? doc.tags : ['Untagged']) : ['All documents']
+ for (const bucket of buckets) {
+ const items = groups.get(bucket) ?? []
+ items.push(leaf)
+ groups.set(bucket, items)
+ }
+ }
+
+ return [...groups.entries()]
+ .map(([label, items]) => ({
+ key: `${groupBy}:${label}`,
+ label,
+ items: items.sort((a, b) => collator.compare(a.label, b.label)),
+ }))
+ .sort(compareGroups)
+}
+
/** Filter a tree by a typed query, keeping the folders that lead to a match. */
export function filterTree(items: TreeLeaf[], query: string): TreeLeaf[] {
const needle = query.trim().toLowerCase()
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 5e6b74e..d7a0604 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -3,12 +3,17 @@ import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import LiveView from './components/LiveView.tsx'
-import { isLiveViewPath } from './utils/basePath.ts'
+import PublicDocs from './documentation/components/PublicDocs.tsx'
+import { isDocsViewPath, isLiveViewPath } from './utils/basePath.ts'
+// Three pages share one bundle: the app, the read-only canvas, and the
+// read-only documentation. Which one boots is decided by the path alone, before
+// any store or session exists.
const isLiveView = isLiveViewPath(window.location.pathname)
+const isDocsView = isDocsViewPath(window.location.pathname)
createRoot(document.getElementById('root')!).render(
<StrictMode>
- {isLiveView ? <LiveView /> : <App />}
+ {isLiveView ? <LiveView /> : isDocsView ? <PublicDocs /> : <App />}
</StrictMode>,
)
diff --git a/frontend/src/utils/__tests__/basePath.test.ts b/frontend/src/utils/__tests__/basePath.test.ts
index 3dfdc68..e2eced3 100644
--- a/frontend/src/utils/__tests__/basePath.test.ts
+++ b/frontend/src/utils/__tests__/basePath.test.ts
@@ -5,6 +5,7 @@ import {
normalizeBasePath,
withBase,
resolveServerPath,
+ isDocsViewPath,
isLiveViewPath,
} from '@/utils/basePath'
@@ -87,6 +88,22 @@ describe('isLiveViewPath', () => {
})
})
+describe('isDocsViewPath', () => {
+ it('matches the documentation view under the base only', () => {
+ expect(isDocsViewPath('/homelab/docs', SUB)).toBe(true)
+ expect(isDocsViewPath('/docs', SUB)).toBe(false)
+ expect(isDocsViewPath('/homelab/', SUB)).toBe(false)
+ expect(isDocsViewPath('/homelab/documents', SUB)).toBe(false)
+ expect(isDocsViewPath('/docs')).toBe(true)
+ })
+
+ // Two public pages, two paths: one must never answer for the other.
+ it('is not the live view', () => {
+ expect(isDocsViewPath('/view')).toBe(false)
+ expect(isLiveViewPath('/docs')).toBe(false)
+ })
+})
+
describe('module wiring', () => {
afterEach(() => {
vi.unstubAllEnvs()
@@ -101,6 +118,7 @@ describe('module wiring', () => {
expect(mod.API_BASE_URL).toBe('/homelab/api/v1')
expect(mod.withBase('view')).toBe('/homelab/view')
expect(mod.isLiveViewPath('/homelab/view')).toBe(true)
+ expect(mod.isDocsViewPath('/homelab/docs')).toBe(true)
expect(mod.resolveServerPath('/api/v1/media/a.png')).toBe('/homelab/api/v1/media/a.png')
})
})
diff --git a/frontend/src/utils/basePath.ts b/frontend/src/utils/basePath.ts
index 51084bf..f88860e 100644
--- a/frontend/src/utils/basePath.ts
+++ b/frontend/src/utils/basePath.ts
@@ -50,3 +50,14 @@ export function resolveServerPath(url: string, base: string = BASE_PATH): string
export function isLiveViewPath(pathname: string, base: string = BASE_PATH): boolean {
return pathname === withBase('view', base)
}
+
+/**
+ * Is this pathname the read-only documentation view (`/docs`, `/homelab/docs`)?
+ *
+ * A path of its own, not the app's `?view=docs` query param: that one is a
+ * section of the logged-in app, this one is a different page served to someone
+ * holding only a key.
+ */
+export function isDocsViewPath(pathname: string, base: string = BASE_PATH): boolean {
+ return pathname === withBase('docs', base)
+}