Grafana-ui: fixes closing modals with escape key (#30745)

* feat(grafana-ui): add an escape key listener to Modal

* Update packages/grafana-ui/src/components/Modal/Modal.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* feat(grafana-ui): add closeOnEscape prop to control Modal behaviour

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>
This commit is contained in:
Jack Westbrook 2021-02-03 17:01:29 +01:00 committed by GitHub
parent 7db00ed6a0
commit 3066b38c5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,4 @@
import React, { FC, PropsWithChildren, useCallback } from 'react';
import React, { FC, PropsWithChildren, useCallback, useEffect } from 'react';
import { Portal } from '../Portal/Portal';
import { cx } from 'emotion';
import { useTheme } from '../../themes';
@ -14,6 +14,7 @@ export interface Props {
title: string | JSX.Element;
className?: string;
contentClassName?: string;
closeOnEscape?: boolean;
isOpen?: boolean;
onDismiss?: () => void;
@ -27,6 +28,7 @@ export function Modal(props: PropsWithChildren<Props>): ReturnType<FC<Props>> {
title,
children,
isOpen = false,
closeOnEscape = true,
className,
contentClassName,
onDismiss: propsOnDismiss,
@ -40,6 +42,23 @@ export function Modal(props: PropsWithChildren<Props>): ReturnType<FC<Props>> {
}
}, [propsOnDismiss]);
const onEscKey = (ev: KeyboardEvent) => {
if (ev.key === 'Esc' || ev.key === 'Escape') {
onDismiss();
}
};
useEffect(() => {
if (isOpen && closeOnEscape) {
document.addEventListener('keydown', onEscKey, false);
} else {
document.removeEventListener('keydown', onEscKey, false);
}
return () => {
document.removeEventListener('keydown', onEscKey, false);
};
}, [closeOnEscape, isOpen]);
if (!isOpen) {
return null;
}