File size: 1,552 Bytes
c6aaacb | 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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import React, { createContext, useContext, useState, useRef, useEffect } from "react";
const Ctx = createContext(null);
export function Popover({ children }) {
const [open, setOpen] = useState(false);
const triggerRef = useRef(null);
const value = { open, setOpen, triggerRef };
useEffect(() => {
function onDocClick(e) {
if (!triggerRef.current) return;
const content = document.getElementById("__popover-content");
if (content && (content.contains(e.target) || triggerRef.current.contains(e.target))) return;
setOpen(false);
}
document.addEventListener("mousedown", onDocClick);
return () => document.removeEventListener("mousedown", onDocClick);
}, []);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}
export function PopoverTrigger({ asChild, children }) {
const { setOpen, triggerRef } = useContext(Ctx);
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children, {
ref: triggerRef,
onClick: (e) => {
children.props.onClick && children.props.onClick(e);
setOpen((o) => !o);
},
});
}
return (
<button ref={triggerRef} onClick={() => setOpen((o) => !o)}>
{children}
</button>
);
}
export function PopoverContent({ className = "", children }) {
const { open } = useContext(Ctx);
if (!open) return null;
return (
<div
id="__popover-content"
className={`absolute z-50 mt-2 rounded-xl border bg-white shadow-lg ${className}`}
>
{children}
</div>
);
}
|