Close datagrid modal by esc key (#2507)

This commit is contained in:
Krzysztof Żuraw 2022-11-09 17:40:57 +01:00 committed by GitHub
parent 33cfd21a76
commit 5fdb51c0ee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 11 deletions

View file

@ -50,12 +50,14 @@ const useAnimationStyles = (isOpen: boolean, duration: number) => {
};
};
interface FullScreenContainerProps {
type FullScreenContainerProps = FC<
PropsWithChildren<{
open?: boolean;
className?: string;
}
}>
>;
const Portal = ({ className, children, open }) => {
const Portal: FullScreenContainerProps = ({ className, children, open }) => {
const { delayedState: delayedOpen, duration } = useDelayedState(open);
const styles = useAnimationStyles(open, duration);
@ -67,13 +69,12 @@ const Portal = ({ className, children, open }) => {
);
};
export const FullScreenContainer: FC<PropsWithChildren<
FullScreenContainerProps
>> = ({ children, open, className }) => (
export const FullScreenContainer: FullScreenContainerProps = ({
children,
...rest
}) => (
<>
<Portal className={className} open={open}>
{children}
</Portal>
<Portal {...rest}>{children}</Portal>
{children}
</>
);

View file

@ -2,6 +2,7 @@ import { usePreventHistoryBack } from "@saleor/hooks/usePreventHistoryBack";
import { useEffect, useState } from "react";
import { useDelayedState } from "./useDelayedState";
import { usePressEscKey } from "./usePressEscKey";
export const useFullScreenMode = () => {
const { enable, disable } = usePreventHistoryBack(document.body, {
@ -11,6 +12,10 @@ export const useFullScreenMode = () => {
const { delayedState: delayedOpen } = useDelayedState(!open);
const togglePreventHistory = open ? disable : enable;
usePressEscKey(() => {
setOpen(false);
});
const toggle = () => {
setOpen(p => !p);
togglePreventHistory();

View file

@ -0,0 +1,14 @@
import { useEffect } from "react";
export const usePressEscKey = (callback?: () => void) => {
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (event.code === "Escape") {
callback();
}
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [callback]);
};