generated from mateusfg7/nextjs-setup
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(ui): add custom code component with copy button on post page
- Loading branch information
Showing
3 changed files
with
55 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
'use client' | ||
|
||
import { useState } from 'react' | ||
import { Copy, Check } from '@/shared/lib/phosphor-icons' | ||
|
||
export const CopyButton = ({ text }) => { | ||
const [isCopied, setIsCopied] = useState(false) | ||
|
||
const copy = async () => { | ||
await navigator.clipboard.writeText(text) | ||
setIsCopied(true) | ||
|
||
setTimeout(() => { | ||
setIsCopied(false) | ||
}, 5000) | ||
} | ||
|
||
return ( | ||
<button | ||
disabled={isCopied} | ||
onClick={copy} | ||
className={`absolute bottom-0 right-0 flex items-center gap-1 rounded p-2 leading-none hover:opacity-100 ${ | ||
isCopied | ||
? 'bg-green-100/40 text-green-800 opacity-100 dark:bg-green-300/10 dark:text-green-500' | ||
: 'cursor-pointer bg-neutral-300 text-neutral-600 opacity-40 dark:bg-neutral-800 dark:text-neutral-400' | ||
}`} | ||
> | ||
{isCopied ? <Check /> : <Copy />} | ||
</button> | ||
) | ||
} |
21 changes: 21 additions & 0 deletions
21
src/app/(blog)/post/[slug]/components/pretty-code-element.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { ReactNode } from 'react' | ||
import { CopyButton } from './copy-button' | ||
|
||
interface Props { | ||
children: ReactNode | ||
} | ||
|
||
export function PrettyCodeElement({ children, ...props }: Props) { | ||
if (!('data-rehype-pretty-code-fragment' in props)) | ||
return <div {...props}>{children}</div> | ||
if (!('raw' in props)) return <div {...props}>{children}</div> | ||
|
||
const raw = props.raw as string | ||
|
||
return ( | ||
<div {...props} className="relative"> | ||
{children} | ||
<CopyButton text={raw} /> | ||
</div> | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters