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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep media picker focus and dismissal inside its dialog (#9881)
Adam Eivy0e7ed6655d6a
diff --git a/client/src/components/media/CollectionPickerShell.jsx b/client/src/components/media/CollectionPickerShell.jsxindex bb1c7497b4..50019bd288 100644--- a/client/src/components/media/CollectionPickerShell.jsx+++ b/client/src/components/media/CollectionPickerShell.jsx@@ -6,7 +6,7 @@ import toast from '../ui/Toast';import { listMediaCollections, createMediaCollection } from '../../services/api';import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';import useClickOutside from '../../hooks/useClickOutside.js';-import useEscapeKey from '../../hooks/useEscapeKey.js';+import useFocusTrap from '../../hooks/useFocusTrap.js';import { applyCollectionView } from '../../lib/mediaCollectionList.js';// Shared popover shell for the list-pick-or-create pickers:@@ -115,14 +115,17 @@ export default function CollectionPickerShell({contentDeps: [collectionsState, query, excludeId],});- // Close on outside-click / Escape — placement and scroll/resize reflow are+ // Wait for placement before claiming focus; the loading state already has+ // a stable create field, so resolving the list never strands keyboard focus.+ useFocusTrap(open && Boolean(style), menuRef);++ // Close on outside-click — placement and scroll/resize reflow are// owned by usePopoverPosition. The menu is portaled to <body>, so the trigger// and the panel both have to count as "inside": that's the array form of// useClickOutside. `triggerRef` mirrors the caller's `anchorRef` when one was- // passed, so this works in either mode. Both hooks read the handler through a+ // passed, so this works in either mode. The hook reads the handler through a// ref, so the inline arrow doesn't resubscribe on every parent render.useClickOutside([triggerRef, menuRef], open, () => onClose?.());- useEscapeKey(open, () => onClose?.());// When the parent owns `collections`, mirror it into local state on each// change so the same render path works for both modes.@@ -193,15 +196,12 @@ export default function CollectionPickerShell({const list = filtered;return createPortal(- // Deliberately NOT role="menu" (see #7265): that role promises arrow-key- // roving focus among menuitem-only children, and this popover owns a search- // input, an inline create <form>, and rows that are plain toggle buttons —- // none of which are permitted menu children. role="group" + the title as- // aria-label names the popover without claiming a contract we don't keep;- // Tab reaches every control natively (same call ShellProviderLauncher made).+ // An anchored dialog owns focus while open. Keep native list/form+ // controls rather than menu semantics, which promise arrow-key navigation.<divref={menuRef}- role="group"+ role="dialog"+ aria-modal="true"aria-label={title}className="fixed bg-port-card border border-port-border rounded-lg shadow-xl z-[100] p-1.5 flex flex-col max-h-dvh-cap"style={{@@ -213,12 +213,13 @@ export default function CollectionPickerShell({visibility: style ? 'visible' : 'hidden',}}onClick={(e) => e.stopPropagation()}- // Same containment as the click handler above — a keystroke that- // reaches here already came through a focused control inside the- // popover (search input, form, toggle buttons), so it must not bubble- // to an ancestor either. Escape is excepted so `useEscapeKey`'s- // `window` listener still sees it and closes the popover.- onKeyDown={(e) => { if (e.key !== 'Escape') e.stopPropagation(); }}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === 'Escape') {+ e.preventDefault();+ onClose?.();+ }+ }}>{title && (<div className="text-[10px] text-gray-500 uppercase tracking-wide px-1 pt-1 pb-1.5 shrink-0">{title}</div>@@ -233,7 +234,6 @@ export default function CollectionPickerShell({placeholder={searchPlaceholder}aria-label={searchPlaceholder}className="w-full bg-port-bg border border-port-border rounded pl-7 pr-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent"- autoFocus/></div>)}diff --git a/client/src/components/media/MediaLightboxOrganization.test.jsx b/client/src/components/media/MediaLightboxOrganization.test.jsxnew file mode 100644index 0000000000..34dd8a9538--- /dev/null+++ b/client/src/components/media/MediaLightboxOrganization.test.jsx@@ -0,0 +1,111 @@+import { useRef, useState } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import MediaLightbox from './MediaLightbox';+import BulkTargetPicker from './BulkTargetPicker';++// Keep the actual lightbox and organization pickers together: mocking those+// children hid the portal's interaction with the viewer's focus/Escape trap.+vi.mock('./PromptRefineModal', () => ({ default: () => null }));+vi.mock('./PromptFromMedia', () => ({ PromptFromMediaModal: () => null }));+const api = vi.hoisted(() => ({+ listMediaCollections: vi.fn(), createMediaCollection: vi.fn(),+ addMediaCollectionItem: vi.fn(), removeMediaCollectionItem: vi.fn(),+ listMoodBoards: vi.fn(), createMoodBoard: vi.fn(),+ addMoodBoardItem: vi.fn(), removeMoodBoardItem: vi.fn(),+}));+vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));+const item = {+ kind: 'image', key: 'image:fixture.png', filename: 'fixture.png',+ previewUrl: '/data/images/fixture.png', downloadUrl: '/data/images/fixture.png',+};+const records = (count) => Array.from({ length: count }, (_, index) => ({+ id: `fixture-${index}`, name: `Fixture ${index}`, items: [], source: 'user',+}));++beforeEach(() => vi.clearAllMocks());++describe('lightbox organization keyboard ownership', () => {+ it.each([+ ['Add to collection', 'Collections', 0], ['Add to collection', 'Collections', 1],+ ['Add to collection', 'Collections', 6], ['Pin to mood board', 'Mood boards', 0],+ ['Pin to mood board', 'Mood boards', 1], ['Pin to mood board', 'Mood boards', 6],+ ])('%s / %s contains focus and Escape with %i records', async (triggerName, dialogName, count) => {+ api.listMediaCollections.mockResolvedValue(records(count));+ api.listMoodBoards.mockResolvedValue(records(count));+ const user = userEvent.setup();+ const onClose = vi.fn();+ render(<MediaLightbox item={item} onClose={onClose} />);+ const trigger = screen.getByRole('button', { name: triggerName });+ trigger.focus();+ await user.keyboard('{Enter}');+ const picker = await screen.findByRole('dialog', { name: dialogName });+ await waitFor(() => expect(picker.contains(document.activeElement)).toBe(true));+ if (count > 0) await within(picker).findByRole('button', { name: 'Fixture 0' });+ const controls = within(picker).getAllByRole('textbox');+ expect(controls).toHaveLength(count >= 6 ? 2 : 1);+ const first = count >= 6 ? controls[0] : count ? within(picker).getByRole('button', { name: 'Fixture 0' }) : controls[0];+ first.focus();+ await user.tab({ shift: true });+ expect(document.activeElement).toBe(controls.at(-1));+ await user.tab();+ expect(document.activeElement).toBe(first);+ await user.keyboard('{Escape}');+ expect(screen.queryByRole('dialog', { name: dialogName })).toBeNull();+ expect(onClose).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(trigger);+ await user.keyboard('{Escape}');+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(api.addMediaCollectionItem).not.toHaveBeenCalled();+ expect(api.addMoodBoardItem).not.toHaveBeenCalled();+ });++ it('keeps the loading focus target usable, then preserves row focus after a successful action', async () => {+ let resolveList;+ api.listMediaCollections.mockReturnValue(new Promise((resolve) => { resolveList = resolve; }));+ api.addMediaCollectionItem.mockResolvedValue({ ...records(1)[0], items: [{ kind: item.kind, ref: item.filename }] });+ const user = userEvent.setup();+ render(<MediaLightbox item={item} onClose={vi.fn()} />);+ await user.click(screen.getByRole('button', { name: 'Add to collection' }));+ const picker = screen.getByRole('dialog', { name: 'Collections' });+ const createField = within(picker).getByRole('textbox', { name: 'New collection name' });+ await waitFor(() => expect(document.activeElement).toBe(createField));+ await act(async () => resolveList(records(1)));+ expect(document.activeElement).toBe(createField);+ await user.tab();+ const row = within(picker).getByRole('button', { name: 'Fixture 0' });+ expect(document.activeElement).toBe(row);+ await user.keyboard('{Enter}');+ await waitFor(() => expect(row).toHaveAttribute('aria-pressed', 'true'));+ expect(document.activeElement).toBe(row);+ await user.click(screen.getByRole('button', { name: 'Pin to mood board' }));+ expect(screen.queryByRole('dialog', { name: 'Collections' })).toBeNull();+ expect(document.activeElement.closest('[role="dialog"]')).toHaveAttribute('aria-label', 'Mood boards');+ });+});++it('returns the bulk picker to its trigger after choosing a destination', async () => {+ const onPick = vi.fn();+ function BulkHost() {+ const anchorRef = useRef(null);+ const [open, setOpen] = useState(false);+ return <>+ <button ref={anchorRef} onClick={() => setOpen(true)}>Copy selected</button>+ {open && <BulkTargetPicker anchorRef={anchorRef} collections={records(1)} onClose={() => setOpen(false)}+ onPick={(...args) => { onPick(...args); setOpen(false); }} />}+ </>;+ }+ const user = userEvent.setup();+ render(<BulkHost />);+ const trigger = screen.getByRole('button', { name: 'Copy selected' });+ trigger.focus();+ await user.keyboard('{Enter}');+ const picker = screen.getByRole('dialog', { name: 'Pick a collection' });+ expect(picker.contains(document.activeElement)).toBe(true);+ await user.keyboard('{Enter}');+ expect(onPick).toHaveBeenCalledWith('fixture-0', 'Fixture 0');+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(document.activeElement).toBe(trigger);+});