Skip to content

Commit

Permalink
Added escape key handler to select elements (#19689)
Browse files Browse the repository at this point in the history
ref DES-58
  • Loading branch information
minimaluminium committed Mar 11, 2024
1 parent 4c02b60 commit be3a566
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion apps/admin-x-design-system/src/global/form/Select.tsx
@@ -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';
Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit be3a566

Please sign in to comment.