This commit is contained in:
07akioni
2026-07-27 12:58:20 +08:00
parent 3ee2982f85
commit 55fc87a7a0
10 changed files with 99 additions and 39 deletions

View File

@@ -18,16 +18,22 @@ export interface CodeBlockProps {
className?: string | undefined
}
async function writeClipboard(text: string): Promise<void> {
/** @returns true only when the host accepted the write. */
async function writeClipboard(text: string): Promise<boolean> {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
return
try {
await navigator.clipboard.writeText(text)
return true
} catch {
// Denied permissions / iframe policy — do not claim success.
return false
}
}
// jsdom and older hosts: best-effort execCommand path when present.
const exec = typeof document.execCommand === 'function'
? document.execCommand.bind(document)
: undefined
if (exec === undefined) return
if (exec === undefined) return false
const el = document.createElement('textarea')
el.value = text
el.setAttribute('readonly', '')
@@ -36,12 +42,12 @@ async function writeClipboard(text: string): Promise<void> {
document.body.appendChild(el)
el.select()
try {
exec('copy')
return exec('copy')
} catch {
// Clipboard unavailable (sandboxed iframe / denied permission); UI still
// flips to the ok label so the gesture is acknowledged.
return false
} finally {
el.remove()
}
el.remove()
}
export function CodeBlock({ code, lang, className }: CodeBlockProps) {
@@ -55,9 +61,11 @@ export function CodeBlock({ code, lang, className }: CodeBlockProps) {
/* v8 ignore next -- both arms always mount a <pre>; trimmed is the
typed fallback if the DOM shape ever diverges. */
const text = rootRef.current?.querySelector('pre')?.textContent ?? trimmed
void writeClipboard(text)
setCopied(true)
window.setTimeout(() => setCopied(false), 1000)
void writeClipboard(text).then((ok) => {
if (!ok) return
setCopied(true)
window.setTimeout(() => setCopied(false), 1000)
})
}, [copied, trimmed])
const body = html === undefined

View File

@@ -6,7 +6,7 @@
// alongside the rest of the markdown family.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { CodeBlock } from '../src/markdown/CodeBlock.tsx'
import { highlightToHtml } from '../src/markdown/highlight.ts'
@@ -65,6 +65,10 @@ describe('CodeBlock', () => {
expect(screen.getByText('ts')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '复制' }))
expect(writeText).toHaveBeenCalledWith('const a = 1')
// Flush the clipboard promise under fake timers before asserting the label.
await act(async () => {
await Promise.resolve()
})
expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
// While the ok label is showing, further clicks are no-ops.
fireEvent.click(screen.getByRole('button', { name: '复制成功' }))
@@ -73,7 +77,22 @@ describe('CodeBlock', () => {
expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
})
it('falls back to execCommand when clipboard.writeText is unavailable', () => {
it('does not claim success when clipboard.writeText rejects', async () => {
const writeText = vi.fn().mockRejectedValue(new Error('denied'))
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
})
render(<CodeBlock code="plain body" />)
fireEvent.click(screen.getByRole('button', { name: '复制' }))
await act(async () => {
await Promise.resolve()
})
expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
expect(screen.queryByRole('button', { name: '复制成功' })).toBeNull()
})
it('falls back to execCommand when clipboard.writeText is unavailable', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
@@ -86,9 +105,10 @@ describe('CodeBlock', () => {
render(<CodeBlock code="plain body" />)
fireEvent.click(screen.getByRole('button', { name: '复制' }))
expect(exec).toHaveBeenCalledWith('copy')
expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy()
})
it('still acknowledges copy when execCommand throws', () => {
it('does not claim success when execCommand throws or is absent', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
@@ -99,22 +119,20 @@ describe('CodeBlock', () => {
throw new Error('denied')
},
})
render(<CodeBlock code="plain body" />)
fireEvent.click(screen.getByRole('button', { name: '复制' }))
expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
})
const denied = render(<CodeBlock code="plain body" />)
fireEvent.click(denied.getByRole('button', { name: '复制' }))
await Promise.resolve()
expect(denied.getByRole('button', { name: '复制' })).toBeTruthy()
denied.unmount()
it('acknowledges copy when neither clipboard API nor execCommand exists', () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
})
Object.defineProperty(document, 'execCommand', {
configurable: true,
value: undefined,
})
render(<CodeBlock code="plain body" />)
fireEvent.click(screen.getByRole('button', { name: '复制' }))
expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
const absent = render(<CodeBlock code="plain body" />)
fireEvent.click(absent.getByRole('button', { name: '复制' }))
await Promise.resolve()
expect(absent.getByRole('button', { name: '复制' })).toBeTruthy()
expect(absent.queryByRole('button', { name: '复制成功' })).toBeNull()
})
})