From 710ab0a81e5b28dd3b4e763c4fd01763c369e305 Mon Sep 17 00:00:00 2001 From: adamviktora Date: Tue, 22 Oct 2024 15:19:49 +0200 Subject: [PATCH] feat(Select example): make items accessible with keyboard --- .../Select/examples/SelectBasic.tsx | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/react-core/src/components/Select/examples/SelectBasic.tsx b/packages/react-core/src/components/Select/examples/SelectBasic.tsx index a149e5d3994..101650ab108 100644 --- a/packages/react-core/src/components/Select/examples/SelectBasic.tsx +++ b/packages/react-core/src/components/Select/examples/SelectBasic.tsx @@ -6,6 +6,8 @@ export const SelectBasic: React.FunctionComponent = () => { const [selected, setSelected] = React.useState('Select a value'); const [isDisabled, setIsDisabled] = React.useState(false); + const menuRef = React.useRef(); + const onToggleClick = () => { setIsOpen(!isOpen); }; @@ -18,6 +20,24 @@ export const SelectBasic: React.FunctionComponent = () => { setIsOpen(false); }; + const onKeyDown = (event: React.KeyboardEvent) => { + if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') { + return; + } + event.preventDefault(); + setIsOpen(true); + + const firstItemSelector = 'li button:not(:disabled),li input:not(:disabled)'; + const lastItemSelector = 'li:last-child button:not(:disabled),li:last-child input:not(:disabled)'; + + setTimeout(() => { + const elementToFocus = menuRef?.current?.querySelector( + event.key === 'ArrowDown' ? firstItemSelector : lastItemSelector + ); + elementToFocus && (elementToFocus as HTMLElement).focus(); + }, 10); + }; + const toggle = (toggleRef: React.Ref) => ( { width: '200px' } as React.CSSProperties } + onKeyDown={onKeyDown} > {selected} @@ -44,6 +65,7 @@ export const SelectBasic: React.FunctionComponent = () => { style={{ marginBottom: 20 }} />