signal-desktop/ts/components/ModalHost.tsx

96 lines
2.7 KiB
TypeScript
Raw Normal View History

2020-11-20 17:30:45 +00:00
// Copyright 2019-2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import React, { useEffect } from 'react';
import classNames from 'classnames';
2020-11-20 17:30:45 +00:00
import { createPortal } from 'react-dom';
import FocusTrap from 'focus-trap-react';
2021-10-14 16:52:42 +00:00
import { SpringValues, animated } from '@react-spring/web';
2021-10-14 16:52:42 +00:00
import type { ModalConfigType } from '../hooks/useAnimated';
import { Theme, themeClassName } from '../util/theme';
2021-09-17 22:24:21 +00:00
import { useEscapeHandling } from '../hooks/useEscapeHandling';
2020-11-20 17:30:45 +00:00
export type PropsType = {
2021-10-14 16:52:42 +00:00
readonly children: React.ReactElement;
2021-05-28 16:15:17 +00:00
readonly noMouseClose?: boolean;
2020-11-20 17:30:45 +00:00
readonly onClose: () => unknown;
2021-10-14 16:52:42 +00:00
readonly onEscape?: () => unknown;
readonly overlayStyles?: SpringValues<ModalConfigType>;
readonly theme?: Theme;
2020-11-20 17:30:45 +00:00
};
export const ModalHost = React.memo(
2021-10-14 16:52:42 +00:00
({
children,
noMouseClose,
onClose,
onEscape,
theme,
overlayStyles,
}: PropsType) => {
const [root, setRoot] = React.useState<HTMLElement | null>(null);
const [isMouseDown, setIsMouseDown] = React.useState(false);
2020-11-20 17:30:45 +00:00
useEffect(() => {
const div = document.createElement('div');
document.body.appendChild(div);
setRoot(div);
2020-11-20 17:30:45 +00:00
return () => {
document.body.removeChild(div);
setRoot(null);
};
}, []);
2020-11-20 17:30:45 +00:00
2021-09-17 22:24:21 +00:00
useEscapeHandling(onEscape || onClose);
2020-11-20 17:30:45 +00:00
// This makes it easier to write dialogs to be hosted here; they won't have to worry
// as much about preventing propagation of mouse events.
const handleMouseDown = React.useCallback(
(e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
setIsMouseDown(true);
}
},
[setIsMouseDown]
);
const handleMouseUp = React.useCallback(
(e: React.MouseEvent) => {
setIsMouseDown(false);
if (e.target === e.currentTarget && isMouseDown) {
onClose();
}
},
[onClose, isMouseDown, setIsMouseDown]
);
2020-11-20 17:30:45 +00:00
return root
? createPortal(
<FocusTrap
focusTrapOptions={{
// This is alright because the overlay covers the entire screen
allowOutsideClick: false,
}}
>
2021-10-14 16:52:42 +00:00
<div>
<animated.div
role="presentation"
className={classNames(
'module-modal-host__overlay',
theme ? themeClassName(theme) : undefined
)}
onMouseDown={noMouseClose ? undefined : handleMouseDown}
onMouseUp={noMouseClose ? undefined : handleMouseUp}
style={overlayStyles}
/>
<div className="module-modal-host__container">{children}</div>
</div>
</FocusTrap>,
root
)
: null;
}
);