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

fix: keep help tooltips readable above glass cards (#9688)

Adam Eivy1c927e43c0df
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
index 64d11d79c7..133ef24927 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -108,7 +108,7 @@ export default function AppQuality({ app, detail = false }) {
<div className="min-w-0">
<h3 className="flex items-center gap-1.5 font-semibold text-white">
{label}
- <InfoTooltip label="How the quality score works" placement="below" align="start" panelClassName="w-80">
+ <InfoTooltip label="How the quality score works" placement="below" align="start" width={320}>
<p>Equal-weight mean of broad, medium/high-confidence assessments from the last 30 days. Missing, partial, low-confidence and stale assessments are excluded, not counted as perfect. Assessments describe the code before fixes.</p>
<p className="mt-1.5">Scores are the auditing agent’s evidence-based judgment, not an issue count: 90–100 no material defect · 70–89 localized debt · 40–69 significant problems · 10–39 severe defects · 0–9 pervasive failure. A run with no findings can score below 100.</p>
{federation && <p className="mt-1.5">Unified score: the newest assessment per category across this install and sync peers with the same repository. Offline peers do not contribute.</p>}
@@ -208,7 +208,7 @@ function CategoryRow({ category, below, runLink }) {
<th scope="row" className="font-medium text-left col-span-1 min-w-0 sm:table-cell sm:py-1.5 sm:px-2">
<span className="inline-flex items-center gap-1.5">
{category.label}
- {details && <InfoTooltip label={`${category.label} assessment details`} placement="below" align="start" panelClassName="w-72 max-h-64 overflow-auto font-normal">
+ {details && <InfoTooltip label={`${category.label} assessment details`} placement="below" align="start" width={288} panelClassName="font-normal">
{category.summary && <p className="break-words">{category.summary}</p>}
{category.totalFiles > 0 && <p className="mt-1">{category.scannedFiles}/{category.totalFiles} files scanned · Worst severity: {category.worstSeverity}/10</p>}
{category.id === 'better-dependency-freedom' && <p className="mt-1">Assesses whether packages earn their place; dependency count carries no automatic penalty.</p>}
diff --git a/client/src/components/apps/AppQualityHistory.jsx b/client/src/components/apps/AppQualityHistory.jsx
index edf8e752ad..803f6bd88c 100644
--- a/client/src/components/apps/AppQualityHistory.jsx
+++ b/client/src/components/apps/AppQualityHistory.jsx
@@ -37,7 +37,7 @@ export default function AppQualityHistory({ appId, categories = [] }) {
<div className="flex flex-wrap items-center justify-between gap-2">
<h4 className="flex items-center gap-1.5 text-sm font-medium">
Quality over time
- <InfoTooltip label="About quality history" placement="below" align="start" panelClassName="w-72">
+ <InfoTooltip label="About quality history" placement="below" align="start" width={288}>
Daily snapshots (UTC), higher is healthier. Scores carry forward for up to 30 days; gaps mean no fresh evidence. Coverage changes can move the overall mean. Category views include provisional assessments.
{state.data?.federation && ` Includes ${state.data.federation.available ?? 0} available full-sync peers; peer availability can change historical coverage.`}
</InfoTooltip>
diff --git a/client/src/components/ui/InfoTooltip.browser.test.js b/client/src/components/ui/InfoTooltip.browser.test.js
new file mode 100644
index 0000000000..6f618a0ffa
--- /dev/null
+++ b/client/src/components/ui/InfoTooltip.browser.test.js
@@ -0,0 +1,166 @@
+// @vitest-environment node
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { existsSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import react from '@vitejs/plugin-react';
+
+const require = createRequire(import.meta.url);
+const { chromium } = require(require.resolve('playwright-core', { paths: [
+ fileURLToPath(new URL('../../..', import.meta.url)),
+ fileURLToPath(new URL('../../../../server', import.meta.url)),
+] }));
+const chrome = [process.env.CHROME_PATH, chromium.executablePath(),
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+].find(path => path && existsSync(path));
+
+describe.skipIf(!chrome)('help above glass cards and clipped scrollers', () => {
+ let server;
+ let browser;
+ let browserTemp;
+ let origin;
+ beforeAll(async () => {
+ server = await createServer({
+ configFile: false,
+ root: fileURLToPath(new URL('../../..', import.meta.url)),
+ plugins: [react(), {
+ name: 'tooltip-browser-fixture',
+ resolveId(id) { if (id === '/tooltip-fixture.jsx') return '\0tooltip-fixture.jsx'; },
+ load(id) {
+ if (id !== '\0tooltip-fixture.jsx') return;
+ return `
+ import React from 'react';
+ import { createRoot } from 'react-dom/client';
+ import InfoTooltip from '/src/components/ui/InfoTooltip.jsx';
+ import { THEMES } from '/src/themes/portosThemes.js';
+ import '/src/index.css';
+ document.documentElement.dataset.portTheme = 'lumen-glass';
+ for (const [name, value] of Object.entries({ ...THEMES['lumen-glass'].colors, ...THEMES['lumen-glass'].tokens })) {
+ document.documentElement.style.setProperty(name, value);
+ }
+ createRoot(document.getElementById('root')).render(
+ React.createElement('main', { style: { padding: 24 } },
+ React.createElement('div', { id: 'scroller', style: { height: 210, overflow: 'auto' } },
+ React.createElement('section', { id: 'summary', className: 'bg-port-card border rounded-lg', style: { padding: 16 } },
+ 'Summary ',
+ React.createElement(InfoTooltip, { label: 'Quality help', placement: 'below', align: 'start', width: 320 },
+ Array.from({ length: 80 }, (_, i) => React.createElement('p', { key: i }, 'Synthetic help line ' + i + ': readable assessment details.'))),
+ React.createElement('button', { id: 'next', type: 'button' }, 'Next control')),
+ React.createElement('section', { id: 'history', className: 'bg-port-card border rounded-lg', style: { height: 400 } }, 'History'),
+ React.createElement('section', { className: 'bg-port-card border rounded-lg', style: { height: 200 } }, 'Categories')),
+ React.createElement('button', { id: 'outside', type: 'button' }, 'Outside'))
+ );
+ `;
+ },
+ configureServer(vite) {
+ vite.middlewares.use('/tooltip-test', async (_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(await vite.transformIndexHtml('/tooltip-test',
+ '<div id="root"></div><script type="module" src="/tooltip-fixture.jsx"></script>'));
+ });
+ },
+ }],
+ server: { host: '127.0.0.1', port: 0 },
+ });
+ await server.listen();
+ origin = server.resolvedUrls.local[0];
+ browserTemp = await mkdtemp(join(tmpdir(), 'tooltip-chrome-'));
+ browser = await chromium.launch({ executablePath: chrome, headless: true, args: ['--mute-audio'],
+ env: { ...process.env, TMPDIR: browserTemp, TMP: browserTemp, TEMP: browserTemp },
+ });
+ }, 60000);
+ afterAll(async () => {
+ try {
+ await browser?.close();
+ } finally {
+ await server?.close();
+ if (browserTemp) await rm(browserTemp, { recursive: true, force: true });
+ }
+ });
+
+ it.each([{ width: 1512, height: 824 }, { width: 756, height: 412 }, { width: 320, height: 568 }])(
+ 'keeps help readable, inside the viewport, and keyboard scrollable at $width x $height',
+ async (viewport) => {
+ const page = await browser.newPage({ viewport });
+ try {
+ await page.goto(`${origin}tooltip-test`);
+ const trigger = page.getByRole('button', { name: 'Quality help' });
+ await trigger.focus();
+ const panel = page.getByRole('tooltip');
+ await panel.waitFor();
+ expect(await page.locator('#summary').evaluate(el => getComputedStyle(el).backdropFilter)).toMatch(/blur\(/);
+ expect(await trigger.getAttribute('aria-describedby')).toBe(await panel.getAttribute('id'));
+ const geometry = await panel.evaluate(el => {
+ const r = el.getBoundingClientRect();
+ const hit = document.elementFromPoint(r.left + 20, r.top + 80);
+ return { left: r.left, right: r.right, top: r.top, bottom: r.bottom,
+ aboveCards: el.contains(hit), scrollable: el.scrollHeight > el.clientHeight,
+ scrollerBottom: document.querySelector('#scroller').getBoundingClientRect().bottom };
+ });
+ expect(geometry.left).toBeGreaterThanOrEqual(8);
+ expect(geometry.right).toBeLessThanOrEqual(viewport.width - 8);
+ expect(geometry.top).toBeGreaterThanOrEqual(8);
+ expect(geometry.bottom).toBeLessThanOrEqual(viewport.height - 8);
+ expect(geometry.bottom).toBeGreaterThan(geometry.scrollerBottom);
+ expect(geometry.aboveCards).toBe(true);
+ expect(geometry.scrollable).toBe(true);
+ expect(await panel.evaluate(el => getComputedStyle(el).backgroundColor)).not.toMatch(/rgba/);
+ await page.locator('#scroller').evaluate(el => { el.scrollTop = 10; });
+ await page.waitForFunction(() => {
+ const trigger = document.querySelector('button[aria-label="Quality help"]').getBoundingClientRect();
+ const panel = document.querySelector('[role="tooltip"]').getBoundingClientRect();
+ return Math.abs(panel.top - trigger.bottom - 6) < 1;
+ });
+ await page.keyboard.press('Tab');
+ expect(await panel.evaluate(el => el === document.activeElement)).toBe(true);
+ await page.keyboard.press('End');
+ await page.waitForFunction(() => document.querySelector('[role="tooltip"]').scrollTop > 0);
+ await page.keyboard.press('Shift+Tab');
+ expect(await trigger.evaluate(el => el === document.activeElement)).toBe(true);
+ await page.keyboard.press('Tab');
+ await page.keyboard.press('Tab');
+ expect(await page.locator('#next').evaluate(el => el === document.activeElement)).toBe(true);
+ await trigger.focus();
+ await page.keyboard.press('Tab');
+ await page.keyboard.press('Escape');
+ expect(await panel.count()).toBe(0);
+ expect(await trigger.evaluate(el => el === document.activeElement)).toBe(true);
+ expect(await trigger.getAttribute('aria-describedby')).toBeNull();
+ } finally {
+ await page.close();
+ }
+ }, 60000,
+ );
+
+ it('preserves pointer crossing, outside dismissal, and click pinning', async () => {
+ const page = await browser.newPage({ viewport: { width: 1512, height: 824 } });
+ try {
+ await page.goto(`${origin}tooltip-test`);
+ const trigger = page.getByRole('button', { name: 'Quality help' });
+ const panel = page.getByRole('tooltip');
+ await trigger.hover();
+ await panel.hover();
+ expect(await panel.isVisible()).toBe(true);
+ await page.getByRole('button', { name: 'Outside', exact: true }).hover();
+ await panel.waitFor({ state: 'detached' });
+ await trigger.click();
+ await page.getByRole('button', { name: 'Outside', exact: true }).hover();
+ await page.locator('#next').focus();
+ expect(await panel.isVisible()).toBe(true);
+ await panel.click();
+ expect(await panel.isVisible()).toBe(true);
+ await trigger.click();
+ expect(await panel.count()).toBe(0);
+ await trigger.click();
+ await page.getByRole('button', { name: 'Outside', exact: true }).click();
+ expect(await panel.count()).toBe(0);
+ } finally {
+ await page.close();
+ }
+ }, 60000);
+});
diff --git a/client/src/components/ui/InfoTooltip.jsx b/client/src/components/ui/InfoTooltip.jsx
index d057c4ba26..da48a5312a 100644
--- a/client/src/components/ui/InfoTooltip.jsx
+++ b/client/src/components/ui/InfoTooltip.jsx
@@ -1,4 +1,8 @@
-import { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { useCallback, useId, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import usePopoverPosition from '../../hooks/usePopoverPosition';
+import useCancelableDebounce from '../../hooks/useCancelableDebounce';
+import useEscapeKey from '../../hooks/useEscapeKey';
import { Info } from 'lucide-react';
import useClickOutside from '../../hooks/useClickOutside';
@@ -19,81 +23,107 @@ import useClickOutside from '../../hooks/useClickOutside';
// it survives blur. Pass `children` as the help text and `label` as the button's
// accessible name.
//
-// `placement` is which way the panel opens. It defaults to `above`, but a trigger
-// near the top of a page needs `below`: full-width routes render inside a
-// `relative overflow-hidden` <main> (see Layout.jsx), which clips a panel that
-// opens upward out of the viewport entirely.
+// Panels portal to body so glass-card stacking contexts and content scrollers
+// cannot obscure help. Placement flips and clamps to the viewport.
export default function InfoTooltip({
children,
label = 'More information',
className = '',
- panelClassName = 'w-56',
+ panelClassName = '',
+ width = 224,
iconSize = 14,
align = 'center',
placement = 'above',
}) {
- // `pinned` = a click/tap latched it open (survives blur until Escape / outside
- // click / another click). `hovering` = the transient hover-or-focus reveal.
- // The panel is visible when either is true — one derived `visible` flag.
const [pinned, setPinned] = useState(false);
const [hovering, setHovering] = useState(false);
+ const [focused, setFocused] = useState(false);
const wrapRef = useRef(null);
const panelId = useId();
- const visible = pinned || hovering;
+ const visible = pinned || hovering || focused;
+ const [scheduleClose, cancelClose] = useCancelableDebounce();
+ const { triggerRef, popoverRef, style } = usePopoverPosition({
+ open: visible, width, minWidth: 0, gap: 6, position: placement, align, constrainHeight: true,
+ contentDeps: [children, panelClassName],
+ });
const close = useCallback(() => {
+ cancelClose();
setPinned(false);
setHovering(false);
- }, []);
+ setFocused(false);
+ }, [cancelClose]);
- // Drive outside-click dismissal off `visible`, not just `pinned`: on touch a
- // tap can synthesize a sticky hover (setting `hovering`) that some mobile
- // browsers never clear with a matching mouseleave, so gating on `pinned` alone
- // could strand the panel open on the very touch path this component targets.
- useClickOutside(wrapRef, visible, close);
+ const onMouseEnter = () => {
+ cancelClose();
+ setHovering(true);
+ };
+ // A short grace period bridges the physical gap between trigger and portal.
+ const onMouseLeave = () => scheduleClose(() => setHovering(false), 150);
+ const onFocus = () => setFocused(true);
+ const onBlur = (event) => {
+ if (wrapRef.current?.contains(event.relatedTarget)
+ || popoverRef.current?.contains(event.relatedTarget)) return;
+ setFocused(false);
+ };
- useEffect(() => {
- if (!visible) return undefined;
- const onKey = (e) => {
- if (e.key === 'Escape') close();
- };
- document.addEventListener('keydown', onKey);
- return () => document.removeEventListener('keydown', onKey);
- }, [visible, close]);
+ useClickOutside([wrapRef, popoverRef], visible, close);
- const alignClass = align === 'start'
- ? 'left-0'
- : align === 'end'
- ? 'right-0'
- : 'left-1/2 -translate-x-1/2';
- const placementClass = placement === 'below' ? 'top-full mt-1.5' : 'bottom-full mb-1.5';
+ useEscapeKey(visible, () => {
+ // Return keyboard scroll focus before removing the portal.
+ if (popoverRef.current?.contains(document.activeElement)) triggerRef.current?.focus();
+ close();
+ });
return (
<div
ref={wrapRef}
className={`relative inline-flex ${className}`}
- onMouseEnter={() => setHovering(true)}
- onMouseLeave={() => setHovering(false)}
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
>
<button
+ ref={triggerRef}
type="button"
aria-label={label}
aria-describedby={visible ? panelId : undefined}
- onClick={() => setPinned((v) => !v)}
- onFocus={() => setHovering(true)}
- onBlur={() => setHovering(false)}
+ onClick={() => { if (pinned) close(); else setPinned(true); }}
+ onKeyDown={(event) => {
+ const panel = popoverRef.current;
+ if (event.key === 'Tab' && !event.shiftKey && panel?.scrollHeight > panel?.clientHeight) {
+ event.preventDefault();
+ panel.focus();
+ }
+ }}
+ onFocus={onFocus}
+ onBlur={onBlur}
className="inline-flex shrink-0 items-center justify-center min-h-[44px] min-w-[44px] -my-[15px] rounded text-gray-500 transition-colors hover:text-gray-300 focus:text-gray-300 focus:outline-none focus-visible:ring-1 focus-visible:ring-port-accent"
>
<Info size={iconSize} aria-hidden="true" />
</button>
- {visible && (
+ {visible && createPortal(
<div
+ ref={popoverRef}
id={panelId}
role="tooltip"
- className={`port-opaque-surface absolute ${placementClass} ${alignClass} z-50 rounded-lg border border-port-border bg-gray-800 px-3 py-2 text-xs text-gray-300 shadow-lg ${panelClassName}`}
+ tabIndex={0}
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ onKeyDown={(event) => {
+ if (event.key === 'Tab') {
+ // Continue from the trigger's place in the caller's tab order.
+ triggerRef.current?.focus();
+ if (event.shiftKey) event.preventDefault();
+ }
+ }}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ style={{ ...style, visibility: style ? undefined : 'hidden' }}
+ className={`port-opaque-surface fixed z-[100] overflow-y-auto rounded-lg border border-port-border px-3 py-2 text-xs text-gray-300 shadow-lg ${panelClassName}`}
>
{children}
- </div>
+ </div>,
+ document.body,
)}
</div>
);
diff --git a/client/src/components/ui/InfoTooltip.test.jsx b/client/src/components/ui/InfoTooltip.test.jsx
index 0268de9930..3fe77f736c 100644
--- a/client/src/components/ui/InfoTooltip.test.jsx
+++ b/client/src/components/ui/InfoTooltip.test.jsx
@@ -1,5 +1,5 @@
-import { describe, it, expect } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent, act } from '@testing-library/react';
import InfoTooltip from './InfoTooltip';
@@ -28,18 +28,46 @@ describe('InfoTooltip', () => {
expect(screen.queryByRole('tooltip')).toBeNull();
});
- // A trigger near the top of a full-width route sits inside an
- // `overflow-hidden` <main>, which clips an upward-opening panel out of view.
- it('opens downward when placement is below, upward by default', () => {
- const { unmount } = render(<InfoTooltip label="help" placement="below">Down</InfoTooltip>);
- fireEvent.focus(screen.getByRole('button', { name: 'help' }));
- expect(screen.getByRole('tooltip').className).toContain('top-full');
- expect(screen.getByRole('tooltip').className).not.toContain('bottom-full');
- unmount();
+ it('portals the panel outside caller clipping and keeps panel clicks and focus inside', () => {
+ const { container } = render(<InfoTooltip label="help" width={320} align="start">Portal help</InfoTooltip>);
+ const btn = screen.getByRole('button', { name: 'help' });
+ fireEvent.focus(btn);
+ const panel = screen.getByRole('tooltip');
+ expect(panel.parentElement).toBe(document.body);
+ expect(container.contains(panel)).toBe(false);
+ expect(panel.style.width).toBe('320px');
+ fireEvent.blur(btn, { relatedTarget: panel });
+ fireEvent.focus(panel);
+ fireEvent.mouseDown(panel);
+ expect(screen.getByRole('tooltip')).toBe(panel);
+ fireEvent.blur(panel);
+ expect(screen.queryByRole('tooltip')).toBeNull();
+ });
- render(<InfoTooltip label="help">Up</InfoTooltip>);
- fireEvent.focus(screen.getByRole('button', { name: 'help' }));
- expect(screen.getByRole('tooltip').className).toContain('bottom-full');
+ it('bridges hover to the portal with a cancellable delay, while focused help stays open', () => {
+ vi.useFakeTimers();
+ try {
+ render(<InfoTooltip label="help">Hover bridge</InfoTooltip>);
+ const btn = screen.getByRole('button', { name: 'help' });
+ const wrap = btn.parentElement;
+ fireEvent.mouseEnter(wrap);
+ const panel = screen.getByRole('tooltip');
+ fireEvent.mouseLeave(wrap);
+ act(() => vi.advanceTimersByTime(100));
+ fireEvent.mouseEnter(panel);
+ act(() => vi.advanceTimersByTime(200));
+ expect(screen.getByRole('tooltip')).toBe(panel);
+ fireEvent.mouseLeave(panel);
+ act(() => vi.advanceTimersByTime(150));
+ expect(screen.queryByRole('tooltip')).toBeNull();
+ fireEvent.focus(btn);
+ fireEvent.mouseEnter(wrap);
+ fireEvent.mouseLeave(wrap);
+ act(() => vi.advanceTimersByTime(150));
+ expect(screen.getByRole('tooltip')).toBeTruthy();
+ } finally {
+ vi.useRealTimers();
+ }
});
it('keeps a 44px minimum, non-shrinking hit area on the trigger button', () => {
@@ -64,6 +92,8 @@ describe('InfoTooltip', () => {
it('closes on a second click (toggle) without stranding the panel visible', () => {
render(<InfoTooltip label="help">Toggles</InfoTooltip>);
const btn = screen.getByRole('button', { name: 'help' });
+ fireEvent.focus(btn);
+ fireEvent.mouseEnter(btn.parentElement);
fireEvent.click(btn);
expect(screen.getByRole('tooltip')).toBeTruthy();
fireEvent.click(btn);
diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.md
index e775eb8fb3..a119838b48 100644
--- a/client/src/components/ui/README.md
+++ b/client/src/components/ui/README.md
@@ -23,7 +23,7 @@ accessibility). Feature-specific components live under their own feature directo
| `HunkDiff` | Hunked side-by-side diff for long texts, with unchanged runs collapsed. |
| `ImageThumb` | List-card thumbnail with an icon fallback when the ref is missing or 404s. |
| `InfiniteScrollFooter` | Shared scroll sentinel with loading, retry, end state and accessible manual Load more; pair with `usePagedCollection`. |
-| `InfoTooltip` | Focusable info/help tooltip — hover, keyboard focus, or tap; Esc to dismiss. |
+| `InfoTooltip` | Focusable info/help tooltip — hover, keyboard focus, or tap; opaque body portal with viewport-clamped numeric `width` (default 224), start/center/end alignment, keyboard scrolling, and Esc dismissal. |
| `InlineConfirmRow` | Inline "question + confirm + cancel" row — PortOS's preferred alternative to `window.confirm`. |
| `InlineDiff` | Stacked word-level diff — old row (red removals) over new row (green additions). |
| `Kbd` | Keycap for rendering a keyboard key in help/cheatsheet UI. |
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 6eb27729c0..92d986591e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -143,7 +143,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useLiveSuggest` | Post-typing debounce for an imperative panel trigger: `{ registerTrigger, scheduleSuggest }` re-arms one `debounceMs` timer per keystroke and fires the registered fn only while `enabled` and still mounted. | An editor that asks a sibling AI panel to suggest once the writer pauses (WorkEditor ↔ LiveContinuationPanel). |
| `useLockToggle` | Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. |
| `usePersistedOptions` | Registry for "saved default + per-run override" form options: one spec row per option (`{ defaultValue, read, clamp, persistOnEdit }`) owns the state, per-field dirty flag, hydrate-if-untouched pass and edited-only override collection. Returns `{ values, edit, hydrate, collectOverrides, inputProps }`, all identity-stable and ref-backed so a caller's `useCallback` needs one dep instead of one per option. | Any panel where each option must load a saved default, persist edits, and send ONLY edited fields as per-run overrides (AutopilotPanel) — use this instead of hand-copying the state/editedRef/hydrate/collect scaffold per option. |
-| `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. |
+| `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 and `align` for start/center/end (default end); opt into `constrainHeight` to cap scrollable help to the roomier side of its 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. |
| `useSidebarResize` | Drag-to-resize split-pane width persisted to `localStorage`; returns `{ containerRef, width, maxWidth, onMouseDown, reset }` and caps the drag at `maxFraction` of the measured container. | A desktop sidebar/split pane with a draggable divider (WorkEditor's storyboard sidebar). |
| `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. |
diff --git a/client/src/hooks/usePopoverPosition.js b/client/src/hooks/usePopoverPosition.js
index e0e75108f2..07da6e2dc6 100644
--- a/client/src/hooks/usePopoverPosition.js
+++ b/client/src/hooks/usePopoverPosition.js
@@ -32,6 +32,9 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react
// 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.
+// Horizontal alignment is 'start', 'center', or 'end' (the compatible default).
+// Opt into `constrainHeight` for scrollable help: cap to the chosen side's
+// available height, choosing the roomier side when the preferred side is too short.
//
// The reflow listener uses capture-phase scroll so scrolling ANY ancestor
// (not just window) keeps the popover attached to its trigger, and coalesces
@@ -48,6 +51,8 @@ export default function usePopoverPosition({
minWidth = 180,
gap = 8,
position = 'above',
+ align = 'end',
+ constrainHeight = false,
anchorRef = null,
contentDeps = [],
} = {}) {
@@ -73,11 +78,29 @@ export default function usePopoverPosition({
popover.style.width = `${w}px`;
const triggerRect = trigger.getBoundingClientRect();
+ let effectivePosition = position;
+ let maxHeight;
+ if (constrainHeight) {
+ const aboveSpace = Math.max(0, triggerRect.top - gap - VIEWPORT_PADDING);
+ const belowSpace = Math.max(0, viewportHeight - triggerRect.bottom - gap - VIEWPORT_PADDING);
+ // Measure natural height at the clamped width before choosing a side.
+ popover.style.maxHeight = `${Math.max(0, viewportHeight - VIEWPORT_PADDING * 2)}px`;
+ const height = popover.getBoundingClientRect().height;
+ const preferredSpace = position === 'above' ? aboveSpace : belowSpace;
+ if (height > preferredSpace) effectivePosition = aboveSpace > belowSpace ? 'above' : 'below';
+ maxHeight = `${effectivePosition === 'above' ? aboveSpace : belowSpace}px`;
+ popover.style.maxHeight = maxHeight;
+ }
const popoverRect = popover.getBoundingClientRect();
const maxLeft = viewportWidth - w - VIEWPORT_PADDING;
+ const alignedLeft = align === 'start'
+ ? triggerRect.left
+ : align === 'center'
+ ? (triggerRect.left + triggerRect.right - w) / 2
+ : triggerRect.right - w;
const left = Math.min(
- Math.max(triggerRect.right - w, VIEWPORT_PADDING),
+ Math.max(alignedLeft, VIEWPORT_PADDING),
Math.max(VIEWPORT_PADDING, maxLeft),
);
@@ -86,7 +109,7 @@ export default function usePopoverPosition({
const wouldOverflowTop = aboveTop < VIEWPORT_PADDING;
const wouldOverflowBottom = belowTop + popoverRect.height > viewportHeight - VIEWPORT_PADDING;
- let top = position === 'above'
+ let top = effectivePosition === 'above'
? (wouldOverflowTop ? belowTop : aboveTop)
: (wouldOverflowBottom ? aboveTop : belowTop);
@@ -94,13 +117,13 @@ export default function usePopoverPosition({
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) {
+ const next = { left: `${left}px`, top: `${top}px`, width: `${w}px`, ...(constrainHeight ? { maxHeight } : {}) };
+ if (prev && prev.left === next.left && prev.top === next.top && prev.width === next.width && prev.maxHeight === next.maxHeight) {
return prev;
}
return next;
});
- }, [triggerRef, width, minWidth, gap, position]);
+ }, [triggerRef, width, minWidth, gap, position, align, constrainHeight]);
// Measure synchronously on open (and on any content-height change) so the
// popover paints in place; clear on close so the next open re-measures (and
diff --git a/client/src/hooks/usePopoverPosition.test.jsx b/client/src/hooks/usePopoverPosition.test.jsx
index 1ccb32af62..0ea26073a1 100644
--- a/client/src/hooks/usePopoverPosition.test.jsx
+++ b/client/src/hooks/usePopoverPosition.test.jsx
@@ -55,6 +55,31 @@ describe('usePopoverPosition', () => {
expect(top).toBe('192px');
});
+ it.each([['start', '500px'], ['center', '406px'], ['end', '312px']])(
+ 'honors %s horizontal alignment without changing placement',
+ (align, left) => {
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 288, align }));
+ act(() => {
+ result.current.triggerRef.current = fakeEl({ top: 400, bottom: 430, left: 500, right: 600 });
+ result.current.popoverRef.current = fakeEl({ height: 200 });
+ result.current.reposition();
+ });
+ expect(result.current.style).toEqual({ left, top: '192px', width: '288px' });
+ },
+ );
+
+ it('optionally limits tall help to the roomier side without covering its trigger', () => {
+ const { result } = renderHook(() => usePopoverPosition({ open: true, width: 288, position: 'below', constrainHeight: true }));
+ const popover = fakeEl({ height: 700 });
+ popover.getBoundingClientRect = () => ({ height: Math.min(700, parseFloat(popover.style.maxHeight) || 700) });
+ act(() => {
+ result.current.triggerRef.current = fakeEl({ top: 650, bottom: 680, left: 500, right: 600 });
+ result.current.popoverRef.current = popover;
+ result.current.reposition();
+ });
+ expect(result.current.style).toEqual({ left: '312px', top: '8px', width: '288px', maxHeight: '634px' });
+ });
+
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(() => {
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index b054a31a68..d8a40342b5 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -183,7 +183,7 @@ function PortosShellView() {
which is most of this page's audience. Costs no vertical space, and
sits outside the `font-mono` span so the prose isn't monospaced.
Opens downward: this row is at the top of a clipped full-width main. */}
- <InfoTooltip label="About live TUI runs" align="end" placement="below" panelClassName="w-60">
+ <InfoTooltip label="About live TUI runs" align="end" placement="below" width={240}>
{liveRunCount} live TUI run{liveRunCount > 1 ? 's' : ''}. Open one to watch it — you can type to
answer or correct it, or Stop to end it. It won't idle-close while you have it open.
</InfoTooltip>