shelving
Version:
Toolkit for using data in JavaScript.
29 lines (28 loc) • 1.68 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { XMarkIcon } from "@heroicons/react/24/solid";
import { memo, Suspense, useEffect, useRef } from "react";
import { getModuleClass } from "../util/css.js";
import styles from "./Dialog.module.css";
export const Dialog = memo(({ children, onClose, ...props }) => {
const ref = useRef(null);
useEffect(() => {
ref.current?.showModal();
}, []);
return (_jsx(Suspense, { fallback: null, children: _jsxs("dialog", { ref: ref, className: styles.dialog, onClick: _closeOnBackdropClick, onClose: onClose, ...props, children: [children, _jsx("div", { className: styles.close, children: _jsx(DialogCloseButton, { plain: true }) })] }) }));
});
/** When the user clicks anywhere on a `<dialog>` element (and the click isn't on a link etc), then close the dialog. */
function _closeOnBackdropClick({ currentTarget, target }) {
// Close the dialog when clicking on the dialog itself (but not its children).
if (currentTarget === target)
currentTarget.close();
// Close the dialog when clicking on links or buttons in a `<nav>` element.
if (target instanceof Element && target.closest("a:any-link, nav button:enabled"))
currentTarget.close();
}
/** Button that closes its wrapping dialog with an X icon. */
export function DialogCloseButton({ children = _jsx(XMarkIcon, {}), ...variants }) {
return (_jsx("button", { type: "button", title: "Close", className: getModuleClass(styles, "button", variants), onClick: _closeOnButtonClick, children: children }));
}
function _closeOnButtonClick({ currentTarget }) {
currentTarget.closest("dialog")?.close();
}