tailwind-nextjs-blog/components/Pre.tsx

78 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-10-17 23:37:01 +08:00
import { useState, useRef, ReactNode } from 'react';
2022-07-17 21:40:41 +08:00
interface Props {
2022-10-17 23:37:01 +08:00
children: ReactNode;
}
const Pre = ({ children }: Props) => {
2022-10-17 23:37:01 +08:00
const textInput = useRef(null);
const [hovered, setHovered] = useState(false);
const [copied, setCopied] = useState(false);
2022-07-17 21:40:41 +08:00
const onEnter = () => {
2022-10-17 23:37:01 +08:00
setHovered(true);
};
2022-07-17 21:40:41 +08:00
const onExit = () => {
2022-10-17 23:37:01 +08:00
setHovered(false);
setCopied(false);
};
2022-07-17 21:40:41 +08:00
const onCopy = () => {
2022-10-17 23:37:01 +08:00
setCopied(true);
navigator.clipboard.writeText(textInput.current.textContent);
2022-07-17 21:40:41 +08:00
setTimeout(() => {
2022-10-17 23:37:01 +08:00
setCopied(false);
}, 2000);
};
2022-07-17 21:40:41 +08:00
return (
2022-10-17 23:37:01 +08:00
<div
ref={textInput}
onMouseEnter={onEnter}
onMouseLeave={onExit}
className="relative">
2022-07-17 21:40:41 +08:00
{hovered && (
<button
aria-label="Copy code"
type="button"
className={`absolute right-2 top-2 h-8 w-8 rounded border-2 bg-gray-700 p-1 dark:bg-gray-800 ${
copied
? 'border-green-400 focus:border-green-400 focus:outline-none'
: 'border-gray-300'
}`}
2022-10-17 23:37:01 +08:00
onClick={onCopy}>
2022-07-17 21:40:41 +08:00
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
stroke="currentColor"
fill="none"
2022-10-17 23:37:01 +08:00
className={copied ? 'text-green-400' : 'text-gray-300'}>
2022-07-17 21:40:41 +08:00
{copied ? (
<>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"
/>
</>
) : (
<>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
/>
</>
)}
</svg>
</button>
)}
<pre>{children}</pre>
2022-07-17 21:40:41 +08:00
</div>
2022-10-17 23:37:01 +08:00
);
};
2022-07-17 21:40:41 +08:00
2022-10-17 23:37:01 +08:00
export default Pre;