mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
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:
parent
7db00ed6a0
commit
3066b38c5e
@ -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;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user