复制按钮

为代码块添加复制按钮。

content.md
```js
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}
```
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}

Implementation

首先我们创建按钮组件:

button.tsx
"use client"
import { Copy, Check } from "lucide-react"
import { useState } from "react"
export function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false)
return (
<button
className=""
aria-label="复制到剪贴板"
onClick={() => {
navigator.clipboard.writeText(text)
setCopied(true)
setTimeout(() => setCopied(false), 1200)
}}
>
{copied ? <Check size={16} /> : <Copy size={16} />}
</button>
)
}

然后在渲染代码块时使用它:

code.tsx
import { Pre, RawCode, highlight } from "codehike/code"
import { CopyButton } from "./button"
async function Code({ codeblock }: { codeblock: RawCode }) {
const highlighted = await highlight(codeblock, "github-dark")
return (
<div className="">
<CopyButton text={highlighted.code} />
<Pre className="" code={highlighted} />
</div>
)
}