Skip to content

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

fix(docs): keep a document's URL across a refresh

Pouzorb40e2cc1db51
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 1b888ce..60eff30 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -8,7 +8,8 @@ import { getCenteredPosition } from '@/utils/viewportCenter'
import { resolveVirtualEdgeParent } from '@/utils/virtualEdgeParent'
import { generateMarkdownTable } from '@/utils/exportMarkdown'
import { copyToClipboard } from '@/utils/clipboard'
-import { getDesignIdFromUrl, setDesignIdInUrl, getDocIdFromUrl, isDocsViewInUrl, setDocsViewInUrl } from '@/utils/designUrl'
+import { getDesignIdFromUrl, setDesignIdInUrl } from '@/utils/designUrl'
+import { useDocsUrlSync } from '@/hooks/useDocsUrlSync'
import { withBase } from '@/utils/basePath'
import { ExportModal } from '@/components/modals/ExportModal'
import { exportCanvasToYaml, downloadYaml } from '@/utils/exportYaml'
@@ -488,10 +489,22 @@ export default function App() {
if (activeDesignId) setDesignIdInUrl(activeDesignId)
}, [activeDesignId])
- // A document is linkable in the same way: `?view=docs&doc=<id>`.
- useEffect(() => {
- setDocsViewInUrl(appView === 'documentation', openDocId)
- }, [appView, openDocId])
+ // A document is linkable in the same way: `?view=docs&doc=<id>` — written on
+ // every change, and read back on boot so a refresh reopens it.
+ const restoreDocsUrl = useCallback(
+ async (docId: string | null) => {
+ setAppView('documentation')
+ if (docId) await useDocsStore.getState().open(docId)
+ },
+ [setAppView],
+ )
+ useDocsUrlSync({
+ view: appView,
+ openDocId,
+ ready: isAuthenticated,
+ enabled: !STANDALONE,
+ onRestore: restoreDocsUrl,
+ })
// The canvas' way into Documentation: it knows a device id, and the section
// resolves that to a document — writing one from the device's facts when
@@ -505,16 +518,6 @@ export default function App() {
[setAppView],
)
- // Reopen the section, and the document, the URL asks for. Once, on boot.
- const docsUrlApplied = useRef(false)
- useEffect(() => {
- if (docsUrlApplied.current || STANDALONE || !isDocsViewInUrl()) return
- docsUrlApplied.current = true
- setAppView('documentation')
- const docId = getDocIdFromUrl()
- if (docId) void useDocsStore.getState().open(docId)
- }, [setAppView])
-
// Keep refs for store actions so keydown handler is always up-to-date without re-registering
const undoRef = useRef(undo)
const redoRef = useRef(redo)
diff --git a/frontend/src/hooks/__tests__/useDocsUrlSync.test.ts b/frontend/src/hooks/__tests__/useDocsUrlSync.test.ts
new file mode 100644
index 0000000..52ef6b5
--- /dev/null
+++ b/frontend/src/hooks/__tests__/useDocsUrlSync.test.ts
@@ -0,0 +1,154 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, waitFor } from '@testing-library/react'
+import { useDocsUrlSync } from '@/hooks/useDocsUrlSync'
+import type { AppView } from '@/stores/uiStore'
+
+const search = () => window.location.search
+
+interface Props {
+ view: AppView
+ openDocId: string | null
+ ready: boolean
+ enabled: boolean
+ onRestore: (docId: string | null) => void | Promise<void>
+}
+
+const setup = (props: Partial<Props> = {}) => {
+ const onRestore = props.onRestore ?? vi.fn()
+ return renderHook((p: Props) => useDocsUrlSync(p), {
+ initialProps: {
+ view: 'canvas' as AppView,
+ openDocId: null,
+ ready: true,
+ enabled: true,
+ ...props,
+ onRestore,
+ },
+ })
+}
+
+describe('useDocsUrlSync', () => {
+ beforeEach(() => {
+ window.history.replaceState(null, '', '/')
+ })
+
+ it('writes the section and the document into the URL', async () => {
+ const { rerender } = setup()
+ await waitFor(() => expect(search()).toBe(''))
+
+ rerender({ view: 'documentation', openDocId: 'doc-1', ready: true, enabled: true, onRestore: vi.fn() })
+ await waitFor(() => {
+ const params = new URLSearchParams(search())
+ expect(params.get('view')).toBe('docs')
+ expect(params.get('doc')).toBe('doc-1')
+ })
+ })
+
+ it('drops both params when leaving the section', async () => {
+ const { rerender } = setup({ view: 'documentation', openDocId: 'doc-1' })
+ await waitFor(() => expect(new URLSearchParams(search()).get('doc')).toBe('doc-1'))
+
+ rerender({ view: 'canvas', openDocId: null, ready: true, enabled: true, onRestore: vi.fn() })
+ await waitFor(() => {
+ const params = new URLSearchParams(search())
+ expect(params.get('view')).toBeNull()
+ expect(params.get('doc')).toBeNull()
+ })
+ })
+
+ it('preserves the design param', async () => {
+ window.history.replaceState(null, '', '/?design=abc')
+ setup({ view: 'documentation', openDocId: 'doc-1' })
+ await waitFor(() => expect(new URLSearchParams(search()).get('design')).toBe('abc'))
+ })
+
+ // The regression: the writer used to run before the reader and overwrite
+ // `?view=docs&doc=` with the default view, so a refresh lost the document.
+ it('restores the document the URL asks for instead of wiping it', async () => {
+ window.history.replaceState(null, '', '/?design=abc&view=docs&doc=doc-9')
+ const onRestore = vi.fn()
+ setup({ onRestore })
+
+ await waitFor(() => expect(onRestore).toHaveBeenCalledWith('doc-9'))
+ const params = new URLSearchParams(search())
+ expect(params.get('view')).toBe('docs')
+ expect(params.get('doc')).toBe('doc-9')
+ })
+
+ it('restores the section when the URL names no document', async () => {
+ window.history.replaceState(null, '', '/?view=docs')
+ const onRestore = vi.fn()
+ setup({ onRestore })
+
+ await waitFor(() => expect(onRestore).toHaveBeenCalledWith(null))
+ })
+
+ it('keeps the URL across the auth bootstrap and restores once ready', async () => {
+ window.history.replaceState(null, '', '/?view=docs&doc=doc-9')
+ const onRestore = vi.fn()
+ const { rerender } = setup({ ready: false, onRestore })
+
+ // Still signed out: nothing fetched, and the request survives in the URL.
+ await waitFor(() => expect(new URLSearchParams(search()).get('doc')).toBe('doc-9'))
+ expect(onRestore).not.toHaveBeenCalled()
+
+ rerender({ view: 'canvas', openDocId: null, ready: true, enabled: true, onRestore })
+ await waitFor(() => expect(onRestore).toHaveBeenCalledWith('doc-9'))
+ })
+
+ it('holds the URL until an awaited restore settles', async () => {
+ window.history.replaceState(null, '', '/?view=docs&doc=doc-9')
+ let release: () => void = () => {}
+ const onRestore = vi.fn(() => new Promise<void>((resolve) => (release = resolve)))
+ const { rerender } = setup({ onRestore })
+
+ await waitFor(() => expect(onRestore).toHaveBeenCalled())
+ // The section has switched but the document has not landed yet: the writer
+ // must not publish `view=docs` with no `doc` in the meantime.
+ rerender({ view: 'documentation', openDocId: null, ready: true, enabled: true, onRestore })
+ expect(new URLSearchParams(search()).get('doc')).toBe('doc-9')
+
+ release()
+ rerender({ view: 'documentation', openDocId: 'doc-9', ready: true, enabled: true, onRestore })
+ await waitFor(() => expect(new URLSearchParams(search()).get('doc')).toBe('doc-9'))
+ })
+
+ it('releases the URL when the restore fails, so the section can be left', async () => {
+ window.history.replaceState(null, '', '/?view=docs&doc=gone')
+ const onRestore = vi.fn(() => Promise.reject(new Error('no such document')))
+ const { rerender } = setup({ onRestore })
+
+ await waitFor(() => expect(onRestore).toHaveBeenCalled())
+ rerender({ view: 'canvas', openDocId: null, ready: true, enabled: true, onRestore })
+ await waitFor(() => expect(new URLSearchParams(search()).get('doc')).toBeNull())
+ })
+
+ it('ignores the URL in standalone, where documents need a backend', async () => {
+ window.history.replaceState(null, '', '/?view=docs&doc=doc-9')
+ const onRestore = vi.fn()
+ setup({ enabled: false, onRestore })
+
+ await waitFor(() => expect(search()).toBe(''))
+ expect(onRestore).not.toHaveBeenCalled()
+ })
+
+ it('restores only once', async () => {
+ window.history.replaceState(null, '', '/?view=docs&doc=doc-9')
+ const onRestore = vi.fn()
+ const { rerender } = setup({ onRestore })
+
+ await waitFor(() => expect(onRestore).toHaveBeenCalledTimes(1))
+ rerender({ view: 'documentation', openDocId: 'doc-9', ready: true, enabled: true, onRestore })
+ rerender({ view: 'documentation', openDocId: 'doc-2', ready: true, enabled: true, onRestore })
+ await waitFor(() => expect(new URLSearchParams(search()).get('doc')).toBe('doc-2'))
+ expect(onRestore).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not add history entries', async () => {
+ const before = window.history.length
+ const { rerender } = setup()
+ rerender({ view: 'documentation', openDocId: 'doc-1', ready: true, enabled: true, onRestore: vi.fn() })
+ await waitFor(() => expect(new URLSearchParams(search()).get('doc')).toBe('doc-1'))
+ expect(window.history.length).toBe(before)
+ })
+})
diff --git a/frontend/src/hooks/useDocsUrlSync.ts b/frontend/src/hooks/useDocsUrlSync.ts
new file mode 100644
index 0000000..72cc17f
--- /dev/null
+++ b/frontend/src/hooks/useDocsUrlSync.ts
@@ -0,0 +1,73 @@
+import { useEffect, useRef, useState } from 'react'
+import { getDocIdFromUrl, isDocsViewInUrl, setDocsViewInUrl } from '@/utils/designUrl'
+import type { AppView } from '@/stores/uiStore'
+
+interface DocsUrlSyncOptions {
+ /** The section the app is showing. */
+ view: AppView
+ /** The open document's id, or null when the section shows no document. */
+ openDocId: string | null
+ /**
+ * True once the app may talk to the backend — the session is bootstrapped.
+ * Restoring earlier would fetch the document without a session and land on
+ * an error the user never sees, because the login page is still up.
+ */
+ ready: boolean
+ /** False in standalone: documents need the backend, so the URL means nothing. */
+ enabled: boolean
+ /**
+ * Honour the URL: switch to Documentation and open `docId` when there is one.
+ * Awaited — the URL stays untouched until it settles.
+ */
+ onRestore: (docId: string | null) => void | Promise<void>
+}
+
+/**
+ * Two-way sync between the Documentation section and `?view=docs&doc=<id>`,
+ * so a document survives a refresh and its URL can be shared.
+ *
+ * The order matters, and used not to: reflecting the view into the address bar
+ * and reading the address bar were two effects, and the writer ran first. On
+ * boot it wrote the *default* view — canvas, no document — over the very params
+ * the reader was about to consume, so a refresh always came back to the canvas.
+ * Here the URL's request is captured at the first render and the writer stays
+ * quiet until that request has been honoured (or there was none to honour).
+ */
+export function useDocsUrlSync({ view, openDocId, ready, enabled, onRestore }: DocsUrlSyncOptions): void {
+ // Read once, at the first render, before any effect can rewrite the address
+ // bar — a lazy initializer, not a ref, which must not be read during render.
+ const [boot] = useState(() => {
+ const docs = enabled && isDocsViewInUrl()
+ return { docs, docId: docs ? getDocIdFromUrl() : null }
+ })
+
+ // Nothing to restore means the writer owns the URL from the first render.
+ const [restored, setRestored] = useState(!boot.docs)
+
+ // Kept in a ref so a caller that passes a fresh closure each render doesn't
+ // re-run the restore.
+ const restore = useRef(onRestore)
+ useEffect(() => {
+ restore.current = onRestore
+ })
+
+ useEffect(() => {
+ if (restored || !ready) return
+ let cancelled = false
+ // Settled either way — a document that no longer exists must not keep the
+ // URL frozen, or the section could never be left. `then(f, f)` rather than
+ // `finally`, which would rethrow the rejection as an unhandled one.
+ const settle = () => {
+ if (!cancelled) setRestored(true)
+ }
+ void Promise.resolve(restore.current(boot.docId)).then(settle, settle)
+ return () => {
+ cancelled = true
+ }
+ }, [restored, ready, boot])
+
+ useEffect(() => {
+ if (!restored) return
+ setDocsViewInUrl(view === 'documentation', openDocId)
+ }, [restored, view, openDocId])
+}