new util for modal edge cases

This commit is contained in:
pablodanswer
2024-08-27 09:31:25 -07:00
committed by Chris Weaver
parent b36cd4937f
commit feaa85f764
4 changed files with 26 additions and 3 deletions

View File

@@ -3,6 +3,7 @@ import { Divider } from "@tremor/react";
import { FiX } from "react-icons/fi";
import { IconProps } from "./icons/icons";
import { useRef } from "react";
import { isEventWithinRef } from "@/lib/contains";
interface ModalProps {
icon?: ({ size, className }: IconProps) => JSX.Element;
@@ -33,7 +34,8 @@ export function Modal({
if (
onOutsideClick &&
modalRef.current &&
!modalRef.current.contains(e.target as Node)
!modalRef.current.contains(e.target as Node) &&
!isEventWithinRef(e.nativeEvent, modalRef)
) {
onOutsideClick();
}

View File

@@ -552,7 +552,6 @@ export function SelectorFormField({
<div className="mb-4">
{label && <Label>{label}</Label>}
{subtext && <SubLabel>{subtext}</SubLabel>}
<div className="mt-2">
<DefaultDropdown
options={options}

View File

@@ -1,5 +1,6 @@
"use client";
import { XIcon } from "@/components/icons/icons";
import { isEventWithinRef } from "@/lib/contains";
import { useRef } from "react";
export const ModalWrapper = ({
@@ -19,7 +20,8 @@ export const ModalWrapper = ({
if (
onClose &&
modalRef.current &&
!modalRef.current.contains(e.target as Node)
!modalRef.current.contains(e.target as Node) &&
!isEventWithinRef(e.nativeEvent, modalRef)
) {
onClose();
}

View File

@@ -1,3 +1,5 @@
import { RefObject } from "react";
interface SomeNonNestedObject {
[key: string]: any;
}
@@ -31,3 +33,21 @@ export function containsObject(
// NOTE: only works for non-nested objects
return list.some((item) => objectsAreEquivalent(item, obj));
}
export function isEventWithinRef(
event: MouseEvent | TouchEvent,
ref: RefObject<HTMLElement>
): boolean {
if (!ref.current) return false;
const rect = ref.current.getBoundingClientRect();
const clientX = "touches" in event ? event.touches[0].clientX : event.clientX;
const clientY = "touches" in event ? event.touches[0].clientY : event.clientY;
return (
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= rect.bottom
);
}