Commit 3066b38c by Jack Westbrook Committed by GitHub

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>
parent 7db00ed6
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;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment