Files
lixiyu-net/components/mdx/PreWrapper.tsx

55 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-12-25 17:21:39 +08:00
import { useRef, useState } from "react";
2024-04-03 22:08:27 +08:00
import { FaCheck } from "react-icons/fa";
import { IoCopyOutline } from "react-icons/io5";
import { Button } from "../ui/button";
2023-12-25 17:21:39 +08:00
const PreWrapper = ({ children }: { children: JSX.Element }) => {
const textInput = useRef(null);
const [hovered, setHovered] = useState(false);
const [copied, setCopied] = useState(false);
const onEnter = () => {
setHovered(true);
};
const onExit = () => {
setHovered(false);
setCopied(false);
};
const onCopy = () => {
setCopied(true);
//@ts-ignore
textInput.current && navigator.clipboard.writeText(textInput.current.textContent);
};
return (
2024-08-12 17:39:38 +08:00
<div
className="flat-scrollbar-normal relative"
2024-08-12 17:39:38 +08:00
dir="ltr"
onMouseLeave={onExit}
onMouseMove={onEnter}
ref={textInput}
>
2023-12-25 17:21:39 +08:00
{hovered && (
2024-04-03 22:08:27 +08:00
<Button
2023-12-25 17:21:39 +08:00
aria-label="Copy code"
className={`absolute top-2 right-2 h-8 w-8 rounded p-1 ${
copied ? "text-green-500 hover:text-green-500" : ""
}`}
2023-12-25 17:21:39 +08:00
onClick={onCopy}
2024-04-03 22:08:27 +08:00
variant={"outline"}
2023-12-25 17:21:39 +08:00
>
2024-04-03 22:08:27 +08:00
{copied ? <FaCheck /> : <IoCopyOutline />}
</Button>
2023-12-25 17:21:39 +08:00
)}
<pre
translate="no"
className="flat-scrollbar-normal not-prose rounded-md bg-[#F6F8FA] p-2 text-sm selection:bg-gray-300 selection:text-inherit dark:bg-[#0d1117] dark:selection:bg-gray-700"
>
2024-04-03 22:08:27 +08:00
{children}
</pre>
2023-12-25 17:21:39 +08:00
</div>
);
};
export default PreWrapper;