Skip to content

Commit 0fcbce3

Browse files
feat(templates): add a copy button to website template code blocks (#8794)
## WHAT - Adds a copy code button to the Code Blocks in V3 Beta Website Template. - Uses the existing button from `@/components/ui/button` - SVG from this website: https://uxwing.com/copy-icon/ https://github.com/user-attachments/assets/2f6e720a-de37-40b5-a3bf-c748a69502b5 ## WHY - Copy-Code button is convenient for users looking at code blocks in tutorials/documentation/etc ## ISSUES - Button color invert isn't immediate on refresh in darkmode https://github.com/user-attachments/assets/f1093a27-73dd-47cb-8fc9-2f4bc301b80c
1 parent 1caa383 commit 0fcbce3

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

templates/website/src/blocks/Code/Component.client.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use client'
22
import { Highlight, themes } from 'prism-react-renderer'
33
import React from 'react'
4+
import { CopyButton } from './CopyButton'
45

56
type Props = {
67
code: string
@@ -24,6 +25,7 @@ export const Code: React.FC<Props> = ({ code, language = '' }) => {
2425
</span>
2526
</div>
2627
))}
28+
<CopyButton code={code} />
2729
</pre>
2830
)}
2931
</Highlight>
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use client'
2+
import { Button } from '@/components/ui/button'
3+
import { CopyIcon } from '@payloadcms/ui'
4+
import { useState } from 'react'
5+
6+
export function CopyButton({ code }: { code: string }) {
7+
const [text, setText] = useState('Copy')
8+
9+
function updateCopyStatus() {
10+
if (text === 'Copy') {
11+
setText(() => 'Copied!')
12+
setTimeout(() => {
13+
setText(() => 'Copy')
14+
}, 1000)
15+
}
16+
}
17+
18+
return (
19+
<div className="flex justify-end align-middle">
20+
<Button
21+
className="flex gap-1"
22+
variant={'secondary'}
23+
onClick={async () => {
24+
await navigator.clipboard.writeText(code)
25+
updateCopyStatus()
26+
}}
27+
>
28+
<p>{text}</p>
29+
30+
<div className="w-6 h-6 dark:invert">
31+
<CopyIcon />
32+
</div>
33+
</Button>
34+
</div>
35+
)
36+
}

0 commit comments

Comments
 (0)