Skip to content

Commit

Permalink
Close modal when both mouseup/mousedown are inside
Browse files Browse the repository at this point in the history
  • Loading branch information
indutny-signal committed Jul 12, 2021
1 parent dfb3c23 commit 77668c3
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions ts/components/ModalHost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type PropsType = {
export const ModalHost = React.memo(
({ onEscape, onClose, children, noMouseClose, theme }: PropsType) => {
const [root, setRoot] = React.useState<HTMLElement | null>(null);
const [isMouseDown, setIsMouseDown] = React.useState(false);

useEffect(() => {
const div = document.createElement('div');
Expand Down Expand Up @@ -51,13 +52,23 @@ export const ModalHost = React.memo(

// 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 handleCancel = React.useCallback(
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]
[onClose, isMouseDown, setIsMouseDown]
);

return root
Expand All @@ -68,7 +79,8 @@ export const ModalHost = React.memo(
'module-modal-host__overlay',
theme ? themeClassName(theme) : undefined
)}
onClick={noMouseClose ? undefined : handleCancel}
onMouseDown={noMouseClose ? undefined : handleMouseDown}
onMouseUp={noMouseClose ? undefined : handleMouseUp}
>
{children}
</div>,
Expand Down

0 comments on commit 77668c3

Please sign in to comment.