Skip to content

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

fix(docs): stop the template menu opening under the sidebar

Pouzorcf18521032c1
diff --git a/frontend/src/documentation/__tests__/NewDocMenu.test.tsx b/frontend/src/documentation/__tests__/NewDocMenu.test.tsx
new file mode 100644
index 0000000..6544699
--- /dev/null
+++ b/frontend/src/documentation/__tests__/NewDocMenu.test.tsx
@@ -0,0 +1,108 @@
+/**
+ * The template picker opens from a button at the right edge of a narrow,
+ * scrolling, resizable column. It used to be absolutely positioned inside that
+ * column, where it was clipped by the scroll container and painted under the
+ * app sidebar; it is portalled to the body now, so what these pin is that it
+ * leaves the column and stays inside the viewport.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen } from '@testing-library/react'
+
+import { NewDocMenu } from '../components/NewDocMenu'
+
+function open(placement: 'up' | 'down' = 'down', onCreate = vi.fn()) {
+ const view = render(
+ <div style={{ overflow: 'auto', width: 260 }}>
+ <NewDocMenu placement={placement} onCreate={onCreate} trigger={<button>New</button>} />
+ </div>,
+ )
+ fireEvent.click(screen.getByText('New'))
+ return { ...view, onCreate }
+}
+
+afterEach(() => vi.restoreAllMocks())
+
+describe('NewDocMenu', () => {
+ it('opens on the trigger and lists every template', () => {
+ open()
+ expect(screen.getByRole('menu')).toBeTruthy()
+ expect(screen.getByText('Runbook')).toBeTruthy()
+ expect(screen.getByText('Decision (ADR)')).toBeTruthy()
+ })
+
+ it('renders outside the scrolling column that would clip it', () => {
+ const { container } = open()
+ // Portalled: the menu is in the body, not under the component's own tree.
+ expect(container.querySelector('[role="menu"]')).toBeNull()
+ expect(document.body.querySelector('[role="menu"]')).toBeTruthy()
+ })
+
+ it('keeps its left edge inside the viewport', () => {
+ open()
+ const menu = screen.getByRole('menu') as HTMLElement
+ // Tailwind's `fixed` is a class, and jsdom loads no stylesheet to resolve it.
+ expect(menu.className).toContain('fixed')
+ expect(parseFloat(menu.style.left)).toBeGreaterThanOrEqual(0)
+ })
+
+ it('hangs below the trigger when it opens downwards', () => {
+ open('down')
+ const menu = screen.getByRole('menu') as HTMLElement
+ expect(menu.style.top).not.toBe('')
+ expect(menu.style.bottom).toBe('')
+ })
+
+ it('sits above the trigger when it opens upwards', () => {
+ open('up')
+ const menu = screen.getByRole('menu') as HTMLElement
+ expect(menu.style.bottom).not.toBe('')
+ expect(menu.style.top).toBe('')
+ })
+
+ it('closes on Escape', () => {
+ open()
+ fireEvent.keyDown(document, { key: 'Escape' })
+ expect(screen.queryByRole('menu')).toBeNull()
+ })
+
+ it('closes on a click outside itself', () => {
+ open()
+ fireEvent.mouseDown(document.body)
+ expect(screen.queryByRole('menu')).toBeNull()
+ })
+
+ it('stays open while the click is inside it', () => {
+ open()
+ fireEvent.mouseDown(screen.getByText('Runbook'))
+ expect(screen.queryByRole('menu')).toBeTruthy()
+ })
+
+ it('closes rather than floating away when the page scrolls', () => {
+ open()
+ fireEvent.scroll(document, {})
+ expect(screen.queryByRole('menu')).toBeNull()
+ })
+
+ it('creates from the picked template with the typed title', async () => {
+ vi.spyOn(window, 'prompt').mockReturnValue(' Switch upgrade ')
+ const { onCreate } = open()
+
+ fireEvent.click(screen.getByText('Runbook'))
+
+ expect(onCreate).toHaveBeenCalledWith({
+ title: 'Switch upgrade',
+ templateId: 'runbook',
+ parentId: undefined,
+ })
+ expect(screen.queryByRole('menu')).toBeNull()
+ })
+
+ it('creates nothing when the title is cancelled or blank', () => {
+ vi.spyOn(window, 'prompt').mockReturnValue(' ')
+ const { onCreate } = open()
+
+ fireEvent.click(screen.getByText('Blank page'))
+
+ expect(onCreate).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/documentation/components/NewDocMenu.tsx b/frontend/src/documentation/components/NewDocMenu.tsx
index a99aed0..4bea11f 100644
--- a/frontend/src/documentation/components/NewDocMenu.tsx
+++ b/frontend/src/documentation/components/NewDocMenu.tsx
@@ -1,4 +1,5 @@
-import { useEffect, useRef, useState, type ReactNode } from 'react'
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
+import { createPortal } from 'react-dom'
import { cn } from '@/lib/utils'
@@ -6,7 +7,7 @@ import { DOC_TEMPLATES } from '../types'
interface Props {
trigger: ReactNode
- /** Which way the popover opens. The menu sits at the top of the pane now. */
+ /** Which way the popover opens from the trigger. */
placement?: 'up' | 'down'
parentId?: string | null
onCreate: (input: { title: string; templateId: string; parentId?: string | null }) => void | Promise<void>
@@ -18,55 +19,108 @@ interface Props {
* A plain popover rather than a shadcn dropdown: the project only ships a
* handful of primitives and this needs no focus trapping beyond closing on an
* outside click or Escape.
+ *
+ * It is **portalled to the body and positioned in viewport coordinates**. The
+ * trigger sits at the right edge of the document tree, which is a narrow,
+ * resizable, vertically scrolling column: an absolutely positioned menu wider
+ * than the space to its left escaped that column, where it was both clipped by
+ * the scroll container and painted under the app sidebar. Out of the column
+ * there is nothing to clip it, and the left edge is clamped to the viewport so
+ * a narrow tree cannot push it off screen.
*/
+
+/** Matches `w-64` below; the clamp needs the width before the menu is drawn. */
+const MENU_WIDTH = 256
+const MARGIN = 8
+const GAP = 4
+
export function NewDocMenu({ trigger, placement = 'up', parentId, onCreate }: Props) {
const [open, setOpen] = useState(false)
- const root = useRef<HTMLDivElement>(null)
+ const [at, setAt] = useState<{ left: number; top?: number; bottom?: number } | null>(null)
+ const anchor = useRef<HTMLDivElement>(null)
+ const menu = useRef<HTMLDivElement>(null)
+
+ const place = useCallback(() => {
+ const rect = anchor.current?.getBoundingClientRect()
+ if (!rect) return
+ setAt({
+ // Right-aligned on the trigger, then pulled back inside the viewport.
+ left: Math.min(
+ Math.max(rect.right - MENU_WIDTH, MARGIN),
+ Math.max(window.innerWidth - MENU_WIDTH - MARGIN, MARGIN),
+ ),
+ ...(placement === 'down'
+ ? { top: rect.bottom + GAP }
+ : { bottom: window.innerHeight - rect.top + GAP }),
+ })
+ }, [placement])
useEffect(() => {
if (!open) return
const onDown = (event: MouseEvent) => {
- if (!root.current?.contains(event.target as Node)) setOpen(false)
+ const target = event.target as Node
+ // The menu is no longer a descendant of the trigger, so both are checked.
+ if (!anchor.current?.contains(target) && !menu.current?.contains(target)) setOpen(false)
}
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') setOpen(false)
}
+ // Fixed coordinates go stale the moment anything moves underneath them;
+ // closing is honest, and cheaper than following the trigger around.
+ const onMove = () => setOpen(false)
document.addEventListener('mousedown', onDown)
document.addEventListener('keydown', onKey)
+ window.addEventListener('resize', onMove)
+ window.addEventListener('scroll', onMove, true)
return () => {
document.removeEventListener('mousedown', onDown)
document.removeEventListener('keydown', onKey)
+ window.removeEventListener('resize', onMove)
+ window.removeEventListener('scroll', onMove, true)
}
}, [open])
return (
- <div ref={root} className="relative">
- <div onClick={() => setOpen((value) => !value)}>{trigger}</div>
- {open && (
- <div
- className={cn(
- 'absolute z-30 w-64 overflow-hidden rounded-lg border border-border bg-popover shadow-lg',
- placement === 'up' ? 'bottom-full left-0 mb-1' : 'right-0 top-full mt-1',
- )}
- >
- {DOC_TEMPLATES.map((template) => (
- <button
- key={template.id}
- type="button"
- onClick={async () => {
- setOpen(false)
- const title = window.prompt('Document title', template.label)
- if (!title?.trim()) return
- await onCreate({ title: title.trim(), templateId: template.id, parentId })
- }}
- className="flex w-full cursor-pointer flex-col items-start px-3 py-1.5 text-left hover:bg-muted"
- >
- <span className="text-xs">{template.label}</span>
- <span className="text-[10px] text-muted-foreground">{template.hint}</span>
- </button>
- ))}
- </div>
- )}
+ <div ref={anchor} className="relative">
+ <div
+ onClick={() => {
+ place()
+ setOpen((value) => !value)
+ }}
+ >
+ {trigger}
+ </div>
+ {open &&
+ at &&
+ createPortal(
+ <div
+ ref={menu}
+ role="menu"
+ style={{ left: at.left, top: at.top, bottom: at.bottom }}
+ className={cn(
+ 'fixed z-50 w-64 overflow-hidden rounded-lg border border-border bg-popover shadow-lg',
+ )}
+ >
+ {DOC_TEMPLATES.map((template) => (
+ <button
+ key={template.id}
+ type="button"
+ role="menuitem"
+ onClick={async () => {
+ setOpen(false)
+ const title = window.prompt('Document title', template.label)
+ if (!title?.trim()) return
+ await onCreate({ title: title.trim(), templateId: template.id, parentId })
+ }}
+ className="flex w-full cursor-pointer flex-col items-start px-3 py-1.5 text-left hover:bg-muted"
+ >
+ <span className="text-xs">{template.label}</span>
+ <span className="text-[10px] text-muted-foreground">{template.hint}</span>
+ </button>
+ ))}
+ </div>,
+ document.body,
+ )}
</div>
)
}