Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-720]): extract shared usePopoverPosition hook

[._.]/ Adam Eivycca5d10350a8
diff --git a/client/src/components/ThemeSwitcher.jsx b/client/src/components/ThemeSwitcher.jsx
index 6406936073..e4dd7427b1 100644
--- a/client/src/components/ThemeSwitcher.jsx
+++ b/client/src/components/ThemeSwitcher.jsx
@@ -1,63 +1,24 @@
-import { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';
+import { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Check, Palette } from 'lucide-react';
import { useThemeContext } from './ThemeContext';
import { getFamilyIcon } from '../themes/familyIcons';
+import usePopoverPosition, { VIEWPORT_PADDING } from '../hooks/usePopoverPosition.js';
const MENU_WIDTH = 288;
-const MENU_GAP = 8;
-const VIEWPORT_PADDING = 8;
export default function ThemeSwitcher({ position = 'above', className = '' }) {
const { themeId, theme, themeList, setTheme } = useThemeContext();
const [open, setOpen] = useState(false);
- const [menuStyle, setMenuStyle] = useState(null);
const containerRef = useRef(null);
- const triggerRef = useRef(null);
- const menuRef = useRef(null);
-
- const updateMenuPosition = useCallback(() => {
- const trigger = triggerRef.current;
- const menu = menuRef.current;
- if (!trigger || !menu) return;
-
- const viewportWidth = window.innerWidth;
- const viewportHeight = window.innerHeight;
- const width = Math.min(MENU_WIDTH, Math.max(180, viewportWidth - VIEWPORT_PADDING * 2));
-
- // Apply width before measuring height — narrow viewports may wrap content
- // and grow the menu's height. Measuring at the wrong width produces a
- // top value that under-clamps and lets the portal overflow.
- menu.style.width = `${width}px`;
-
- const triggerRect = trigger.getBoundingClientRect();
- const menuRect = menu.getBoundingClientRect();
- const maxLeft = viewportWidth - width - VIEWPORT_PADDING;
- const left = Math.min(
- Math.max(triggerRect.right - width, VIEWPORT_PADDING),
- Math.max(VIEWPORT_PADDING, maxLeft)
- );
-
- const aboveTop = triggerRect.top - menuRect.height - MENU_GAP;
- const belowTop = triggerRect.bottom + MENU_GAP;
- const wouldOverflowTop = aboveTop < VIEWPORT_PADDING;
- const wouldOverflowBottom = belowTop + menuRect.height > viewportHeight - VIEWPORT_PADDING;
-
- let top = position === 'above'
- ? (wouldOverflowTop ? belowTop : aboveTop)
- : (wouldOverflowBottom ? aboveTop : belowTop);
-
- const maxTop = Math.max(VIEWPORT_PADDING, viewportHeight - menuRect.height - VIEWPORT_PADDING);
- top = Math.min(Math.max(top, VIEWPORT_PADDING), maxTop);
-
- setMenuStyle(prev => {
- if (prev && prev.left === `${left}px` && prev.top === `${top}px` && prev.width === `${width}px`) {
- return prev;
- }
- return { left: `${left}px`, top: `${top}px`, width: `${width}px` };
- });
- }, [position]);
-
+ const {
+ triggerRef,
+ popoverRef: menuRef,
+ style: menuStyle,
+ } = usePopoverPosition({ open, width: MENU_WIDTH, minWidth: 180, gap: 8, position });
+
+ // Close on outside-click / Escape — the popover-position hook owns placement
+ // and reflow; this component still owns its own dismiss semantics.
useEffect(() => {
if (!open) return undefined;
@@ -71,36 +32,14 @@ export default function ThemeSwitcher({ position = 'above', className = '' }) {
if (e.key === 'Escape') setOpen(false);
};
- let rafId = null;
- const onReposition = () => {
- if (rafId !== null) return;
- rafId = requestAnimationFrame(() => {
- rafId = null;
- updateMenuPosition();
- });
- };
-
document.addEventListener('mousedown', onMouseDown);
document.addEventListener('keydown', onKeyDown);
- window.addEventListener('resize', onReposition);
- window.addEventListener('scroll', onReposition, true);
return () => {
- if (rafId !== null) cancelAnimationFrame(rafId);
document.removeEventListener('mousedown', onMouseDown);
document.removeEventListener('keydown', onKeyDown);
- window.removeEventListener('resize', onReposition);
- window.removeEventListener('scroll', onReposition, true);
};
- }, [open, updateMenuPosition]);
-
- useLayoutEffect(() => {
- if (!open) {
- setMenuStyle(null);
- return;
- }
- updateMenuPosition();
- }, [open, updateMenuPosition]);
+ }, [open, menuRef]);
return (
<div ref={containerRef} className={`relative ${className}`}>
diff --git a/client/src/components/media/CollectionPickerShell.jsx b/client/src/components/media/CollectionPickerShell.jsx
index d131cb561d..3e25cd0c0a 100644
--- a/client/src/components/media/CollectionPickerShell.jsx
+++ b/client/src/components/media/CollectionPickerShell.jsx
@@ -1,8 +1,9 @@
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Plus, Search } from 'lucide-react';
import toast from '../ui/Toast';
import { listMediaCollections, createMediaCollection } from '../../services/api';
+import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';
// Shared popover shell for the two collection pickers:
//
@@ -28,7 +29,6 @@ import { listMediaCollections, createMediaCollection } from '../../services/api'
const DEFAULT_MENU_WIDTH = 260;
const MENU_GAP = 6;
-const VIEWPORT_PADDING = 8;
const SEARCH_THRESHOLD = 6;
export default function CollectionPickerShell({
@@ -57,8 +57,11 @@ export default function CollectionPickerShell({
const [query, setQuery] = useState('');
const [creating, setCreating] = useState(false);
const [newName, setNewName] = useState('');
- const [style, setStyle] = useState(null);
- const menuRef = useRef(null);
+ const {
+ popoverRef: menuRef,
+ style,
+ reposition,
+ } = usePopoverPosition({ open, width, minWidth, gap: MENU_GAP, position: 'above', anchorRef });
// Parents may pass inline arrow handlers — read through a ref so the
// event-listener effect doesn't tear down on every parent render.
@@ -101,35 +104,16 @@ export default function CollectionPickerShell({
return q ? base.filter((c) => c.name.toLowerCase().includes(q)) : base;
}, [collectionsState, query, excludeId]);
- const reposition = useCallback(() => {
- const trigger = anchorRef?.current;
- const menu = menuRef.current;
- if (!trigger || !menu) return;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- const w = Math.min(width, Math.max(minWidth, vw - VIEWPORT_PADDING * 2));
- menu.style.width = `${w}px`;
- const tr = trigger.getBoundingClientRect();
- const mr = menu.getBoundingClientRect();
- const maxLeft = vw - w - VIEWPORT_PADDING;
- const left = Math.min(Math.max(tr.right - w, VIEWPORT_PADDING), Math.max(VIEWPORT_PADDING, maxLeft));
- const above = tr.top - mr.height - MENU_GAP;
- const below = tr.bottom + MENU_GAP;
- const top = above < VIEWPORT_PADDING ? below : above;
- const maxTop = Math.max(VIEWPORT_PADDING, vh - mr.height - VIEWPORT_PADDING);
- const clampedTop = Math.min(Math.max(top, VIEWPORT_PADDING), maxTop);
- setStyle((prev) => {
- const next = { left: `${left}px`, top: `${clampedTop}px`, width: `${w}px` };
- if (prev && prev.left === next.left && prev.top === next.top && prev.width === next.width) return prev;
- return next;
- });
- }, [anchorRef, width, minWidth]);
-
- useLayoutEffect(() => {
- if (!open) { setStyle(null); return; }
+ // The popover height changes as the user filters/searches or the list loads,
+ // so re-measure on those content changes (the hook already re-flows on
+ // scroll/resize). reposition is stable while the anchor/sizing props hold.
+ useEffect(() => {
+ if (!open) return;
reposition();
}, [open, reposition, filtered, query, collectionsState]);
+ // Close on outside-click / Escape — placement and scroll/resize reflow are
+ // owned by usePopoverPosition; this effect only handles dismissal.
useEffect(() => {
if (!open) return undefined;
const close = () => onCloseRef.current?.();
@@ -139,20 +123,13 @@ export default function CollectionPickerShell({
const onMenu = menuRef.current?.contains(e.target);
if (!onTrigger && !onMenu) close();
};
- let raf = null;
- const onScroll = () => { if (raf !== null) return; raf = requestAnimationFrame(() => { raf = null; reposition(); }); };
document.addEventListener('keydown', onKey);
document.addEventListener('mousedown', onAway);
- window.addEventListener('resize', onScroll);
- window.addEventListener('scroll', onScroll, true);
return () => {
- if (raf !== null) cancelAnimationFrame(raf);
document.removeEventListener('keydown', onKey);
document.removeEventListener('mousedown', onAway);
- window.removeEventListener('resize', onScroll);
- window.removeEventListener('scroll', onScroll, true);
};
- }, [open, anchorRef, reposition]);
+ }, [open, anchorRef, menuRef]);
const updateCollections = useCallback((updater) => {
setCollectionsState((prev) => {
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index c1c9a64189..3c28a58f74 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -89,6 +89,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useKeyboardControls` | Keyboard binding for CyberCity mode toggle. | CyberCity-specific. |
| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
| `useLockToggle` | Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. |
+| `usePopoverPosition` | Viewport-clamped `{ left, top, width }` for a fixed-position portal popover anchored to a trigger; re-measures on open and rAF-coalesced on capture-phase scroll/resize. Returns `{ triggerRef, popoverRef, style, reposition }`; pass `anchorRef` to follow a parent-owned trigger. | Any portal-into-`<body>` menu/popover placed relative to a button (ThemeSwitcher, CollectionPickerShell) — use this instead of re-rolling the measure/flip/clamp/reflow plumbing. |
| `useScrollLock` | Body-scroll lock with ref-count. | Modals, drawers, lightboxes. |
| `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. |
| `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 19b93f9855..d6299ca1d7 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -23,6 +23,7 @@ export { default as useMoltworldWs } from './useMoltworldWs.js';
export { default as useMounted } from './useMounted.js';
export { default as useNextEvalCountdown } from './useNextEvalCountdown.js';
export { default as usePendingListRows } from './usePendingListRows.js';
+export { default as usePopoverPosition } from './usePopoverPosition.js';
export { default as usePreviewRoute } from './usePreviewRoute.js';
export { default as useProviderModels } from './useProviderModels.js';
export { default as useRowDraft } from './useRowDraft.js';
diff --git a/client/src/hooks/usePopoverPosition.js b/client/src/hooks/usePopoverPosition.js
new file mode 100644
index 0000000000..9a33444de6
--- /dev/null
+++ b/client/src/hooks/usePopoverPosition.js
@@ -0,0 +1,130 @@
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+
+// usePopoverPosition — shared fixed-position placement for portal popovers
+// anchored to a trigger element.
+//
+// Both ThemeSwitcher and CollectionPickerShell (and any future surface that
+// portals a menu into <body>) compute the same thing: a viewport-clamped
+// { left, top, width } for a fixed-position card that sits above-or-below a
+// trigger, re-measured on open and re-flowed (rAF-coalesced) on scroll/resize.
+// This hook owns that plumbing so callers only wire two refs and render the
+// returned style.
+//
+// Contract:
+// const { triggerRef, popoverRef, style, reposition } = usePopoverPosition({ open, ... });
+// - triggerRef → the anchor element (button) whose rect the popover follows.
+// Attach this to your trigger. If the trigger lives in a parent and you
+// already hold a ref to it, pass it as `anchorRef` and the hook follows
+// that one instead (the returned `triggerRef` then mirrors it).
+// - popoverRef → the fixed-position portal element being placed.
+// - style → { left, top, width } strings while measured, or `null` before the
+// first measurement (render with `visibility: hidden` until non-null so the
+// popover never flashes at the top-left corner pre-measure).
+// - reposition → force a re-measure (e.g. after the popover's content height
+// changes from filtering/search) without waiting for a scroll/resize event.
+//
+// Placement: `position: 'above'` prefers opening above the trigger and flips
+// below only when there isn't room above; `'below'` does the inverse. Both
+// clamp into the viewport with VIEWPORT_PADDING on every edge.
+//
+// The reflow listener uses capture-phase scroll so scrolling ANY ancestor
+// (not just window) keeps the popover attached to its trigger, and coalesces
+// bursts through requestAnimationFrame so a fast scrollwheel can't queue dozens
+// of layout reads per frame. The setter short-circuits on an unchanged
+// { left, top, width } so a capture-phase scroll that doesn't move the trigger
+// doesn't re-render every pixel.
+
+const VIEWPORT_PADDING = 8;
+
+export default function usePopoverPosition({
+ open,
+ width = 288,
+ minWidth = 180,
+ gap = 8,
+ position = 'above',
+ anchorRef = null,
+} = {}) {
+ const ownTriggerRef = useRef(null);
+ // Follow a parent-owned anchor when one is supplied; otherwise place this
+ // hook's own ref on the trigger.
+ const triggerRef = anchorRef ?? ownTriggerRef;
+ const popoverRef = useRef(null);
+ const [style, setStyle] = useState(null);
+
+ const reposition = useCallback(() => {
+ const trigger = triggerRef.current;
+ const popover = popoverRef.current;
+ if (!trigger || !popover) return;
+
+ const viewportWidth = window.innerWidth;
+ const viewportHeight = window.innerHeight;
+ const w = Math.min(width, Math.max(minWidth, viewportWidth - VIEWPORT_PADDING * 2));
+
+ // Apply width before measuring height — narrow viewports may wrap content
+ // and grow the popover's height. Measuring at the wrong width produces a
+ // top value that under-clamps and lets the portal overflow.
+ popover.style.width = `${w}px`;
+
+ const triggerRect = trigger.getBoundingClientRect();
+ const popoverRect = popover.getBoundingClientRect();
+
+ const maxLeft = viewportWidth - w - VIEWPORT_PADDING;
+ const left = Math.min(
+ Math.max(triggerRect.right - w, VIEWPORT_PADDING),
+ Math.max(VIEWPORT_PADDING, maxLeft),
+ );
+
+ const aboveTop = triggerRect.top - popoverRect.height - gap;
+ const belowTop = triggerRect.bottom + gap;
+ const wouldOverflowTop = aboveTop < VIEWPORT_PADDING;
+ const wouldOverflowBottom = belowTop + popoverRect.height > viewportHeight - VIEWPORT_PADDING;
+
+ let top = position === 'above'
+ ? (wouldOverflowTop ? belowTop : aboveTop)
+ : (wouldOverflowBottom ? aboveTop : belowTop);
+
+ const maxTop = Math.max(VIEWPORT_PADDING, viewportHeight - popoverRect.height - VIEWPORT_PADDING);
+ top = Math.min(Math.max(top, VIEWPORT_PADDING), maxTop);
+
+ setStyle((prev) => {
+ const next = { left: `${left}px`, top: `${top}px`, width: `${w}px` };
+ if (prev && prev.left === next.left && prev.top === next.top && prev.width === next.width) {
+ return prev;
+ }
+ return next;
+ });
+ }, [triggerRef, width, minWidth, gap, position]);
+
+ // Measure synchronously on open so the popover paints in place; clear on close
+ // so the next open re-measures (and renders hidden until it does).
+ useLayoutEffect(() => {
+ if (!open) {
+ setStyle(null);
+ return;
+ }
+ reposition();
+ }, [open, reposition]);
+
+ useEffect(() => {
+ if (!open) return undefined;
+ let rafId = null;
+ const onReflow = () => {
+ if (rafId !== null) return;
+ rafId = requestAnimationFrame(() => {
+ rafId = null;
+ reposition();
+ });
+ };
+ window.addEventListener('resize', onReflow);
+ window.addEventListener('scroll', onReflow, true);
+ return () => {
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ window.removeEventListener('resize', onReflow);
+ window.removeEventListener('scroll', onReflow, true);
+ };
+ }, [open, reposition]);
+
+ return { triggerRef, popoverRef, style, reposition };
+}
+
+export { VIEWPORT_PADDING };
diff --git a/client/src/hooks/usePopoverPosition.test.jsx b/client/src/hooks/usePopoverPosition.test.jsx
new file mode 100644
index 0000000000..4d9dd60cd6
--- /dev/null
+++ b/client/src/hooks/usePopoverPosition.test.jsx
@@ -0,0 +1,138 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import usePopoverPosition from './usePopoverPosition.js';
+
+// jsdom returns all-zero rects by default; stub measurements so the placement
+// math has something to clamp/flip against. We model a viewport of 1000x800.
+function stubViewport({ width = 1000, height = 800 } = {}) {
+ vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(width);
+ vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(height);
+}
+
+// Build a fake element with a fixed rect and a no-op style object so the hook's
+// `el.style.width = …` write doesn't throw.
+function fakeEl(rect) {
+ return {
+ style: {},
+ getBoundingClientRect: () => rect,
+ contains: () => false,
+ };
+}
+
+describe('usePopoverPosition', () => {
+ beforeEach(() => {
+ stubViewport();
+ // Run rAF callbacks synchronously so reflow assertions don't need timers.
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {
+ cb();
+ return 1;
+ });
+ vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('returns null style while closed and never measures', () => {
+ const { result } = renderHook(() => usePopoverPosition({ open: false }));
+ expect(result.current.style).toBeNull();
+ });
+
+ it('measures on open and returns viewport-clamped { left, top, width }', () => {
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 288, gap: 8 }));
+ // Wire trigger + popover refs to measurable fakes, then re-measure.
+ act(() => {
+ // Trigger sits mid-viewport; popover is 288x200.
+ result.current.triggerRef.current = fakeEl({ top: 400, bottom: 430, left: 500, right: 600, height: 30 });
+ result.current.popoverRef.current = fakeEl({ height: 200, width: 288 });
+ result.current.reposition();
+ });
+ const { left, top, width } = result.current.style;
+ expect(width).toBe('288px');
+ // right-align to trigger.right (600) minus width (288) = 312.
+ expect(left).toBe('312px');
+ // position 'above' (default): trigger.top(400) - height(200) - gap(8) = 192.
+ expect(top).toBe('192px');
+ });
+
+ it("flips below the trigger when 'above' would overflow the top edge", () => {
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 288, gap: 8, position: 'above' }));
+ act(() => {
+ // Trigger pinned near the top; a 200px popover above would overflow.
+ result.current.triggerRef.current = fakeEl({ top: 20, bottom: 50, left: 500, right: 600, height: 30 });
+ result.current.popoverRef.current = fakeEl({ height: 200, width: 288 });
+ result.current.reposition();
+ });
+ // Flipped below: trigger.bottom(50) + gap(8) = 58.
+ expect(result.current.style.top).toBe('58px');
+ });
+
+ it('clamps left to the viewport padding instead of going off-screen', () => {
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 288, gap: 8 }));
+ act(() => {
+ // Trigger near the left edge; right-align would push left negative.
+ result.current.triggerRef.current = fakeEl({ top: 400, bottom: 430, left: 10, right: 60, height: 30 });
+ result.current.popoverRef.current = fakeEl({ height: 200, width: 288 });
+ result.current.reposition();
+ });
+ // left = max(60 - 288, 8) = 8 (VIEWPORT_PADDING).
+ expect(result.current.style.left).toBe('8px');
+ });
+
+ it('shrinks width to fit a narrow viewport down to minWidth bound', () => {
+ stubViewport({ width: 300, height: 800 });
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 288, minWidth: 180 }));
+ act(() => {
+ result.current.triggerRef.current = fakeEl({ top: 400, bottom: 430, left: 100, right: 200, height: 30 });
+ result.current.popoverRef.current = fakeEl({ height: 200, width: 288 });
+ result.current.reposition();
+ });
+ // min(288, max(180, 300 - 16)) = min(288, 284) = 284.
+ expect(result.current.style.width).toBe('284px');
+ });
+
+ it('clears the style back to null when it closes', () => {
+ const { result, rerender } = renderHook(
+ ({ open }) => usePopoverPosition({ open, width: 288 }),
+ { initialProps: { open: true } },
+ );
+ act(() => {
+ result.current.triggerRef.current = fakeEl({ top: 400, bottom: 430, left: 500, right: 600, height: 30 });
+ result.current.popoverRef.current = fakeEl({ height: 200, width: 288 });
+ result.current.reposition();
+ });
+ expect(result.current.style).not.toBeNull();
+ act(() => rerender({ open: false }));
+ expect(result.current.style).toBeNull();
+ });
+
+ it('follows a parent-supplied anchorRef instead of its own trigger ref', () => {
+ const anchorRef = { current: fakeEl({ top: 300, bottom: 330, left: 400, right: 500, height: 30 }) };
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 200, gap: 6, anchorRef }));
+ act(() => {
+ result.current.popoverRef.current = fakeEl({ height: 100, width: 200 });
+ result.current.reposition();
+ });
+ // The hook surfaces the supplied anchor as triggerRef and places off it:
+ expect(result.current.triggerRef).toBe(anchorRef);
+ // left = max(500 - 200, 8) = 300; top (above) = 300 - 100 - 6 = 194.
+ expect(result.current.style.left).toBe('300px');
+ expect(result.current.style.top).toBe('194px');
+ });
+
+ it('re-measures on window resize while open', () => {
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 288, gap: 8 }));
+ act(() => {
+ result.current.triggerRef.current = fakeEl({ top: 400, bottom: 430, left: 500, right: 600, height: 30 });
+ result.current.popoverRef.current = fakeEl({ height: 200, width: 288 });
+ });
+ // Move the trigger near the top, then fire resize — the listener re-reads
+ // the rect, sees 'above' would overflow (100 - 200 - 8 = -108), and flips
+ // below: trigger.bottom(130) + gap(8) = 138.
+ act(() => {
+ result.current.triggerRef.current = fakeEl({ top: 100, bottom: 130, left: 500, right: 600, height: 30 });
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(result.current.style.top).toBe('138px');
+ });
+});