Skip to content

Commit

Permalink
Forbedre lesbarhet og fjern behov for midlertidige objekter
Browse files Browse the repository at this point in the history
  • Loading branch information
cskrov committed Feb 23, 2024
1 parent f22d48e commit 068ee75
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
28 changes: 15 additions & 13 deletions @navikt/core/react/src/modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import ModalBody from "./ModalBody";
import ModalFooter from "./ModalFooter";
import ModalHeader from "./ModalHeader";
import {
clickWasOutside,
MouseCoordinates,
coordsAreInside,
getCloseHandler,
useBodyScrollLock,
} from "./ModalUtils";
Expand Down Expand Up @@ -151,33 +152,34 @@ export const Modal = forwardRef<HTMLDialogElement, ModalProps>(
...(!isWidthPreset ? { width } : {}),
};

const mouseClickStart = useRef({ x: 0, y: 0 });
const mouseClickStart = useRef<MouseCoordinates>({
clientX: 0,
clientY: 0,
});
const handleModalMouseDown: React.MouseEventHandler<HTMLDialogElement> = (
event,
) => {
mouseClickStart.current.x = event.clientX;
mouseClickStart.current.y = event.clientY;
mouseClickStart.current = event;
};

const shouldHandleModalClick = closeOnBackdropClick && !needPolyfill;

/**
* @note `closeOnBackdropClick` has issues on polyfill when nesting modals (DatePicker)
*/
const handleModalClick = (event: React.MouseEvent<HTMLDialogElement>) => {
if (event.target !== modalRef.current) {
const handleModalClick = (
endEvent: React.MouseEvent<HTMLDialogElement>,
) => {
if (endEvent.target !== modalRef.current) {
return;
}

const modalRect = modalRef.current.getBoundingClientRect();

if (!clickWasOutside(mouseClickStart.current, modalRect)) {
return;
}

const end = { x: event.clientX, y: event.clientY };

if (!clickWasOutside(end, modalRect)) {
if (
coordsAreInside(mouseClickStart.current, modalRect) ||
coordsAreInside(endEvent, modalRect)
) {
return;
}

Expand Down
21 changes: 13 additions & 8 deletions @navikt/core/react/src/modal/ModalUtils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import React from "react";
import type { ModalProps } from "./types";

export const clickWasOutside = (
cords: { x: number; y: number },
rect: DOMRect,
) =>
cords.x < rect.x ||
cords.y < rect.y ||
cords.x > rect.x + rect.width ||
cords.y > rect.y + rect.height;
export interface MouseCoordinates {
clientX: number;
clientY: number;
}

export const coordsAreInside = (
{ clientX, clientY }: MouseCoordinates,
{ x, y, width, height }: DOMRect,
) => {
if (clientX < x || clientY < y) return false;
if (clientX > x + width || clientY > y + height) return false;
return true;
};

export function getCloseHandler(
modalRef: React.RefObject<HTMLDialogElement>,
Expand Down

0 comments on commit 068ee75

Please sign in to comment.