Skip to content

Commit

Permalink
fix(@clayui/color-picker): splotch should get focus if menu is closed…
Browse files Browse the repository at this point in the history
… via 'esc'
  • Loading branch information
bryceosterhaus committed Aug 11, 2020
1 parent e5c9994 commit 85b52c6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
1 change: 1 addition & 0 deletions packages/clay-color-picker/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ const ClayColorPicker: React.FunctionComponent<IProps> = ({
active={active}
alignElementRef={triggerElementRef}
className="clay-color-dropdown-menu"
focusRefOnEsc={splotchRef}
onSetActive={setActive}
ref={dropdownContainerRef}
>
Expand Down
9 changes: 8 additions & 1 deletion packages/clay-drop-down/src/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ interface IProps extends React.HTMLAttributes<HTMLDivElement> {
*/
hasRightSymbols?: boolean;

/**
* Element ref to call focus() on after menu is closed via Escape key
*/
focusRefOnEsc?: React.RefObject<HTMLElement>;

/**
* Function for setting the offset of the menu from the trigger.
*/
Expand All @@ -154,6 +159,7 @@ const ClayDropDownMenu = React.forwardRef<HTMLDivElement, IProps>(
className,
hasLeftSymbols,
hasRightSymbols,
focusRefOnEsc,
offsetFn = (points) =>
OFFSET_MAP[points.join('') as keyof typeof OFFSET_MAP] as [
number,
Expand All @@ -171,7 +177,8 @@ const ClayDropDownMenu = React.forwardRef<HTMLDivElement, IProps>(

useDropdownCloseInteractions(
[alignElementRef, subPortalRef],
onSetActive
onSetActive,
focusRefOnEsc
);

React.useLayoutEffect(() => {
Expand Down
14 changes: 11 additions & 3 deletions packages/clay-drop-down/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export function useDropdownCloseInteractions(
nodeRefs:
| React.RefObject<HTMLElement>
| Array<React.RefObject<HTMLElement>>,
setActive: (val: boolean) => void
setActive: (val: boolean) => void,
focusRefOnEsc?: React.RefObject<HTMLElement>
) {
React.useEffect(() => {
const handleClick = (event: MouseEvent) => {
Expand All @@ -32,8 +33,15 @@ export function useDropdownCloseInteractions(
}
};

const handleEsc = (event: KeyboardEvent) =>
event.key === Keys.Esc && setActive(false);
const handleEsc = (event: KeyboardEvent) => {
if (event.key === Keys.Esc) {
if (focusRefOnEsc && focusRefOnEsc.current) {
focusRefOnEsc.current.focus();
}

return setActive(false);
}
};

window.addEventListener('mousedown', handleClick);
window.addEventListener('keydown', handleEsc);
Expand Down

0 comments on commit 85b52c6

Please sign in to comment.