Shortcuts modal opened with ? that restores focus on close
A note-taking app has a help dialog that lists its keyboard shortcuts. Power users open it by pressing ? anywhere on the page, everyone else clicks a button. Build the page and the dialog so it behaves like a proper modal: it is announced as a dialog, takes focus when it opens, closes in all the usual ways, and gives focus back to wherever the user was.
The starter code includes the shortcuts:
const SHORTCUTS = [
{ keys: ['Ctrl', 'K'], action: 'Open search' },
{ keys: ['N'], action: 'New note' },
{ keys: ['Ctrl', 'Shift', 'P'], action: 'Pin note' },
{ keys: ['?'], action: 'Toggle this help' },
];
Press ? to see all shortcuts.Render a full-screen backdrop element whose direct child is the dialog panel. The panel:
role="dialog" and aria-modal="true",aria-labelledby,SHORTCUTS order: its keys joined with + (for example Ctrl + Shift + P, ideally each key in a <kbd>) and its action,aria-label="Close").While the dialog is closed, don’t render it (or hide it).
keydown whose key is '?') anywhere on the page opens it too. Listen on document. Ignore the key when:
input, textarea, select, or a contenteditable element), because the user is typing a question mark, ordocument.activeElement) and move focus to the Close button.Press ? on the page dialog opens, focus on Close
Press ? again dialog closes
Type "what?" in Search notes the ? goes into the input, no dialog
Press Ctrl + ? no dialog
Focus Search notes, click "Keyboard shortcuts"
Press Escape dialog closes, focus back in Search notes
Click "Keyboard shortcuts", click the dialog title still open
Click the dark backdrop dialog closes
keydown listener handles both ? and Escape, so it must read the current open state, not a stale copy captured when it was added.mousedown happened handles that.The tests click your buttons and dispatch keydown events (key: '?' with shiftKey, key: 'Escape') on the focused element, or on the input for the “typing” case. The events bubble to document. You don’t need test ids or class names. The test frame is hidden, so the browser can’t move focus by itself there. The tests track focus through element.focus() calls and document.activeElement, so move focus with .focus() (React’s autoFocus also works). They check that:
role="dialog" element until it is opened.aria-modal="true", an aria-labelledby element whose text is Keyboard shortcuts, every action, and the keys Ctrl + K and Ctrl + Shift + P (spaces around + are optional).document.activeElement is the Close button (found by its aria-label or text) right after opening, and the previously focused element after closing.mousedown, mouseup and click on the panel’s parent element. The same events on the dialog title must not close it.A closed dialog can be removed from the page or hidden (hidden, display: none, or visibility: hidden). Capitalization and extra spacing don’t matter.