Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(docs): open the insert menu at the caret, and insert where the slash is
Pouzorbf0d8077bbe9
diff --git a/frontend/src/documentation/__tests__/DocEditor.test.tsx b/frontend/src/documentation/__tests__/DocEditor.test.tsxindex 1b7e8fd..7967542 100644--- a/frontend/src/documentation/__tests__/DocEditor.test.tsx+++ b/frontend/src/documentation/__tests__/DocEditor.test.tsx@@ -1,3 +1,4 @@+import { useState } from 'react'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -11,6 +12,34 @@ vi.mock('@/api/client', () => ({const api = vi.mocked(documentsApi)+/**+ * A stateful host, so the textarea really holds what was typed.+ *+ * The plain `setup` below keeps `body` fixed and spies on `onChange`, which is+ * right for asserting what the editor asked for — but it means the `/` never+ * lands in the value, and the slash-replacement arithmetic is measured against+ * a value that does contain it.+ */+function setupLive(initial = '') {+ const onChange = vi.fn()+ function Host() {+ const [body, setBody] = useState(initial)+ return (+ <DocEditor+ body={body}+ onChange={(next) => { onChange(next); setBody(next) }}+ onSave={vi.fn()}+ onCancel={vi.fn()}+ dirty+ saving={false}+ deviceId="dev-1"+ />+ )+ }+ render(<Host />)+ return { onChange }+}+function setup(overrides: Partial<React.ComponentProps<typeof DocEditor>> = {}) {const props = {body: '',@@ -148,4 +177,31 @@ describe('DocEditor', () => {expect(screen.queryByLabelText('Insert a block')).not.toBeInTheDocument()expect(props.onCancel).not.toHaveBeenCalled()})+ // ── the slash and its query are consumed by the insert ──────────────────++ it('replaces only the slash when nothing was typed after it', async () => {+ const user = userEvent.setup()+ const { onChange } = setupLive()++ // Typed rather than seeded, so the caret is unambiguously at the end.+ await user.click(screen.getByLabelText('Document source'))+ await user.keyboard('Intro{Enter}/')+ await user.click(await screen.findByText('/task'))++ await waitFor(() => expect(onChange).toHaveBeenLastCalledWith('Intro\n- [ ] \n- [ ] \n'))+ })++ it('does not eat the text before the slash when a query was typed', async () => {+ const user = userEvent.setup()+ const { onChange } = setupLive()++ await user.click(screen.getByLabelText('Document source'))+ await user.keyboard('Intro{Enter}/')+ // The query goes into the menu's own field, never into the document — so it+ // is not part of what the insert has to remove.+ await user.type(await screen.findByLabelText('Insert a block'), 'task')+ await user.click(await screen.findByText('/task'))++ await waitFor(() => expect(onChange).toHaveBeenLastCalledWith('Intro\n- [ ] \n- [ ] \n'))+ })})diff --git a/frontend/src/documentation/__tests__/caret.test.ts b/frontend/src/documentation/__tests__/caret.test.tsnew file mode 100644index 0000000..e30de5b--- /dev/null+++ b/frontend/src/documentation/__tests__/caret.test.ts@@ -0,0 +1,76 @@+/**+ * The slash menu used to be pinned to the bottom-left of the editor pane, so it+ * opened far from the caret and ran off the screen as its list grew. These cover+ * the placement maths that replaced it; the DOM measurement it consumes is not+ * testable here, because jsdom lays nothing out and every offset it reports is 0.+ */+import { describe, it, expect } from 'vitest'+import { placeMenu, type CaretPoint } from '@/documentation/caret'++const caret = (top: number, left = 0, lineHeight = 16): CaretPoint => ({ top, left, lineHeight })++const PANE = { width: 600, height: 800 }+const MENU = { width: 288, height: 260 }++describe('placeMenu', () => {+ it('sits just under the caret when there is room', () => {+ const { top, left, flipped } = placeMenu({ caret: caret(100, 40), pane: PANE, menu: MENU })+ expect(top).toBe(120) // 100 + 16 line + 4 gap+ expect(left).toBe(40)+ expect(flipped).toBe(false)+ })++ it('follows the caret down the pane', () => {+ const high = placeMenu({ caret: caret(50), pane: PANE, menu: MENU }).top+ const low = placeMenu({ caret: caret(300), pane: PANE, menu: MENU }).top+ expect(low - high).toBe(250)+ })++ it('flips above the caret when it would run past the bottom', () => {+ // 700 + 16 + 4 + 260 = 980, well past the 800 pane.+ const { top, flipped } = placeMenu({ caret: caret(700), pane: PANE, menu: MENU })+ expect(flipped).toBe(true)+ expect(top).toBe(436) // 700 - 4 gap - 260 menu+ })++ it('stays below while it still just fits', () => {+ // 520 + 16 + 4 + 260 = exactly 800.+ const { top, flipped } = placeMenu({ caret: caret(520), pane: PANE, menu: MENU })+ expect(flipped).toBe(false)+ expect(top).toBe(540)+ })++ it('never lets the menu hang off the bottom of the pane', () => {+ for (const top of [0, 200, 500, 780, 900]) {+ const placed = placeMenu({ caret: caret(top), pane: PANE, menu: MENU })+ expect(placed.top).toBeGreaterThanOrEqual(0)+ expect(placed.top + MENU.height).toBeLessThanOrEqual(PANE.height)+ }+ })++ it('takes the roomier side and clamps when the menu fits neither', () => {+ const shortPane = { width: 600, height: 200 }+ const low = placeMenu({ caret: caret(160), pane: shortPane, menu: MENU })+ expect(low.flipped).toBe(true)+ expect(low.top).toBe(0) // clamped: 200 - 260 is negative++ const high = placeMenu({ caret: caret(10), pane: shortPane, menu: MENU })+ expect(high.flipped).toBe(false)+ expect(high.top).toBe(0)+ })++ it('pulls the menu left so it does not overflow the right edge', () => {+ const { left } = placeMenu({ caret: caret(100, 500), pane: PANE, menu: MENU })+ expect(left).toBe(312) // 600 - 288+ })++ it('never goes past the left edge', () => {+ const narrow = { width: 200, height: 800 }+ expect(placeMenu({ caret: caret(100, 150), pane: narrow, menu: MENU }).left).toBe(0)+ })++ it('honours a custom gap', () => {+ const { top } = placeMenu({ caret: caret(100), pane: PANE, menu: MENU, gap: 12 })+ expect(top).toBe(128)+ })+})diff --git a/frontend/src/documentation/caret.ts b/frontend/src/documentation/caret.tsnew file mode 100644index 0000000..28db3f5--- /dev/null+++ b/frontend/src/documentation/caret.ts@@ -0,0 +1,142 @@+/**+ * Where the caret is, in pixels, inside a `<textarea>` — and where a popup+ * anchored to it should go.+ *+ * A textarea exposes no caret geometry, so the only way to measure it is the+ * mirror trick: build a hidden div carrying the same text metrics and box, fill+ * it with the text up to the caret, and read back the position of a marker span+ * at the end of it.+ *+ * The placement maths is kept separate from the measuring so it can be tested:+ * jsdom lays nothing out, so every `offsetTop` there is 0 and a test of the+ * measurement itself would assert nothing.+ */++/** Point relative to the textarea's padding box, before scroll is applied. */+export interface CaretPoint {+ top: number+ left: number+ /** Height of one line, so a popup can clear the caret rather than cover it. */+ lineHeight: number+}++/** Every property that changes where text lands, copied onto the mirror. */+const MIRRORED = [+ 'boxSizing',+ 'width',+ 'paddingTop',+ 'paddingRight',+ 'paddingBottom',+ 'paddingLeft',+ 'borderTopWidth',+ 'borderRightWidth',+ 'borderBottomWidth',+ 'borderLeftWidth',+ 'fontFamily',+ 'fontSize',+ 'fontWeight',+ 'fontStyle',+ 'letterSpacing',+ 'lineHeight',+ 'textTransform',+ 'textIndent',+ 'whiteSpace',+ 'wordSpacing',+ 'wordBreak',+ 'tabSize',+] as const++/**+ * Measure the caret at `index`, relative to the textarea's own box.+ *+ * The textarea's scroll offset is subtracted, so the result is where the caret+ * appears on screen rather than where it sits in the full text.+ */+export function caretPoint(el: HTMLTextAreaElement, index: number): CaretPoint {+ const style = window.getComputedStyle(el)+ const mirror = document.createElement('div')++ for (const property of MIRRORED) {+ mirror.style[property] = style[property]+ }+ // A textarea wraps and preserves its whitespace; a div does neither by default.+ mirror.style.whiteSpace = 'pre-wrap'+ mirror.style.overflowWrap = 'break-word'+ mirror.style.position = 'absolute'+ mirror.style.visibility = 'hidden'+ mirror.style.top = '0'+ mirror.style.left = '-9999px'+ mirror.style.height = 'auto'++ mirror.textContent = el.value.slice(0, index)+ const marker = document.createElement('span')+ // A zero-width space keeps the span from collapsing on an empty last line,+ // which would put the marker on the previous one.+ marker.textContent = ''+ mirror.appendChild(marker)++ document.body.appendChild(mirror)+ const top = marker.offsetTop - el.scrollTop+ const left = marker.offsetLeft - el.scrollLeft+ document.body.removeChild(mirror)++ const lineHeight = parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.4 || 16++ return { top, left, lineHeight }+}++export interface Box {+ width: number+ height: number+}++export interface PlacementInput {+ caret: CaretPoint+ /** The positioned ancestor the popup is absolutely placed inside. */+ pane: Box+ menu: Box+ /** Space between the caret line and the popup. */+ gap?: number+}++export interface Placement {+ top: number+ left: number+ /** True when there was no room below and the popup sits above the caret. */+ flipped: boolean+}++/**+ * Place a popup under the caret, kept inside the pane.+ *+ * Below the caret by default. When the popup would run past the bottom it goes+ * above instead — and if it fits in neither direction (a short pane, a long+ * list) it takes whichever side has more room and is clamped there, so it is+ * never pushed off-screen the way a fixed `bottom-4` anchor was.+ */+export function placeMenu({ caret, pane, menu, gap = 4 }: PlacementInput): Placement {+ const below = caret.top + caret.lineHeight + gap+ const above = caret.top - gap - menu.height++ const roomBelow = pane.height - below+ const roomAbove = caret.top - gap++ let top: number+ let flipped: boolean+ if (menu.height <= roomBelow) {+ top = below+ flipped = false+ } else if (menu.height <= roomAbove) {+ top = above+ flipped = true+ } else {+ // Neither side fits: take the roomier one and clamp into the pane.+ flipped = roomAbove > roomBelow+ top = flipped ? above : below+ }+ top = Math.max(0, Math.min(top, Math.max(0, pane.height - menu.height)))++ const left = Math.max(0, Math.min(caret.left, Math.max(0, pane.width - menu.width)))++ return { top, left, flipped }+}diff --git a/frontend/src/documentation/components/DocEditor.tsx b/frontend/src/documentation/components/DocEditor.tsxindex 0b3af59..9341651 100644--- a/frontend/src/documentation/components/DocEditor.tsx+++ b/frontend/src/documentation/components/DocEditor.tsx@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { Bold, Italic, Link2, List, ListChecks, Save, Table, X } from 'lucide-react'import { documentsApi } from '@/api/client'+import { caretPoint, placeMenu, type CaretPoint, type Placement } from '@/documentation/caret'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'import { Markdown } from '../markdown/Markdown'@@ -66,9 +67,19 @@ export function DocEditor({devices = [],}: Props) {const textarea = useRef<HTMLTextAreaElement>(null)+ const pane = useRef<HTMLDivElement>(null)+ const caretRef = useRef<CaretPoint | null>(null)+ // Where the `/` that opened the menu sits in the body. Recorded on the way in+ // because the menu takes focus, which leaves the textarea's own selection+ // pointing wherever it happened to be when it lost focus.+ const slashIndex = useRef<number | null>(null)+ const menu = useRef<HTMLDivElement>(null)const [slashOpen, setSlashOpen] = useState(false)const [slashQuery, setSlashQuery] = useState('')const [inserting, setInserting] = useState(false)+ // Null until measured: the menu is rendered to be measured, and placing it+ // needs its height, so the first paint would otherwise flash at 0,0.+ const [slashAt, setSlashAt] = useState<Placement | null>(null)const commands = useMemo<SlashCommand[]>(() => {const generated: SlashCommand[] = deviceId@@ -90,13 +101,21 @@ export function DocEditor({return needle ? commands.filter((c) => c.label.toLowerCase().includes(needle)) : commands}, [commands, slashQuery])+ /**+ * Insert `text`, either at the live caret or over the `/` at `replacing`.+ *+ * The `/` is the only thing the menu ever put in the document — the query was+ * typed into the menu's own field — so replacing it consumes exactly that one+ * character. The index is passed in rather than read from the textarea:+ * opening the menu moves focus, which freezes the textarea's selection+ * wherever it happened to be, and every later keystroke widens the gap.+ */const insertAtCursor = useCallback(- (text: string, replaceSlash: boolean) => {+ (text: string, replacing: number | null) => {const el = textarea.currentif (!el) return- const end = el.selectionEnd- // The `/query` the user typed to open the menu is consumed by the insert.- const start = replaceSlash ? Math.max(0, end - slashQuery.length - 1) : el.selectionStart+ const start = replacing ?? el.selectionStart+ const end = replacing === null ? el.selectionEnd : Math.min(replacing + 1, body.length)const next = `${body.slice(0, start)}${text}${body.slice(end)}`onChange(next)requestAnimationFrame(() => {@@ -105,15 +124,17 @@ export function DocEditor({el.setSelectionRange(caret, caret)})},- [body, onChange, slashQuery.length],+ [body, onChange],)const runCommand = useCallback(async (command: SlashCommand) => {+ // Read before the await: closing the menu lets the reset effect run.+ const slash = slashIndex.currentsetSlashOpen(false)setInserting(true)try {- insertAtCursor(await command.insert(), true)+ insertAtCursor(await command.insert(), slash)} finally {setInserting(false)setSlashQuery('')@@ -159,6 +180,10 @@ export function DocEditor({const before = body.slice(0, el.selectionStart)// Only at the start of a line — mid-sentence a slash is just a slash.if (before === '' || before.endsWith('\n')) {+ // Measure before React re-renders: the caret is where the `/` is about+ // to land, which is where it is now.+ caretRef.current = caretPoint(el, el.selectionStart)+ slashIndex.current = el.selectionStartsetSlashOpen(true)setSlashQuery('')}@@ -166,9 +191,30 @@ export function DocEditor({}useEffect(() => {- if (!slashOpen) setSlashQuery('')+ if (!slashOpen) {+ setSlashQuery('')+ setSlashAt(null)+ slashIndex.current = null+ }}, [slashOpen])+ // Place the menu once it (and the filtered list) have a height. Re-runs as the+ // query narrows the list, so a menu that shrank stops hanging off the bottom.+ useEffect(() => {+ if (!slashOpen) return+ const caret = caretRef.current+ const paneEl = pane.current+ const menuEl = menu.current+ if (!caret || !paneEl || !menuEl) return+ setSlashAt(+ placeMenu({+ caret,+ pane: { width: paneEl.clientWidth, height: paneEl.clientHeight },+ menu: { width: menuEl.offsetWidth, height: menuEl.offsetHeight },+ }),+ )+ }, [slashOpen, visible.length])+return (<div className="flex h-full flex-col"><div className="flex items-center gap-1 border-b border-border px-3 py-1.5">@@ -178,16 +224,16 @@ export function DocEditor({<Button size="icon-xs" variant="ghost" title="Italic" onClick={() => wrapSelection('_')}><Italic /></Button>- <Button size="icon-xs" variant="ghost" title="Bullet list" onClick={() => insertAtCursor('\n- ', false)}>+ <Button size="icon-xs" variant="ghost" title="Bullet list" onClick={() => insertAtCursor('\n- ', null)}><List /></Button>- <Button size="icon-xs" variant="ghost" title="Checklist" onClick={() => insertAtCursor('\n- [ ] ', false)}>+ <Button size="icon-xs" variant="ghost" title="Checklist" onClick={() => insertAtCursor('\n- [ ] ', null)}><ListChecks /></Button>- <Button size="icon-xs" variant="ghost" title="Table" onClick={() => insertAtCursor('\n| | |\n|---|---|\n| | |\n', false)}>+ <Button size="icon-xs" variant="ghost" title="Table" onClick={() => insertAtCursor('\n| | |\n|---|---|\n| | |\n', null)}><Table /></Button>- <Button size="icon-xs" variant="ghost" title="Link to a document" onClick={() => insertAtCursor('[[doc:]]', false)}>+ <Button size="icon-xs" variant="ghost" title="Link to a document" onClick={() => insertAtCursor('[[doc:]]', null)}><Link2 /></Button><span className="ml-2 text-[10px] text-muted-foreground/70">@@ -205,7 +251,7 @@ export function DocEditor({</div><div className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-2">- <div className="relative min-h-0 border-r border-border">+ <div ref={pane} className="relative min-h-0 overflow-hidden border-r border-border"><textarearef={textarea}value={body}@@ -216,7 +262,16 @@ export function DocEditor({className="h-full w-full resize-none bg-transparent p-4 font-mono text-xs leading-relaxed outline-none"/>{slashOpen && (- <div className="absolute bottom-4 left-4 z-20 w-72 overflow-hidden rounded-lg border border-border bg-popover shadow-lg">+ <div+ ref={menu}+ style={slashAt ? { top: slashAt.top, left: slashAt.left } : undefined}+ className={cn(+ 'absolute z-20 w-72 overflow-hidden rounded-lg border border-border bg-popover shadow-lg',+ // Hidden, not unmounted, for the frame it takes to measure it —+ // placing it needs the height it only has once rendered.+ !slashAt && 'invisible',+ )}+ ><inputautoFocusvalue={slashQuery}