feat(file-browser): add context-aware copy submenu (#517)

* feat(file-browser): add context-aware copy submenu

* refactor(file-browser): address code review feedback for copy submenu

* fix(webui): align submenu trigger text and widen file context menu

* test(e2e): guard clipboard permissions in copy-menu spec for cross-browser support
This commit is contained in:
Yiling-J
2026-11-05 09:57:34 +08:00
committed by GitHub
parent 2ecbd49d18
commit 0dc0bbeb03
30 changed files with 2285 additions and 106 deletions
+91 -1
View File
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { copyToClipboard } from './clipboard'
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from './clipboard'
describe('copyToClipboard', () => {
const originalClipboard = navigator.clipboard
@@ -49,3 +49,93 @@ describe('copyToClipboard', () => {
expect(execCommandFn).toHaveBeenCalledWith('copy')
})
})
describe('copyToClipboardDeferred', () => {
it('uses navigator.clipboard.write with ClipboardItem when available', async () => {
const mockWrite = vi.fn().mockResolvedValue(undefined)
class MockClipboardItem {
types: Record<string, unknown>
constructor(types: Record<string, unknown>) {
this.types = types
}
}
Object.defineProperty(globalThis, 'ClipboardItem', {
value: MockClipboardItem,
configurable: true,
writable: true,
})
Object.defineProperty(navigator, 'clipboard', {
value: { write: mockWrite },
configurable: true,
writable: true,
})
const success = await copyToClipboardDeferred(Promise.resolve('deferred text'))
expect(success).toBe(true)
expect(mockWrite).toHaveBeenCalledTimes(1)
})
it('falls back to copyToClipboard when ClipboardItem is unavailable', async () => {
const mockWriteText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(globalThis, 'ClipboardItem', {
value: undefined,
configurable: true,
writable: true,
})
Object.defineProperty(navigator, 'clipboard', {
value: { writeText: mockWriteText },
configurable: true,
writable: true,
})
const success = await copyToClipboardDeferred(Promise.resolve('fallback deferred text'))
expect(success).toBe(true)
expect(mockWriteText).toHaveBeenCalledWith('fallback deferred text')
})
})
describe('copyImageToClipboard', () => {
it('returns false when clipboard API is unavailable', async () => {
Object.defineProperty(navigator, 'clipboard', {
value: undefined,
configurable: true,
writable: true,
})
const success = await copyImageToClipboard('http://example.com/image.png')
expect(success).toBe(false)
})
it('accepts a Promise resolving to a URL and writes to clipboard', async () => {
const mockWrite = vi.fn().mockResolvedValue(undefined)
class MockClipboardItem {
types: Record<string, unknown>
constructor(types: Record<string, unknown>) {
this.types = types
}
}
Object.defineProperty(globalThis, 'ClipboardItem', {
value: MockClipboardItem,
configurable: true,
writable: true,
})
Object.defineProperty(navigator, 'clipboard', {
value: { write: mockWrite },
configurable: true,
writable: true,
})
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => {
return new Response(new Blob(['fake-image-bytes'], { type: 'image/webp' }))
})
const success = await copyImageToClipboard(Promise.resolve('http://example.com/image.png'))
expect(success).toBe(true)
expect(mockWrite).toHaveBeenCalledTimes(1)
fetchSpy.mockRestore()
})
})
+116
View File
@@ -41,3 +41,119 @@ export async function copyToClipboard(text: string): Promise<boolean> {
return false
}
}
/**
* Copies text resolved asynchronously to clipboard, using ClipboardItem to preserve
* Safari's transient user activation when fetching links.
*/
export async function copyToClipboardDeferred(textPromise: Promise<string>): Promise<boolean> {
if (
typeof navigator !== 'undefined' &&
navigator.clipboard &&
typeof navigator.clipboard.write === 'function' &&
typeof ClipboardItem !== 'undefined'
) {
try {
const blobPromise = textPromise.then((text) => {
if (!text) throw new Error('EMPTY_TEXT')
return new Blob([text], { type: 'text/plain' })
})
blobPromise.catch(() => {})
await navigator.clipboard.write([
new ClipboardItem({
'text/plain': blobPromise,
}),
])
await textPromise
return true
} catch {
// Fall back if deferred writing fails or is rejected
}
}
try {
const text = await textPromise
if (!text) return false
return await copyToClipboard(text)
} catch (err) {
console.error('Failed to copy deferred text to clipboard:', err)
return false
}
}
/**
* Copies an image at a given URL (or promise resolving to URL) to the clipboard as PNG.
*/
export async function copyImageToClipboard(
imageUrlOrPromise: string | Promise<string>,
): Promise<boolean> {
if (
typeof navigator === 'undefined' ||
!navigator.clipboard ||
typeof navigator.clipboard.write !== 'function' ||
typeof ClipboardItem === 'undefined'
) {
return false
}
const renderPngBlob = async (): Promise<Blob> => {
const imageUrl = await imageUrlOrPromise
const response = await fetch(imageUrl)
const blob = await response.blob()
const img = new Image()
img.crossOrigin = 'anonymous'
const objectUrl = URL.createObjectURL(blob)
img.src = objectUrl
try {
await new Promise((resolve, reject) => {
img.onload = resolve
img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e)))
})
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)
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)
}
}
try {
const blobPromise = renderPngBlob()
// Try passing promise to ClipboardItem (Safari / Chrome 86+) to preserve user activation
try {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blobPromise,
}),
])
return true
} catch {
// Fallback for environments requiring a concrete Blob in ClipboardItem
const blob = await blobPromise
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blob,
}),
])
return true
}
} catch (err) {
console.error('Failed to copy image to clipboard:', err)
return false
}
}