Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(docs): give the document editor a working undo
Pouzor6ba3d1a38fe0
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex ef740b1..db27c6d 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -530,8 +530,19 @@ export default function App() {const isInput = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement).isContentEditableif (ctrl && e.key === 's') { e.preventDefault(); handleSaveRef.current(); return }- if (ctrl && e.key === 'z') { e.preventDefault(); undoRef.current(); return }- if (ctrl && (e.key === 'y' || (e.shiftKey && e.key === 'z'))) { e.preventDefault(); redoRef.current(); return }+ // Undo belongs to whatever is being typed in — the document editor keeps+ // its own history, a plain field has the browser's — and the canvas only+ // gets it when nothing has the caret.+ if (ctrl && e.key.toLowerCase() === 'z') {+ if (isInput) return+ e.preventDefault()+ // Shift+Z is the other redo, and matched neither branch while both+ // compared a lowercase key — a shifted `z` arrives as `Z`.+ if (e.shiftKey) redoRef.current()+ else undoRef.current()+ return+ }+ if (ctrl && e.key.toLowerCase() === 'y') { if (isInput) return; e.preventDefault(); redoRef.current(); return }if (ctrl && e.key === 'k') { e.preventDefault(); setSearchOpen(true); return }// Copy/paste (Ctrl/Cmd+C/V) handled in CanvasContainer so paste can place// nodes under the cursor / viewport center.diff --git a/frontend/src/documentation/__tests__/DocEditor.test.tsx b/frontend/src/documentation/__tests__/DocEditor.test.tsxindex 7967542..18767b4 100644--- a/frontend/src/documentation/__tests__/DocEditor.test.tsx+++ b/frontend/src/documentation/__tests__/DocEditor.test.tsx@@ -59,6 +59,97 @@ beforeEach(() => {vi.clearAllMocks()})+describe('DocEditor — undo', () => {+ const source = () => screen.getByLabelText('Document source') as HTMLTextAreaElement++ it('takes back a typed burst', async () => {+ const user = userEvent.setup()+ setupLive('start')++ await user.click(source())+ await user.keyboard(' and more')+ expect(source().value).toBe('start and more')++ await user.keyboard('{Control>}z{/Control}')+ expect(source().value).toBe('start')+ })++ it('takes back a toolbar insertion, and only that', async () => {+ const user = userEvent.setup()+ setupLive('start')++ await user.click(source())+ await user.keyboard('!')+ await user.click(screen.getByTitle('Bullet list'))+ expect(source().value).toBe('start!\n- ')++ // The insert hands focus back on the next frame; a real user pressing the+ // shortcut is long past it.+ await user.click(source())+ await user.keyboard('{Control>}z{/Control}')+ expect(source().value).toBe('start!')+ await user.keyboard('{Control>}z{/Control}')+ expect(source().value).toBe('start')+ })++ it('takes back an inserted block, which the browser could not', async () => {+ const user = userEvent.setup()+ api.block.mockResolvedValue({ data: { block: 'device-info', markdown: '| IP | 10.0.0.1 |' } } as never)+ setupLive('')++ await user.click(source())+ await user.keyboard('/')+ await user.click(await screen.findByText('/device'))+ await waitFor(() => expect(source().value).toBe('| IP | 10.0.0.1 |\n'))++ // Setting the value from code is exactly what empties the browser's own+ // undo stack, so this is the case the editor's history exists for.+ await user.click(source())+ await user.keyboard('{Control>}z{/Control}')+ expect(source().value).toBe('')+ })++ it('redoes what it took back, on either binding', async () => {+ const user = userEvent.setup()+ setupLive('start')++ await user.click(source())+ await user.keyboard('!')+ await user.keyboard('{Control>}z{/Control}')+ expect(source().value).toBe('start')++ await user.keyboard('{Control>}{Shift>}z{/Shift}{/Control}')+ expect(source().value).toBe('start!')++ await user.keyboard('{Control>}z{/Control}')+ await user.keyboard('{Control>}y{/Control}')+ expect(source().value).toBe('start!')+ })++ it('drops the redo once editing carries on down a new branch', async () => {+ const user = userEvent.setup()+ setupLive('start')++ await user.click(source())+ await user.keyboard('!')+ await user.keyboard('{Control>}z{/Control}')+ await user.click(screen.getByTitle('Bullet list'))+ await user.click(source())+ await user.keyboard('{Control>}{Shift>}z{/Shift}{/Control}')++ expect(source().value).toBe('start\n- ')+ })++ it('does nothing, and changes nothing, with no history behind it', async () => {+ const user = userEvent.setup()+ const props = setup({ body: 'start' })++ await user.click(screen.getByLabelText('Document source'))+ await user.keyboard('{Control>}z{/Control}')+ expect(props.onChange).not.toHaveBeenCalled()+ })+})+describe('DocEditor', () => {it('shows the source in an editable field', () => {setup({ body: '# NAS' })diff --git a/frontend/src/documentation/components/DocEditor.tsx b/frontend/src/documentation/components/DocEditor.tsxindex 9341651..d32aac8 100644--- a/frontend/src/documentation/components/DocEditor.tsx+++ b/frontend/src/documentation/components/DocEditor.tsx@@ -3,6 +3,7 @@ import { Bold, Italic, Link2, List, ListChecks, Save, Table, X } from 'lucide-reimport { documentsApi } from '@/api/client'import { caretPoint, placeMenu, type CaretPoint, type Placement } from '@/documentation/caret'+import { useDocHistory } from '@/documentation/history'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'import { Markdown } from '../markdown/Markdown'@@ -81,6 +82,8 @@ export function DocEditor({// needs its height, so the first paint would otherwise flash at 0,0.const [slashAt, setSlashAt] = useState<Placement | null>(null)+ const history = useDocHistory({ body, onChange, textarea })+const commands = useMemo<SlashCommand[]>(() => {const generated: SlashCommand[] = deviceId? GENERATED_BLOCKS.map((entry) => ({@@ -117,6 +120,7 @@ export function DocEditor({const start = replacing ?? el.selectionStartconst end = replacing === null ? el.selectionEnd : Math.min(replacing + 1, body.length)const next = `${body.slice(0, start)}${text}${body.slice(end)}`+ history.record('edit')onChange(next)requestAnimationFrame(() => {el.focus()@@ -124,7 +128,7 @@ export function DocEditor({el.setSelectionRange(caret, caret)})},- [body, onChange],+ [body, history, onChange],)const runCommand = useCallback(@@ -150,13 +154,14 @@ export function DocEditor({const { selectionStart: start, selectionEnd: end } = elconst selected = body.slice(start, end)const next = `${body.slice(0, start)}${before}${selected}${after}${body.slice(end)}`+ history.record('edit')onChange(next)requestAnimationFrame(() => {el.focus()el.setSelectionRange(start + before.length, end + before.length)})},- [body, onChange],+ [body, history, onChange],)const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {@@ -165,6 +170,20 @@ export function DocEditor({onSave()return}+ // The editor's own history, not the browser's: a controlled textarea loses+ // the native stack to every programmatic insertion. Always swallowed, so+ // the canvas' undo cannot fire on a document instead.+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'z') {+ event.preventDefault()+ if (event.shiftKey) history.redo()+ else history.undo()+ return+ }+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'y') {+ event.preventDefault()+ history.redo()+ return+ }if (event.key === 'Escape') {if (slashOpen) {event.preventDefault()@@ -257,7 +276,10 @@ export function DocEditor({value={body}aria-label="Document source"spellCheck={false}- onChange={(event) => onChange(event.target.value)}+ onChange={(event) => {+ history.record('type')+ onChange(event.target.value)+ }}onKeyDown={handleKeyDown}className="h-full w-full resize-none bg-transparent p-4 font-mono text-xs leading-relaxed outline-none"/>diff --git a/frontend/src/documentation/history.ts b/frontend/src/documentation/history.tsnew file mode 100644index 0000000..92fe640--- /dev/null+++ b/frontend/src/documentation/history.ts@@ -0,0 +1,110 @@+import { useCallback, useRef, type RefObject } from 'react'++/**+ * Undo for the document editor.+ *+ * The textarea is controlled and half its edits are programmatic — the toolbar+ * and the slash menu rewrite the body around the caret — and a browser drops+ * its own undo stack the moment a value is set that way. So the editor keeps+ * its own, which is the only one that can cover a `/device` insertion and a+ * typed word alike.+ */++export interface EditSnapshot {+ body: string+ selectionStart: number+ selectionEnd: number+}++/** Typing folds into the entry before it while it keeps coming this fast. */+export const COALESCE_MS = 500++/** Entries kept. Deep enough to cover a session, bounded so it cannot grow. */+export const HISTORY_LIMIT = 200++/** Typing coalesces; anything else is a step of its own. */+export type EditKind = 'type' | 'edit'++interface Options {+ body: string+ onChange: (body: string) => void+ textarea: RefObject<HTMLTextAreaElement | null>+}++export interface DocHistory {+ /** Called *before* a change, with what kind of change is about to happen. */+ record: (kind: EditKind) => void+ /** Both return false when there was nothing to move to. */+ undo: () => boolean+ redo: () => boolean+}++export function useDocHistory({ body, onChange, textarea }: Options): DocHistory {+ const past = useRef<EditSnapshot[]>([])+ const future = useRef<EditSnapshot[]>([])+ const lastAt = useRef(0)+ const lastKind = useRef<EditKind | null>(null)++ // The body comes from the props rather than a ref, so every callback below+ // is rebuilt when it changes — the handlers using them are rebuilt per render+ // anyway, and a ref read during render is not allowed.+ const snapshot = useCallback((): EditSnapshot => {+ const el = textarea.current+ return {+ body,+ selectionStart: el?.selectionStart ?? body.length,+ selectionEnd: el?.selectionEnd ?? body.length,+ }+ }, [body, textarea])++ const apply = useCallback(+ (target: EditSnapshot) => {+ onChange(target.body)+ // After the value lands, or the caret is placed in the old text.+ requestAnimationFrame(() => {+ const el = textarea.current+ if (!el) return+ el.focus()+ el.setSelectionRange(target.selectionStart, target.selectionEnd)+ })+ },+ [onChange, textarea],+ )++ const record = useCallback(+ (kind: EditKind) => {+ const now = Date.now()+ const coalesce =+ kind === 'type' && lastKind.current === 'type' && now - lastAt.current < COALESCE_MS+ lastAt.current = now+ lastKind.current = kind+ // Editing after an undo is a new branch; there is nothing to redo onto.+ future.current = []+ if (coalesce) return+ past.current = [...past.current, snapshot()].slice(-HISTORY_LIMIT)+ },+ [snapshot],+ )++ const undo = useCallback(() => {+ const previous = past.current.pop()+ if (!previous) return false+ future.current.push(snapshot())+ // The next keystroke starts a fresh burst rather than folding into the+ // entry that was just restored.+ lastKind.current = null+ apply(previous)+ return true+ }, [apply, snapshot])++ const redo = useCallback(() => {+ const next = future.current.pop()+ if (!next) return false+ past.current.push(snapshot())+ lastKind.current = null+ apply(next)+ return true+ }, [apply, snapshot])++ return { record, undo, redo }+}