Skip to content

Commit 1e18255

Browse files
committed
refactor: Extract onKeyDown handler for legibility
1 parent 719bd34 commit 1e18255

File tree

1 file changed

+30
-25
lines changed
  • code/core/src/components/components/Select

1 file changed

+30
-25
lines changed

code/core/src/components/components/Select/Select.tsx

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,35 @@ export const Select = forwardRef<HTMLButtonElement, SelectProps>(
394394
[options, resetOption, setActiveOption, selectedOptions]
395395
);
396396

397+
const handleListboxKeyDown = useCallback(
398+
(e: KeyboardEvent<HTMLUListElement>) => {
399+
// We don't prevent default on Tab, so that the Tab or Shift+Tab goes
400+
// through after we've repositioned to the Button.
401+
if (e.key !== 'Tab') {
402+
e.preventDefault();
403+
} else {
404+
handleClose();
405+
}
406+
407+
if (e.key === 'Escape') {
408+
handleClose();
409+
} else if (e.key === 'ArrowDown') {
410+
moveActiveOptionDown();
411+
} else if (e.key === 'ArrowUp') {
412+
moveActiveOptionUp();
413+
} else if (e.key === 'Home') {
414+
setActiveOption(options[0]);
415+
} else if (e.key === 'End') {
416+
setActiveOption(options[options.length - 1]);
417+
} else if (e.key === 'PageDown') {
418+
moveActiveOptionDown(PAGE_STEP_SIZE);
419+
} else if (e.key === 'PageUp') {
420+
moveActiveOptionUp(PAGE_STEP_SIZE);
421+
}
422+
},
423+
[handleClose, moveActiveOptionDown, moveActiveOptionUp, options, setActiveOption]
424+
);
425+
397426
// Transfer focus to the active option whenever we open the listbox.
398427
useEffect(() => {
399428
if (isOpen && activeOption) {
@@ -471,31 +500,7 @@ export const Select = forwardRef<HTMLButtonElement, SelectProps>(
471500
id={listboxId}
472501
ref={listboxRef}
473502
aria-multiselectable={multiSelect}
474-
onKeyDown={(e) => {
475-
// We don't prevent default on Tab, so that the Tab or Shift+Tab goes
476-
// through after we've repositioned to the Button.
477-
if (e.key !== 'Tab') {
478-
e.preventDefault();
479-
} else {
480-
handleClose();
481-
}
482-
483-
if (e.key === 'Escape') {
484-
handleClose();
485-
} else if (e.key === 'ArrowDown') {
486-
moveActiveOptionDown();
487-
} else if (e.key === 'ArrowUp') {
488-
moveActiveOptionUp();
489-
} else if (e.key === 'Home') {
490-
setActiveOption(options[0]);
491-
} else if (e.key === 'End') {
492-
setActiveOption(options[options.length - 1]);
493-
} else if (e.key === 'PageDown') {
494-
moveActiveOptionDown(PAGE_STEP_SIZE);
495-
} else if (e.key === 'PageUp') {
496-
moveActiveOptionUp(PAGE_STEP_SIZE);
497-
}
498-
}}
503+
onKeyDown={handleListboxKeyDown}
499504
>
500505
{options.map((option) => (
501506
<SelectOption

0 commit comments

Comments
 (0)