Skip to content

Commit

Permalink
feat(templates): add a copy button to website template code blocks (#…
Browse files Browse the repository at this point in the history
…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
  • Loading branch information
MotorcycleEnjoyer authored Oct 23, 2024
1 parent 1caa383 commit 0fcbce3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions templates/website/src/blocks/Code/Component.client.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use client'
import { Highlight, themes } from 'prism-react-renderer'
import React from 'react'
import { CopyButton } from './CopyButton'

type Props = {
code: string
Expand All @@ -24,6 +25,7 @@ export const Code: React.FC<Props> = ({ code, language = '' }) => {
</span>
</div>
))}
<CopyButton code={code} />
</pre>
)}
</Highlight>
Expand Down
36 changes: 36 additions & 0 deletions templates/website/src/blocks/Code/CopyButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use client'
import { Button } from '@/components/ui/button'
import { CopyIcon } from '@payloadcms/ui'
import { useState } from 'react'

export function CopyButton({ code }: { code: string }) {
const [text, setText] = useState('Copy')

function updateCopyStatus() {
if (text === 'Copy') {
setText(() => 'Copied!')
setTimeout(() => {
setText(() => 'Copy')
}, 1000)
}
}

return (
<div className="flex justify-end align-middle">
<Button
className="flex gap-1"
variant={'secondary'}
onClick={async () => {
await navigator.clipboard.writeText(code)
updateCopyStatus()
}}
>
<p>{text}</p>

<div className="w-6 h-6 dark:invert">
<CopyIcon />
</div>
</Button>
</div>
)
}

0 comments on commit 0fcbce3

Please sign in to comment.