Hook returning whether any of the given keys is held down
Desktop-style web apps change behaviour while a modifier key is held: holding Shift selects a range of rows, holding Space turns the cursor into a hand that pans a canvas, holding Alt shows keyboard hints. Implement a React hook, useKeyHeld, that returns whether one of the given keys is currently held down.
function useKeyHeld(keys: string | string[]): boolean
Each key is a KeyboardEvent.key value, for example 'Shift', ' ' (Space), 'Alt', or 'k'.
keydown and keyup on window. Return true while at least one of keys is held down, and false otherwise.'k' matches 'K', because holding Shift changes event.key from 'k' to 'K', and the user may release Shift before the letter.['Shift', 'Meta'], pressing both and releasing only Shift keeps the result true.keydown events (event.repeat is true). A single keyup still releases the key.blur event on window), treat every key as released. Otherwise a user who presses Alt+Tab to switch apps comes back with Alt stuck “held”, because the keyup went to another app.keys argument changes, return the result for the new keys in that render, including keys that were already held.function FileList({ files }) {
const extendSelection = useKeyHeld('Shift');
return files.map((file) => (
<Row key={file.id} file={file} onClick={() => select(file, { range: extendSelection })} />
));
}
const commandHeld = useKeyHeld(['Meta', 'Control']);
// keydown Meta -> true
// keydown Control -> true
// keyup Meta -> true (Control is still down)
// keyup Control -> false
// keydown Control, blur -> false (window lost focus)
KeyboardEvents (keydown, keyup) and a blur event on window, inside ReactDOM.flushSync. They count the active keydown, keyup, and blur listeners on window.Object.assign(window, { useKeyHeld }); below “Do not edit below this line”. The tests use it to call your hook.