Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add copy to clipboard button to code blocks #104

Merged
merged 3 commits into from
Jan 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions app/components/CodeBlock.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import type { FC, HTMLAttributes, ReactElement } from 'react'
import {
useState,
type FC,
type HTMLAttributes,
type ReactElement,
} from 'react'
import invariant from 'tiny-invariant'
import type { Language } from 'prism-react-renderer'
import { Highlight, Prism } from 'prism-react-renderer'
import { FaCopy } from 'react-icons/fa'
import { svelteHighlighter } from '~/utils/svelteHighlighter'
// Add back additional language support after `prism-react` upgrade
;(typeof global !== 'undefined' ? global : window).Prism = Prism
require('prismjs/components/prism-diff')

Check warning on line 14 in app/components/CodeBlock.tsx

View workflow job for this annotation

GitHub Actions / PR

Do not use "require"
require('prismjs/components/prism-bash')

Check warning on line 15 in app/components/CodeBlock.tsx

View workflow job for this annotation

GitHub Actions / PR

Do not use "require"

// @ts-ignore Alias markup as vue highlight
Prism.languages.vue = Prism.languages.markup
Expand All @@ -25,13 +31,29 @@

export const CodeBlock: FC<HTMLAttributes<HTMLPreElement>> = ({ children }) => {
invariant(!!children, 'children is required')
const [copied, setCopied] = useState(false)
const child = children as ReactElement
const className = child.props?.className || ''
const userLang = getLanguageFromClassName(className)
const lang = isLanguageSupported(userLang) ? userLang : 'bash'
const code = child.props.children || ''
return (
<div className="w-full max-w-full">
<div className="w-full max-w-full relative">
<button
className="absolute right-1 top-3 z-10 p-2 group flex items-center"
onClick={() => {
setCopied(true)
navigator.clipboard.writeText(code.trim())
setTimeout(() => setCopied(false), 2000)
}}
aria-label="Copy code to clipboard"
>
{copied ? (
<span className="text-xs">Copied!</span>
) : (
<FaCopy className="text-gray-500 group-hover:text-gray-100 dark:group-hover:text-gray-200 transition duration-200" />
)}
</button>
<Highlight code={code.trim()} language={lang}>
{({ className, tokens, getLineProps, getTokenProps }) => (
<div className="relative not-prose">
Expand Down
Loading