Added escape key handler to select elements (#19689)

ref DES-58
This commit is contained in:
Sodbileg Gansukh 2024-03-11 17:40:03 +08:00 committed by GitHub
parent 4c02b60ec3
commit be3a5664a2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,5 +1,5 @@
import clsx from 'clsx';
import React, {useId, useMemo} from 'react';
import React, {useId, useMemo, useEffect} from 'react';
import ReactSelect, {ClearIndicatorProps, DropdownIndicatorProps, GroupBase, OptionProps, OptionsOrGroups, Props, components} from 'react-select';
import AsyncSelect from 'react-select/async';
import {useFocusContext} from '../../providers/DesignSystemProvider';
@ -118,6 +118,26 @@ const Select: React.FC<SelectProps> = ({
setFocusState(false);
};
useEffect(() => {
const handleEscapeKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
// Fix for Safari - if an element in the modal is focused, closing it will jump to
// the bottom of the page because Safari tries to focus the "next" element in the DOM
if (document.activeElement && document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
setFocusState(false);
}
};
document.addEventListener('keydown', handleEscapeKey);
// Clean up the event listener when the modal is closed
return () => {
document.removeEventListener('keydown', handleEscapeKey);
};
}, [setFocusState]);
let containerClasses = '';
if (!unstyled) {
containerClasses = clsx(