fix(ui): prevent memory leak and ensure Safari/iOS compatibility in image copying

This commit is contained in:
yiling
2026-05-30 13:46:25 +08:00
parent ec14e12b3f
commit f6656dce2f
+40 -29
View File
@@ -138,40 +138,51 @@ export function FileViewer({
const webpUrl = bestUrl const webpUrl = bestUrl
if (!webpUrl) return if (!webpUrl) return
try { try {
const response = await fetch(webpUrl) // To support Safari and iOS, we must invoke navigator.clipboard.write
const blob = await response.blob() // synchronously inside the click handler. We can pass a promise to ClipboardItem
// which resolves to the Blob asynchronously.
const copyPromise = (async () => {
const response = await fetch(webpUrl)
const blob = await response.blob()
const img = new Image() const img = new Image()
img.crossOrigin = 'anonymous' img.crossOrigin = 'anonymous'
img.src = URL.createObjectURL(blob) const objectUrl = URL.createObjectURL(blob)
await new Promise((resolve, reject) => { img.src = objectUrl
img.onload = resolve
img.onerror = reject
})
const canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Could not get canvas context')
ctx.drawImage(img, 0, 0)
canvas.toBlob(async (pngBlob) => {
if (!pngBlob) return
try { try {
await navigator.clipboard.write([ await new Promise((resolve, reject) => {
new ClipboardItem({ img.onload = resolve
'image/png': pngBlob, img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e)))
}), })
])
setCopied(true) const canvas = document.createElement('canvas')
setTimeout(() => setCopied(false), 2000) canvas.width = img.width
} catch (err) { canvas.height = img.height
console.error('Failed to copy image to clipboard:', err) const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Could not get canvas context')
ctx.drawImage(img, 0, 0)
const pngBlob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob(resolve, 'image/png')
})
if (!pngBlob) throw new Error('Failed to convert image to PNG')
return pngBlob
} finally {
URL.revokeObjectURL(objectUrl)
} }
}, 'image/png') })()
await navigator.clipboard.write([
new ClipboardItem({
'image/png': copyPromise,
}),
])
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (err) { } catch (err) {
console.error('Failed to copy image:', err) console.error('Failed to copy image to clipboard:', err)
} }
} }