feat(file-browser): add copy name and path option to context menu

This commit is contained in:
yiling
2026-07-27 10:23:22 +08:00
parent d81fc09b35
commit f429873362
20 changed files with 284 additions and 13 deletions
+51
View File
@@ -0,0 +1,51 @@
// @vitest-environment happy-dom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { copyToClipboard } from './clipboard'
describe('copyToClipboard', () => {
const originalClipboard = navigator.clipboard
beforeEach(() => {
vi.restoreAllMocks()
})
afterEach(() => {
Object.defineProperty(navigator, 'clipboard', {
value: originalClipboard,
configurable: true,
writable: true,
})
})
it('uses navigator.clipboard.writeText when available', async () => {
const mockWriteText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', {
value: { writeText: mockWriteText },
configurable: true,
writable: true,
})
const success = await copyToClipboard('test text')
expect(success).toBe(true)
expect(mockWriteText).toHaveBeenCalledWith('test text')
})
it('falls back to execCommand when navigator.clipboard is missing', async () => {
Object.defineProperty(navigator, 'clipboard', {
value: undefined,
configurable: true,
writable: true,
})
const execCommandFn = vi.fn().mockReturnValue(true)
Object.defineProperty(document, 'execCommand', {
value: execCommandFn,
configurable: true,
writable: true,
})
const success = await copyToClipboard('fallback text')
expect(success).toBe(true)
expect(execCommandFn).toHaveBeenCalledWith('copy')
})
})
+43
View File
@@ -0,0 +1,43 @@
/**
* Copies text to clipboard across both HTTP (non-secure context) and HTTPS (secure context).
*/
export async function copyToClipboard(text: string): Promise<boolean> {
if (
typeof navigator !== 'undefined' &&
navigator.clipboard &&
typeof navigator.clipboard.writeText === 'function'
) {
try {
await navigator.clipboard.writeText(text)
return true
} catch {
// Fallback if navigator.clipboard fails or permission is denied
}
}
// Fallback for non-secure HTTP context using execCommand
try {
const textArea = document.createElement('textarea')
textArea.value = text
textArea.style.position = 'fixed'
textArea.style.top = '0'
textArea.style.left = '0'
textArea.style.width = '2em'
textArea.style.height = '2em'
textArea.style.padding = '0'
textArea.style.border = 'none'
textArea.style.outline = 'none'
textArea.style.boxShadow = 'none'
textArea.style.background = 'transparent'
textArea.style.opacity = '0'
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
const successful = document.execCommand('copy')
document.body.removeChild(textArea)
return successful
} catch (err) {
console.error('Failed to copy text to clipboard:', err)
return false
}
}