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 code copy button #97

Merged
merged 2 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import disableBlocks from './plugins/disableBlocks'

const envAdapter = () => {
switch (process.env.OUTPUT) {
case 'vercel': return vercel()
case 'vercel': return vercel({ analytics: false }) // Set `analytics` to `true` if you want to use Vercel Analytics
case 'netlify': return netlify()
default: return node({ mode: 'standalone' })
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"solid-emoji-picker": "^0.2.0",
"solid-js": "1.7.7",
"solid-transition-group": "^0.2.2",
"solidjs-use": "^2.3.0",
"unified": "^10.1.2"
},
"devDependencies": {
Expand Down
43 changes: 37 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 68 additions & 2 deletions src/components/Markdown.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Show } from 'solid-js'
import { Show, createSignal, createEffect } from 'solid-js'
import { useClipboard, useEventListener } from 'solidjs-use'
import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkGfm from 'remark-gfm'
Expand Down Expand Up @@ -31,7 +32,72 @@ const parseMarkdown = (raw: string) => {
}

export default (props: Props) => {
const htmlString = () => props.showRawCode ? props.text : parseMarkdown(props.text)
const [source] = createSignal('')
const { copy } = useClipboard({ source, copiedDuring: 1000 })
const [copied, setCopied] = createSignal<Array<boolean>>([])

useEventListener('click', (e) => {
const el = e.target as HTMLElement
let code = null
let index = -1

if (el.matches('div > div.code-copy-btn')) {
code = decodeURIComponent(el.dataset.code!)
index = parseInt(el.dataset.index!)
copy(code)
}
if (el.matches('div > div.code-copy-btn > i')) {
code = decodeURIComponent(el.parentElement?.dataset.code!)
index = parseInt(el.parentElement?.dataset.index!)
copy(code)
}

if (index >= 0) {
const newCopied = [...copied()]
newCopied[index] = true
setCopied(newCopied)

// Reset the button state after 1 second
setTimeout(() => {
const resetCopied = [...copied()]
resetCopied[index] = false
setCopied(resetCopied)
}, 1000)
}
})

const htmlString = () => {
if (props.showRawCode) return props.text

const raw = parseMarkdown(props.text)

// Replace the code block with a custom HTML structure that includes a copy button
const codeBlockRegex = /<pre[^>]*><code[^>]*>([\s\S]*?)<\/code><\/pre>/g
let index = 0
const newHtml = raw.replace(codeBlockRegex, (match) => {
const parser = new DOMParser()
const doc = parser.parseFromString(match, 'text/html')
const codeElement = doc.querySelector('code')
const code = codeElement ? codeElement.textContent : ''

const result = `<div relative>
<div data-code=${encodeURIComponent(code)} data-index=${index} class="code-copy-btn group">
${copied()[index] === true ? '<i class="i-carbon-checkmark"></i>' : '<i class="i-carbon-copy"></i>'}
</div>
${match}
</div>`
index++
return result
})

return newHtml
}

createEffect(() => {
const codeBlocks = props.text.match(/```[\s\S]*?```/g)
const initialCopied = codeBlocks ? new Array(codeBlocks.length).fill(false) : []
setCopied(initialCopied)
})

return (
<Show when={props.showRawCode} fallback={<div class={props.class ?? ''} innerHTML={htmlString()} />}>
Expand Down
2 changes: 2 additions & 0 deletions unocss.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ export default defineConfig({
'fi': 'flex items-center',
'fcc': 'fc items-center',
'fb': 'flex justify-between',
'code-copy-btn': 'absolute z-3 op-90 w-8 h-8 p-1 top-12px right-12px bg-light-300 dark:bg-dark-300 hover-text-emerald-600 fcc border rounded-md b-transparent cursor-pointer',
'code-copy-tips': 'absolute z-1 op-0 px-2 py-1 -top-8 bg-dark-600 dark:bg-dark fcc box-border rounded-md text-xs c-white transition-opacity duration-300 whitespace-nowrap',
}],
preflights: [{
layer: 'base',
Expand Down