Skip to content

Commit

Permalink
feat(ui): add custom code component with copy button on post page
Browse files Browse the repository at this point in the history
  • Loading branch information
mateusfg7 committed Jun 19, 2023
1 parent 061b378 commit 2b2fb01
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
31 changes: 31 additions & 0 deletions src/app/(blog)/post/[slug]/components/copy-button.tsx
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 src/app/(blog)/post/[slug]/components/pretty-code-element.tsx
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>
)
}
4 changes: 3 additions & 1 deletion src/app/(blog)/post/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Folder, CalendarBlank, Clock, Tag } from '@/shared/lib/phosphor-icons'
import { Date } from '@/shared/components/date'
import { TopButton } from './components/top-button'
import { Anchor } from './components/anchor'
import { PrettyCodeElement } from './components/pretty-code-element'

interface Props {
params: { slug: string }
Expand Down Expand Up @@ -38,7 +39,8 @@ const mdxComponents: MDXComponents = {
</Anchor>
) : (
<a href={href}>{children}</a>
)
),
div: PrettyCodeElement
}

export default function Page({ params }: Props) {
Expand Down

0 comments on commit 2b2fb01

Please sign in to comment.