feat: add copy button to code blocks in blog posts

This commit is contained in:
Mauricio Siu
2025-03-02 18:02:23 -06:00
parent 350b36d97a
commit 06b33b6d8d
2 changed files with 40 additions and 4 deletions

View File

@@ -1,3 +1,4 @@
import { CopyButton } from "@/components/ui/copy-button";
import { getPost, getPosts } from "@/lib/ghost";
import type { Metadata, ResolvingMetadata } from "next";
import { getTranslations } from "next-intl/server";
@@ -121,10 +122,13 @@ async function CodeBlock(props: LanguageProps) {
});
return (
<div
dangerouslySetInnerHTML={{ __html: out }}
className="text-sm p-4 rounded-lg bg-[#18191F]"
/>
<div className="group relative">
<CopyButton text={format} />
<div
dangerouslySetInnerHTML={{ __html: out }}
className="text-sm p-4 rounded-lg bg-[#18191F]"
/>
</div>
);
}
export default async function BlogPostPage({ params }: Props) {

View File

@@ -0,0 +1,32 @@
"use client";
import { CheckIcon, CopyIcon } from "lucide-react";
import { useState } from "react";
interface CopyButtonProps {
text: string;
}
export function CopyButton({ text }: CopyButtonProps) {
const [isCopied, setIsCopied] = useState(false);
const copy = async () => {
await navigator.clipboard.writeText(text);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
};
return (
<button
className="absolute right-4 top-4 z-20 h-8 w-8 rounded-md border bg-background/50 p-1.5 backdrop-blur-sm transition-all hover:bg-background/80"
onClick={copy}
type="button"
>
{isCopied ? (
<CheckIcon className="h-full w-full text-green-500" />
) : (
<CopyIcon className="h-full w-full text-gray-400" />
)}
</button>
);
}