fix(chat): support code block copy feedback (#349)

This commit is contained in:
Lanke
2026-04-30 18:36:00 +08:00
committed by GitHub
parent e82674039c
commit 05f15da90b
5 changed files with 66 additions and 20 deletions
@@ -1,4 +1,5 @@
import hljs from 'highlight.js'
import { copyToClipboard } from '@/utils/clipboard'
const LANGUAGE_ALIASES: Record<string, string> = {
shellscript: 'bash',
@@ -80,27 +81,23 @@ export function renderHighlightedCodeBlock(
return `<pre class="hljs-code-block"><div class="code-header">${languageLabelHtml}<button type="button" class="copy-btn" data-copy-code="true">${escapeHtml(copyLabel)}</button></div><code class="hljs language-${sanitizeLanguageClass(codeClassLanguage)}">${highlighted}</code></pre>`
}
export async function copyTextToClipboard(text: string): Promise<void> {
try {
await navigator.clipboard?.writeText?.(text)
} catch {
// Ignore clipboard failures; the code block still renders safely.
}
export async function copyTextToClipboard(text: string): Promise<boolean> {
return copyToClipboard(text)
}
export async function handleCodeBlockCopyClick(event: MouseEvent): Promise<void> {
export async function handleCodeBlockCopyClick(event: MouseEvent): Promise<boolean | null> {
const target = event.target
if (!(target instanceof HTMLElement)) return
if (!(target instanceof HTMLElement)) return null
const button = target.closest<HTMLElement>('[data-copy-code="true"]')
if (!button) return
if (!button) return null
event.preventDefault()
const block = button.closest('.hljs-code-block')
const code = block?.querySelector('code')
const text = code?.textContent ?? ''
if (!text) return
if (!text) return false
await copyTextToClipboard(text)
return copyTextToClipboard(text)
}