Add code block copy button with toast

This commit is contained in:
Tim
2025-07-21 22:47:57 +08:00
parent ae76260d8f
commit 9c0a63d054
5 changed files with 61 additions and 13 deletions

View File

@@ -1,15 +1,39 @@
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { toast } from '../main'
const md = new MarkdownIt({
html: false,
linkify: true,
breaks: true
breaks: true,
highlight: (str, lang) => {
let code = ''
if (lang && hljs.getLanguage(lang)) {
code = hljs.highlight(str, { language: lang, ignoreIllegals: true }).value
} else {
code = hljs.highlightAuto(str).value
}
return `<pre class="code-block"><button class="copy-code-btn">复制</button><code class="hljs language-${lang || ''}">${code}</code></pre>`
}
})
export function renderMarkdown(text) {
return md.render(text || '')
}
export function handleMarkdownClick(e) {
if (e.target.classList.contains('copy-code-btn')) {
const pre = e.target.closest('pre')
const codeEl = pre && pre.querySelector('code')
if (codeEl) {
navigator.clipboard.writeText(codeEl.innerText).then(() => {
toast.success('已复制')
})
}
}
}
export function stripMarkdown(text) {
const html = md.render(text || '')
const el = document.createElement('div')
@@ -24,4 +48,4 @@ export function stripMarkdownLength(text, length) {
}
// 截断并加省略号
return plain.slice(0, length) + '...'
}
}