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: give useKeyCapture the dialog guard instead of inlining it per call site (#4731)

[._.]/ Adam Eivy7fd14fde4868
diff --git a/client/src/components/RapidReader.jsx b/client/src/components/RapidReader.jsx
index fb4bb054e2..5f49c7184f 100644
--- a/client/src/components/RapidReader.jsx
+++ b/client/src/components/RapidReader.jsx
@@ -54,6 +54,7 @@ export default function RapidReader({
focalColor = '#ef4444',
autoPlay = false,
compact = false,
+ inDialog = false,
onClose,
onComplete
}) {
@@ -104,6 +105,7 @@ export default function RapidReader({
// listener (notably VoiceWidget's hotkey, which also binds Space); keys we
// do not handle pass through untouched.
useKeyCapture({
+ enabledInDialog: inDialog,
onKeyDown: (e) => {
if (e.key === ' ') setPlaying((p) => !p);
else if (e.key === 'ArrowLeft') setIdx((i) => Math.max(0, i - 1));
@@ -293,14 +295,10 @@ function FocalSlot({ chunk, focalColor }) {
}
// Modal wrapper — full-screen overlay so any page can pop the reader without
-// leaving its context. Closes on Esc or backdrop click. The inner RapidReader
-// uses useKeyCapture, a capture-phase window keydown listener (so Space / arrow
-// keys can be claimed before VoiceWidget sees them) that, on Esc, calls onClose
-// and then preventDefault() + stopImmediatePropagation(). Modal's window
-// listener is bubble-phase, so it never even reaches the same event — the
-// capture-phase stopImmediatePropagation cancels propagation entirely; even
-// if it did reach Modal, `defaultPrevented` would suppress the close
-// dispatch. RapidReader owns Esc unilaterally inside this wrapper.
+// leaving its context. `inDialog` is what lets the reader keep its keys in here:
+// its useKeyCapture claim otherwise stands down while an aria-modal layer is open,
+// and Modal IS that layer. The claim runs in the capture phase, so Esc reaches
+// onClose and never Modal's own bubble-phase close — the reader owns Esc here.
export function RapidReaderModal({ open, text, title, onClose, ...readerProps }) {
return (
<Modal
@@ -324,7 +322,7 @@ export function RapidReaderModal({ open, text, title, onClose, ...readerProps })
<X size={18} />
</button>
</div>
- <RapidReader text={text} onClose={onClose} autoPlay {...readerProps} />
+ <RapidReader text={text} onClose={onClose} autoPlay inDialog {...readerProps} />
</Modal>
);
}
diff --git a/client/src/components/RapidReader.test.jsx b/client/src/components/RapidReader.test.jsx
index 69ddea8179..731f3bddd1 100644
--- a/client/src/components/RapidReader.test.jsx
+++ b/client/src/components/RapidReader.test.jsx
@@ -1,21 +1,10 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, act } from '@testing-library/react';
-import RapidReader from './RapidReader';
+import { installVoiceHotkeySpy } from '../test/voiceHotkeySpy';
+import RapidReader, { RapidReaderModal } from './RapidReader';
describe('RapidReader keyboard transport', () => {
- // Stands in for VoiceWidget's app-global push-to-talk hotkey, which binds the same
- // Space on `window` in the bubble phase. The reader claims its keys in the capture
- // phase, so a handled key must never reach this spy.
- let voiceHotkey;
-
- beforeEach(() => {
- voiceHotkey = vi.fn();
- window.addEventListener('keydown', voiceHotkey);
- });
-
- afterEach(() => {
- window.removeEventListener('keydown', voiceHotkey);
- });
+ const voiceHotkey = installVoiceHotkeySpy();
const renderReader = (props = {}) => render(
<RapidReader text="alpha bravo charlie delta" chunkSize={1} {...props} />,
@@ -28,7 +17,7 @@ describe('RapidReader keyboard transport', () => {
act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
expect(screen.getByLabelText('Pause')).toBeInTheDocument();
- expect(voiceHotkey).not.toHaveBeenCalled();
+ expect(voiceHotkey()).not.toHaveBeenCalled();
});
it('claims Escape for its own close handler', () => {
@@ -38,30 +27,12 @@ describe('RapidReader keyboard transport', () => {
act(() => { fireEvent.keyDown(document.body, { key: 'Escape' }); });
expect(onClose).toHaveBeenCalledTimes(1);
- expect(voiceHotkey).not.toHaveBeenCalled();
- });
-
- it('lets unhandled keys through to app-global listeners', () => {
- renderReader();
-
- act(() => { fireEvent.keyDown(document.body, { key: 'j' }); });
-
- expect(voiceHotkey).toHaveBeenCalledTimes(1);
- });
-
- it('ignores keys typed into a text field', () => {
- const { container } = renderReader();
- const input = document.createElement('input');
- container.appendChild(input);
-
- act(() => { fireEvent.keyDown(input, { key: ' ', code: 'Space' }); });
-
- expect(screen.getByLabelText('Play')).toBeInTheDocument();
+ expect(voiceHotkey()).not.toHaveBeenCalled();
});
it('ignores Space aimed at a <select>, where it natively opens the dropdown', () => {
// The old hand-rolled guard only knew INPUT/TEXTAREA/contentEditable, so Space on a
- // focused <select> hijacked the transport. `isEditableTarget` covers SELECT.
+ // <select> hijacked the transport. `isEditableTarget` covers SELECT.
const { container } = renderReader();
const select = document.createElement('select');
container.appendChild(select);
@@ -72,17 +43,37 @@ describe('RapidReader keyboard transport', () => {
});
it('steps through the text with the arrow keys', () => {
- // The current word is split across spans to anchor its focal letter, so the
- // token counter ("2/4") is the readable signal for which word is showing.
+ // The current word is split across spans to anchor its focal letter, so the token
+ // counter ("2/4") is the readable signal for which word is showing.
const { container } = renderReader();
- const position = () => container.querySelector('.font-mono.text-gray-500').textContent.split(' ')[0];
- expect(position()).toBe('1/4');
+ expect(container.textContent).toContain('1/4');
act(() => { fireEvent.keyDown(document.body, { key: 'ArrowRight' }); });
- expect(position()).toBe('2/4');
+ expect(container.textContent).toContain('2/4');
act(() => { fireEvent.keyDown(document.body, { key: 'ArrowLeft' }); });
- expect(position()).toBe('1/4');
- expect(voiceHotkey).not.toHaveBeenCalled();
+ expect(container.textContent).toContain('1/4');
+ expect(voiceHotkey()).not.toHaveBeenCalled();
+ });
+
+ it('stands down while an unrelated dialog is open', () => {
+ const { container } = renderReader();
+ const dialog = document.createElement('div');
+ dialog.setAttribute('aria-modal', 'true');
+ container.appendChild(dialog);
+
+ act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
+
+ expect(screen.getByLabelText('Play')).toBeInTheDocument();
+ });
+
+ it('keeps its keys inside RapidReaderModal, whose own Modal is that dialog', () => {
+ render(<RapidReaderModal open text="alpha bravo charlie delta" title="Notes" onClose={vi.fn()} />);
+
+ // autoPlay is on in the modal, so the first Space pauses.
+ act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
+
+ expect(screen.getByLabelText('Play')).toBeInTheDocument();
+ expect(voiceHotkey()).not.toHaveBeenCalled();
});
});
diff --git a/client/src/components/openworld/PlayerController.jsx b/client/src/components/openworld/PlayerController.jsx
index 38312e0229..3ffa2aef1c 100644
--- a/client/src/components/openworld/PlayerController.jsx
+++ b/client/src/components/openworld/PlayerController.jsx
@@ -315,8 +315,9 @@ export default function PlayerController({
// In exploration mode, Space is the jump key — claim it in the capture phase so it
// never reaches the global voice push-to-talk hotkey (VoiceWidget listens for the
- // same key on `window`). Only the keydown is claimed; the matching keyup just
- // clears the held-key state, matching how the rig reads every other movement key.
+ // same key on `window`). Claiming the keydown is also what stops useKeyboardControls
+ // from recording the hold, hence the manual add here; the release needs no handler,
+ // because that keyup is NOT claimed and useKeyboardControls clears the key itself.
useKeyCapture({
enabled: active,
onKeyDown: (e) => {
@@ -324,19 +325,11 @@ export default function PlayerController({
keysRef.current.add(' ');
return true;
},
- onKeyUp: (e) => {
- if (e.code !== 'Space') return false;
- keysRef.current.delete(' ');
- return false;
- },
});
- // Drop a held jump when exploration mode ends, so re-entering it does not start
- // mid-jump from a keyup that fired after the listeners went away.
- useEffect(() => {
- if (!active) return undefined;
- return () => { keysRef.current.delete(' '); };
- }, [active, keysRef]);
+ // Drop a held jump when exploration mode ends — the keyup that would have cleared it
+ // can land after the mode switch, and the rig would resume mid-jump on re-entry.
+ useEffect(() => () => { keysRef.current.delete(' '); }, [active, keysRef]);
useFrame((_, delta) => {
if (!active) return;
diff --git a/client/src/components/openworld/PlayerController.test.jsx b/client/src/components/openworld/PlayerController.test.jsx
index b143d056a4..b147ff79c0 100644
--- a/client/src/components/openworld/PlayerController.test.jsx
+++ b/client/src/components/openworld/PlayerController.test.jsx
@@ -1,6 +1,7 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, fireEvent, act } from '@testing-library/react';
import * as THREE from 'three';
+import { installVoiceHotkeySpy } from '../../test/voiceHotkeySpy';
// PlayerController is an r3f component, but its Space handling is plain DOM wiring. The
// fiber hooks are stubbed so it can mount in jsdom without a WebGL canvas; rendering in
@@ -13,20 +14,10 @@ vi.mock('@react-three/fiber', () => ({
const PlayerController = (await import('./PlayerController')).default;
describe('PlayerController Space (jump) capture', () => {
- // Stands in for VoiceWidget's app-global push-to-talk hotkey, which binds the same
- // Space on `window` in the bubble phase.
- let voiceHotkey;
+ const voiceHotkey = installVoiceHotkeySpy();
let keysRef;
- beforeEach(() => {
- voiceHotkey = vi.fn();
- window.addEventListener('keydown', voiceHotkey);
- keysRef = { current: new Set() };
- });
-
- afterEach(() => {
- window.removeEventListener('keydown', voiceHotkey);
- });
+ beforeEach(() => { keysRef = { current: new Set() }; });
const renderRig = (props = {}) => render(
<PlayerController keysRef={keysRef} active cameraView="first" positions={new Map()} apps={[]} {...props} />,
@@ -36,14 +27,14 @@ describe('PlayerController Space (jump) capture', () => {
renderRig();
act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
- expect(keysRef.current.has(' ')).toBe(true);
- expect(voiceHotkey).not.toHaveBeenCalled();
- act(() => { fireEvent.keyUp(document.body, { key: ' ', code: 'Space' }); });
- expect(keysRef.current.has(' ')).toBe(false);
+ expect(keysRef.current.has(' ')).toBe(true);
+ expect(voiceHotkey()).not.toHaveBeenCalled();
});
it('ignores Space typed into a text field', () => {
+ // The old guard read document.activeElement, so an un-focused field did not
+ // suppress the jump; the shared isEditableTarget reads the event target.
const { container } = renderRig();
const input = document.createElement('input');
container.appendChild(input);
@@ -53,6 +44,18 @@ describe('PlayerController Space (jump) capture', () => {
expect(keysRef.current.has(' ')).toBe(false);
});
+ it('stands down while a dialog is open, so Space can activate its buttons', () => {
+ const { container } = renderRig();
+ const dialog = document.createElement('div');
+ dialog.setAttribute('aria-modal', 'true');
+ container.appendChild(dialog);
+
+ act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
+
+ expect(keysRef.current.has(' ')).toBe(false);
+ expect(voiceHotkey()).toHaveBeenCalledTimes(1);
+ });
+
it('drops a held jump when exploration mode ends', () => {
const { rerender } = renderRig();
act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
@@ -73,6 +76,6 @@ describe('PlayerController Space (jump) capture', () => {
act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
expect(keysRef.current.has(' ')).toBe(false);
- expect(voiceHotkey).toHaveBeenCalledTimes(1);
+ expect(voiceHotkey()).toHaveBeenCalledTimes(1);
});
});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 310c29adb3..af63ab4863 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -109,7 +109,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `usePendingListRows` | List-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`. | Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |
| `useKeyboardControls` | Keyboard binding for OpenWorld mode toggle. | OpenWorld-specific. |
| `useFirstTouchHint` | `{ visible, showOnFirstTouch }` — reveals a brief one-time touch gesture hint, then auto-hides it. | 3D canvases whose primary one-finger gesture needs an initial explanation. |
-| `useKeyCapture` | `useKeyCapture({ enabled?, onKeyDown, onKeyUp })` — capture-phase window listener whose handler *claims* an event by returning `true`; a claimed event is `preventDefault`ed AND `stopImmediatePropagation`ed so no app-global bubble handler sees it. Events from editable fields are never offered (shares `isEditableTarget`). | A surface that must own a key an app-global handler already binds — chiefly Space, which the voice widget uses for push-to-talk: the POST cognitive drills (n-back, go/no-go, reaction-time) and the Morse keyer. Not for ordinary shortcuts (that is `useKeyboardShortcuts`). |
+| `useKeyCapture` | `useKeyCapture({ enabled?, enabledInDialog?, onKeyDown, onKeyUp })` — capture-phase window listener whose handler *claims* an event by returning `true`; a claimed event is `preventDefault`ed AND `stopImmediatePropagation`ed so no app-global bubble handler sees it. Events from editable fields are never offered (shares `isEditableTarget`), nor are events fired while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a surface that lives INSIDE one — same name and default as `useKeyboardShortcuts`). Each listener subscribes only when its handler is supplied. | A surface that must own a key an app-global handler already binds — chiefly Space, which the voice widget uses for push-to-talk: the POST cognitive drills (n-back, go/no-go, reaction-time), the Morse keyer, RapidReader, the OpenWorld playback transport, and the exploration-mode jump key. Not for ordinary shortcuts (that is `useKeyboardShortcuts`). |
| `useKeyboardShortcuts` | `useKeyboardShortcuts(active, bindings, opts?)` — fire a `{ key: handler }` map while `active`; ignores events from editable fields (`isEditableTarget` also exported), ⌘/Ctrl/Alt chords, OS key auto-repeat (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a modal-owned shortcut); a falsy handler disables that key. | Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key/game input (that's `useKeyboardControls`). |
| `useHfTokenStatus` | Reads the central HuggingFace token status (`GET /image-gen/setup/hf-token-status` → `server/lib/hfToken.js`: stored → env → `hf auth login`). Returns `{ present, source, refresh }` where `present` is TRI-state — `null` means "unknown/failed", not "absent" — so a slow fetch can't flash a token nag at a user who has one. `{ enabled }` gates the fetch (false resets to unknown, so a modal re-checks per open); `{ errorAs: 'absent' }` opts a surface into offering the paste form when the status call fails. | Any gated-HuggingFace surface (3D page, MIDI gated modal, Image Gen banners) — use this instead of re-rolling the fetch, or the same blip renders differently per page. |
| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
diff --git a/client/src/hooks/useKeyCapture.js b/client/src/hooks/useKeyCapture.js
index 4f74fe7bc4..323036ce22 100644
--- a/client/src/hooks/useKeyCapture.js
+++ b/client/src/hooks/useKeyCapture.js
@@ -11,39 +11,52 @@ import { isEditableTarget } from './useKeyboardShortcuts.js';
* keyboard trap.
*
* Events originating in an editable field are never offered to the handlers, so
- * a Space-driven surface that also has a text input keeps normal typing.
+ * a Space-driven surface that also has a text input keeps normal typing. Nor are
+ * events fired while an `aria-modal` dialog is open: the surface is behind that
+ * dialog, and claiming Escape there would dismiss the surface instead of the
+ * layer the user is actually looking at. A surface that itself lives INSIDE a
+ * dialog passes `enabledInDialog: true` to opt back in. Both the option name and
+ * its default mirror `useKeyboardShortcuts`.
*
* Handlers are read through refs, so inline arrows recreated every render (the
* common call-site shape) don't tear down and re-add the listeners; only
- * `enabled` flips the subscription.
+ * `enabled` flips the subscription. A handler that is absent entirely doesn't
+ * subscribe its listener at all.
*
* @param {object} opts
- * @param {boolean} [opts.enabled=true] attach while truthy
+ * @param {boolean} [opts.enabled=true] attach while truthy
+ * @param {boolean} [opts.enabledInDialog=false] also fire while a dialog is open
* @param {(e: KeyboardEvent) => boolean} [opts.onKeyDown] return true to claim
* @param {(e: KeyboardEvent) => boolean} [opts.onKeyUp] return true to claim
*/
-export default function useKeyCapture({ enabled = true, onKeyDown, onKeyUp } = {}) {
+export default function useKeyCapture({ enabled = true, enabledInDialog = false, onKeyDown, onKeyUp } = {}) {
const downRef = useRef(onKeyDown);
const upRef = useRef(onKeyUp);
downRef.current = onKeyDown;
upRef.current = onKeyUp;
+ // Presence, not identity — a call site that always passes a handler keeps one
+ // stable subscription no matter how often its inline arrow is recreated.
+ const hasDown = Boolean(onKeyDown);
+ const hasUp = Boolean(onKeyUp);
+
useEffect(() => {
if (!enabled) return undefined;
const claim = (ref) => (e) => {
if (isEditableTarget(e.target)) return;
+ if (!enabledInDialog && document.querySelector('[aria-modal="true"]')) return;
if (ref.current?.(e) !== true) return;
e.preventDefault();
// Subsumes stopPropagation: also skips the remaining listeners on window.
e.stopImmediatePropagation();
};
- const down = claim(downRef);
- const up = claim(upRef);
- window.addEventListener('keydown', down, true);
- window.addEventListener('keyup', up, true);
+ const down = hasDown ? claim(downRef) : null;
+ const up = hasUp ? claim(upRef) : null;
+ if (down) window.addEventListener('keydown', down, true);
+ if (up) window.addEventListener('keyup', up, true);
return () => {
- window.removeEventListener('keydown', down, true);
- window.removeEventListener('keyup', up, true);
+ if (down) window.removeEventListener('keydown', down, true);
+ if (up) window.removeEventListener('keyup', up, true);
};
- }, [enabled]);
+ }, [enabled, enabledInDialog, hasDown, hasUp]);
}
diff --git a/client/src/hooks/useKeyCapture.test.jsx b/client/src/hooks/useKeyCapture.test.jsx
index 000963ac62..b0c235ee0b 100644
--- a/client/src/hooks/useKeyCapture.test.jsx
+++ b/client/src/hooks/useKeyCapture.test.jsx
@@ -7,11 +7,20 @@ import useKeyCapture from './useKeyCapture';
// Space push-to-talk hotkey from firing during a Space-driven drill. Every test
// here installs a stand-in for that global listener and asserts on it.
-function Probe({ enabled = true, onKeyDown, onKeyUp }) {
- useKeyCapture({ enabled, onKeyDown, onKeyUp });
+function Probe({ enabled = true, enabledInDialog = false, onKeyDown, onKeyUp }) {
+ useKeyCapture({ enabled, enabledInDialog, onKeyDown, onKeyUp });
return <input aria-label="note" />;
}
+// A stand-in for whatever dialog is on top — Modal and Drawer both render this
+// attribute, and the hook consults it, not either component.
+function openDialog() {
+ const dialog = document.createElement("div");
+ dialog.setAttribute("aria-modal", "true");
+ document.body.appendChild(dialog);
+ return () => dialog.remove();
+}
+
function withGlobalHotkey(fn) {
const global = vi.fn();
window.addEventListener('keydown', global);
@@ -90,6 +99,38 @@ describe('useKeyCapture', () => {
});
});
+ it('stands down while a dialog is open, so that layer owns the key', () => {
+ const claimed = vi.fn(() => true);
+ render(<Probe onKeyDown={claimed} />);
+ const close = openDialog();
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ' });
+ expect(claimed).not.toHaveBeenCalled();
+ expect(global).toHaveBeenCalledTimes(1);
+ });
+ close();
+ });
+
+ it('keeps claiming inside a dialog when the surface opts in', () => {
+ const claimed = vi.fn(() => true);
+ render(<Probe enabledInDialog onKeyDown={claimed} />);
+ const close = openDialog();
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ' });
+ expect(claimed).toHaveBeenCalledTimes(1);
+ expect(global).not.toHaveBeenCalled();
+ });
+ close();
+ });
+
+ it('subscribes no keyup listener when the caller passes no onKeyUp', () => {
+ const addSpy = vi.spyOn(window, 'addEventListener');
+ render(<Probe onKeyDown={() => true} />);
+ const captured = addSpy.mock.calls.filter(([, , capture]) => capture === true).map(([type]) => type);
+ expect(captured).toEqual(['keydown']);
+ addSpy.mockRestore();
+ });
+
it('reads the latest handler without re-subscribing', () => {
const first = vi.fn(() => true);
const second = vi.fn(() => true);
diff --git a/client/src/pages/OpenWorld.jsx b/client/src/pages/OpenWorld.jsx
index bfd96c110e..31ce221e1e 100644
--- a/client/src/pages/OpenWorld.jsx
+++ b/client/src/pages/OpenWorld.jsx
@@ -4,7 +4,7 @@ import { useOpenWorldData } from '../hooks/useOpenWorldData';
import { useOpenWorldPlayback } from '../hooks/useOpenWorldPlayback';
import useOpenWorldAudio from '../hooks/useOpenWorldAudio';
import useKeyboardControls from '../hooks/useKeyboardControls';
-import useKeyboardShortcuts, { isEditableTarget } from '../hooks/useKeyboardShortcuts';
+import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';
import useKeyCapture from '../hooks/useKeyCapture';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { mergeFrameIntoOpenWorldProps } from '../lib/openWorldPlaybackFrame';
@@ -308,19 +308,16 @@ function OpenWorldInner() {
}, [clearFocusRoute, updateSetting, playback]);
// Esc exits photo mode; ←/→ cycle the framing preset; D toggles depth-of-field. Bound only while
- // photo mode is on so it doesn't shadow other shortcuts. Ignores key events while typing.
- useEffect(() => {
- if (!photoMode) return;
- const onKey = (e) => {
- if (isEditableTarget(e.target)) return;
- if (e.key === 'Escape') setPhotoMode(false);
- else if (e.key === 'ArrowLeft') setPhotoPresetId(id => cyclePreset(id, -1));
- else if (e.key === 'ArrowRight') setPhotoPresetId(id => cyclePreset(id, 1));
- else if (e.key === 'd' || e.key === 'D') setPhotoDof(v => !v);
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [photoMode]);
+ // photo mode is on so it doesn't shadow other shortcuts. These are ordinary shortcuts, not keys
+ // an app-global handler already owns, so they ride useKeyboardShortcuts rather than a capture-phase
+ // claim — which also yields them to any dialog opened on top of photo mode.
+ useKeyboardShortcuts(photoMode, {
+ Escape: () => setPhotoMode(false),
+ ArrowLeft: () => setPhotoPresetId(id => cyclePreset(id, -1)),
+ ArrowRight: () => setPhotoPresetId(id => cyclePreset(id, 1)),
+ d: () => setPhotoDof(v => !v),
+ D: () => setPhotoDof(v => !v),
+ });
// Playback keyboard transport: Esc exits, Space play/pause, ←/→ step a frame.
// Bound only while playback is active. Claimed in the capture phase so Space
@@ -329,10 +326,6 @@ function OpenWorldInner() {
useKeyCapture({
enabled: playback.active,
onKeyDown: (e) => {
- // An open dialog layer (the settings drawer, a lightbox) owns the keyboard while
- // it is up — most importantly Escape, which has to dismiss that layer rather than
- // drop the user out of playback behind it.
- if (document.querySelector('[aria-modal="true"]')) return false;
if (e.key === 'Escape') playback.exit();
else if (e.key === ' ') playback.togglePlay();
else if (e.key === 'ArrowLeft') playback.step(-1);
diff --git a/client/src/pages/OpenWorld.transport.test.jsx b/client/src/pages/OpenWorld.transport.test.jsx
index 25aac66430..c0f1af4f0a 100644
--- a/client/src/pages/OpenWorld.transport.test.jsx
+++ b/client/src/pages/OpenWorld.transport.test.jsx
@@ -1,6 +1,7 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, fireEvent, act } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router';
+import { installVoiceHotkeySpy } from '../test/voiceHotkeySpy';
// Same stubbing strategy as OpenWorld.fastTravel.test.jsx: the 3D scene and the HUD are
// replaced with inert divs so the page's keyboard WIRING can be exercised in jsdom.
@@ -50,10 +51,7 @@ const renderPage = () => render(
);
describe('OpenWorld playback transport keys', () => {
- // Stands in for VoiceWidget's app-global push-to-talk hotkey, which binds the same
- // Space on `window` in the bubble phase. If the transport ever stops CLAIMING the
- // key in the capture phase, this spy fires and the mic opens mid-playback.
- let voiceHotkey;
+ const voiceHotkey = installVoiceHotkeySpy();
beforeEach(() => {
playback.active = true;
@@ -61,12 +59,6 @@ describe('OpenWorld playback transport keys', () => {
playback.step.mockClear();
playback.togglePlay.mockClear();
localStorage.clear();
- voiceHotkey = vi.fn();
- window.addEventListener('keydown', voiceHotkey);
- });
-
- afterEach(() => {
- window.removeEventListener('keydown', voiceHotkey);
});
it('toggles play on Space without leaking the key to the global voice hotkey', () => {
@@ -75,7 +67,7 @@ describe('OpenWorld playback transport keys', () => {
act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
expect(playback.togglePlay).toHaveBeenCalledTimes(1);
- expect(voiceHotkey).not.toHaveBeenCalled();
+ expect(voiceHotkey()).not.toHaveBeenCalled();
});
it('claims Escape and the arrow keys too', () => {
@@ -87,7 +79,7 @@ describe('OpenWorld playback transport keys', () => {
expect(playback.step.mock.calls).toEqual([[-1], [1]]);
expect(playback.exit).toHaveBeenCalledTimes(1);
- expect(voiceHotkey).not.toHaveBeenCalled();
+ expect(voiceHotkey()).not.toHaveBeenCalled();
});
it('lets unhandled keys through to app-global listeners', () => {
@@ -95,7 +87,7 @@ describe('OpenWorld playback transport keys', () => {
act(() => { fireEvent.keyDown(document.body, { key: 'j' }); });
- expect(voiceHotkey).toHaveBeenCalledTimes(1);
+ expect(voiceHotkey()).toHaveBeenCalledTimes(1);
expect(playback.togglePlay).not.toHaveBeenCalled();
});
@@ -112,7 +104,8 @@ describe('OpenWorld playback transport keys', () => {
it('yields the transport keys to an open dialog layer', () => {
// The settings drawer renders aria-modal and closes on its own Escape handler; the
- // transport must not swallow that keystroke out from under it.
+ // transport must not swallow that keystroke out from under it (useKeyCapture's
+ // enabledInDialog default).
const { container } = renderPage();
const drawer = document.createElement('div');
drawer.setAttribute('aria-modal', 'true');
@@ -123,7 +116,7 @@ describe('OpenWorld playback transport keys', () => {
expect(playback.exit).not.toHaveBeenCalled();
expect(playback.togglePlay).not.toHaveBeenCalled();
- expect(voiceHotkey).toHaveBeenCalledTimes(2);
+ expect(voiceHotkey()).toHaveBeenCalledTimes(2);
});
it('binds nothing while playback is inactive', () => {
@@ -133,6 +126,6 @@ describe('OpenWorld playback transport keys', () => {
act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
expect(playback.togglePlay).not.toHaveBeenCalled();
- expect(voiceHotkey).toHaveBeenCalledTimes(1);
+ expect(voiceHotkey()).toHaveBeenCalledTimes(1);
});
});
diff --git a/client/src/test/voiceHotkeySpy.js b/client/src/test/voiceHotkeySpy.js
new file mode 100644
index 0000000000..6dca988e1c
--- /dev/null
+++ b/client/src/test/voiceHotkeySpy.js
@@ -0,0 +1,32 @@
+import { vi, beforeEach, afterEach } from 'vitest';
+
+/**
+ * Stand-in for the voice widget's app-global push-to-talk hotkey, which binds
+ * Space (and every other key) on `window` in the bubble phase.
+ *
+ * Any surface that claims a key through `useKeyCapture` is claiming it *from*
+ * this listener, so "did the key leak?" is the assertion those suites keep
+ * needing. Call this at the top of a `describe`; it registers its own
+ * beforeEach/afterEach and returns a getter for the current spy.
+ *
+ * const voiceHotkey = installVoiceHotkeySpy();
+ * …
+ * expect(voiceHotkey()).not.toHaveBeenCalled();
+ *
+ * @param {object} [opts]
+ * @param {boolean} [opts.keyup=false] also spy on keyup (held-key surfaces)
+ * @returns {() => import('vitest').Mock}
+ */
+export function installVoiceHotkeySpy({ keyup = false } = {}) {
+ let spy;
+ beforeEach(() => {
+ spy = vi.fn();
+ window.addEventListener('keydown', spy);
+ if (keyup) window.addEventListener('keyup', spy);
+ });
+ afterEach(() => {
+ window.removeEventListener('keydown', spy);
+ if (keyup) window.removeEventListener('keyup', spy);
+ });
+ return () => spy;
+}