mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-25 15:40:49 +08:00
Add code block copy button with toast
This commit is contained in:
@@ -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) + '...'
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user