All files / src/hooks use-dialog.ts

80.95% Statements 17/21
100% Branches 4/4
66.66% Functions 2/3
80.95% Lines 17/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 331x             1x 22x   22x 2x 2x   22x 22x   22x           22x 22x 22x   22x 22x 22x 22x 22x  
import {RefObject, useEffect, useRef} from "react";
 
export interface DialogHook {
    dialogRef: RefObject<HTMLDialogElement | null>;
    openDialog: () => void;
}
 
export function useDialog(): DialogHook {
    const dialogRef = useRef<HTMLDialogElement>(null);
 
    function openDialog() {
        dialogRef.current?.showModal();
    }
 
    useEffect(() => {
        const dialog = dialogRef.current;
 
        function closeDialog(event: MouseEvent) {
            if (event.target === dialog) {
                dialog?.close();
            }
        }
 
        dialog?.addEventListener("click", closeDialog);
        return () => dialog?.removeEventListener("click", closeDialog);
    }, []);
 
    return {
        dialogRef,
        openDialog,
    };
}