Skip to content

Commit

Permalink
Modal: Fiks lukking ved slipp av museknapp på backdrop
Browse files Browse the repository at this point in the history
  • Loading branch information
cskrov committed Feb 21, 2024
1 parent 884bf0c commit a469a23
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions @navikt/core/react/src/modal/Modal.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { useFloatingPortalNode } from "@floating-ui/react";
import cl from "clsx";
import React, { forwardRef, useContext, useEffect, useRef } from "react";
import React, {
forwardRef,
useCallback,
useContext,
useEffect,
useRef,
} from "react";
import { createPortal } from "react-dom";
import { DateContext } from "../date/context";
import { useProvider } from "../provider/Provider";
Expand Down Expand Up @@ -86,6 +92,7 @@ export const Modal = forwardRef<HTMLDialogElement, ModalProps>(
"aria-labelledby": ariaLabelledby,
style,
onClick,
onMouseDown,
...rest
}: ModalProps,
ref,
Expand Down Expand Up @@ -146,6 +153,15 @@ export const Modal = forwardRef<HTMLDialogElement, ModalProps>(
...(!isWidthPreset ? { width } : {}),
};

const mouseClickStart = useRef({ x: 0, y: 0 });
const handleModalMouseDown = useCallback(
(e: React.MouseEvent<HTMLDialogElement>) => {
mouseClickStart.current.x = e.pageX;
mouseClickStart.current.y = e.pageY;
},
[],
);

/**
* @note `closeOnBackdropClick` has issues on polyfill when nesting modals (DatePicker)
*/
Expand All @@ -156,7 +172,18 @@ export const Modal = forwardRef<HTMLDialogElement, ModalProps>(
event.target === modalRef.current &&
(!onBeforeClose || onBeforeClose() !== false)
) {
modalRef.current.close();
const rect = modalRef.current.getBoundingClientRect();
const { x, y } = mouseClickStart.current;

// Check if the mouse click was started outside the modal.
if (
x < rect.x ||
y < rect.y ||
x > rect.x + rect.width ||
y > rect.y + rect.height
) {
modalRef.current.close();
}
}
};

Expand All @@ -183,6 +210,11 @@ export const Modal = forwardRef<HTMLDialogElement, ModalProps>(
style={mergedStyle}
onCancel={composeEventHandlers(onCancel, handleModalCancel)}
onClick={composeEventHandlers(onClick, handleModalClick)}
onMouseDown={
closeOnBackdropClick
? composeEventHandlers(onMouseDown, handleModalMouseDown)
: onMouseDown
}
aria-labelledby={mergedAriaLabelledBy}
>
<ModalContextProvider
Expand Down

0 comments on commit a469a23

Please sign in to comment.