Add hints
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import { useState, useRef, useEffect, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
interface HintProps {
|
||||
hint: ReactNode;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function Hint({ hint, children }: HintProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [pos, setPos] = useState({ top: 0, left: 0 });
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const tooltipRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const updatePos = () => {
|
||||
if (!wrapperRef.current?.children[0]) return;
|
||||
const rect = wrapperRef.current.children[0].getBoundingClientRect();
|
||||
setPos({
|
||||
top: rect.bottom,
|
||||
left: rect.left + rect.width / 2,
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !tooltipRef.current) return;
|
||||
const tip = tooltipRef.current.getBoundingClientRect();
|
||||
const margin = 8;
|
||||
|
||||
setPos((prev) => ({
|
||||
top: tip.top,
|
||||
left: Math.min(Math.max(prev.left, tip.width / 2 + margin), window.innerWidth - tip.width / 2 - margin),
|
||||
}));
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
style={{ display: "contents" }}
|
||||
onMouseEnter={() => {
|
||||
updatePos();
|
||||
setOpen(true);
|
||||
}}
|
||||
onMouseLeave={() => setOpen(false)}
|
||||
>
|
||||
{children}
|
||||
{open &&
|
||||
createPortal(
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
style={{
|
||||
position: "fixed",
|
||||
top: pos.top,
|
||||
left: pos.left,
|
||||
transform: "translateX(-50%)",
|
||||
background: "#141414",
|
||||
border: "1px solid #4af626",
|
||||
color: "#fff",
|
||||
padding: "6px 10px",
|
||||
fontSize: "12px",
|
||||
maxWidth: "260px",
|
||||
pointerEvents: "none",
|
||||
zIndex: 9999,
|
||||
whiteSpace: "pre-wrap",
|
||||
}}
|
||||
>
|
||||
{hint}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user