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

This commit is contained in:
yiling
2026-11-04 21:52:49 +08:00
parent 2723d725a8
commit 10bda73cb9
17 changed files with 836 additions and 235 deletions
@@ -237,7 +237,6 @@ export function FileBrowserContextMenu({
context={{
isTeamOwner,
allowDownload,
archiveStorageEnabled,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
@@ -334,7 +333,6 @@ export function FileBrowserContextMenu({
context={{
isTeamOwner,
allowDownload,
archiveStorageEnabled,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
@@ -265,5 +265,18 @@ describe('copy-options', () => {
'Assets\tfolder\t—\thttps://shumai.app/projects/proj-1/folders/folder-1\tfolder-1',
)
})
it('escapes brackets in markdown links', () => {
const fileWithBrackets = { ...dummyFile, name: 'Report [Final] (v1).pdf' }
expect(formatCopyText('markdown', [fileWithBrackets], ctx)).toBe(
'[Report \\[Final\\] (v1).pdf](https://shumai.app/projects/proj-1/files/file-1)',
)
})
it('sanitizes tabs and newlines in TSV file names', () => {
const fileWithTabs = { ...dummyFile, name: 'test\tfile\nname.pdf' }
const tsv = formatCopyText('tsv', [fileWithTabs], ctx)
expect(tsv).toContain('test file name.pdf\tfile\t1.05 MB')
})
})
})
@@ -14,7 +14,6 @@ export interface CopyOptionsContext {
isPublicShare?: boolean
isTeamOwner?: boolean
allowDownload?: boolean
archiveStorageEnabled?: boolean
}
export interface CopyFormatContext {
@@ -182,13 +181,15 @@ export function formatCopyText(
case 'markdown':
if (items.length === 1) {
const item = items[0]
const safeName = item.name.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
const url = getItemInAppUrl(item, context.origin, context.projectId)
return `[${item.name}](${url})`
return `[${safeName}](${url})`
}
return items
.map((i) => {
const safeName = i.name.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
const url = getItemInAppUrl(i, context.origin, context.projectId)
return `- [${i.name}](${url})`
return `- [${safeName}](${url})`
})
.join('\n')
@@ -199,7 +200,8 @@ export function formatCopyText(
const size = i.type === 'folder' ? '—' : formatSize(i.sizeByte || 0)
const link = getItemInAppUrl(i, context.origin, context.projectId)
const id = i.versionStack ? i.versionStack.id : i.id
return `${i.name}\t${type}\t${size}\t${link}\t${id}`
const safeName = i.name.replace(/[\t\r\n]+/g, ' ')
return `${safeName}\t${type}\t${size}\t${link}\t${id}`
})
return [header, ...rows].join('\n')
}
@@ -705,7 +705,6 @@ export function FileCard({
context={{
isTeamOwner,
allowDownload,
archiveStorageEnabled,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
@@ -485,7 +485,6 @@ export function FolderCard({
context={{
isTeamOwner,
allowDownload,
archiveStorageEnabled,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
@@ -424,4 +424,17 @@ describe('MobileFileBrowser', () => {
expect(screen.queryByRole('button', { name: /actions/i })).toBeNull()
})
it('renders Copy submenu in file card dropdown menu on mobile', async () => {
const { container } = renderComponent()
const dropdownTrigger = container.querySelector(
'[data-slot="dropdown-menu-trigger"]',
) as HTMLElement
expect(dropdownTrigger).toBeTruthy()
fireEvent.keyDown(dropdownTrigger, { key: 'ArrowDown', code: 'ArrowDown' })
const copyOption = await screen.findByText(/^Copy$|^复制$/i)
expect(copyOption).toBeTruthy()
})
})
@@ -176,6 +176,7 @@ export function MobileFileBrowser({
confirmArchiveOrRestore,
isArchiving,
isRestoringArchive,
handleCopy,
} = useFileActions({
teamId,
projectId,
@@ -537,6 +538,8 @@ export function MobileFileBrowser({
archiveStorageEnabled={archiveStorageEnabled}
isShareView={isShareView}
allowDownload={allowDownload}
onCopy={handleCopy}
isTeamOwner={canAdmin}
/>
))}
</div>
@@ -600,6 +603,8 @@ export function MobileFileBrowser({
archiveStorageEnabled={archiveStorageEnabled}
isShareView={isShareView}
allowDownload={allowDownload}
onCopy={handleCopy}
isTeamOwner={canAdmin}
/>
))}
</div>
@@ -0,0 +1,299 @@
// @vitest-environment happy-dom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useCopyActions } from './use-copy-actions'
import type { AssetInfo } from '@shumai/dtos'
import { toast } from 'sonner'
import * as clipboardModule from '@/ui/lib/clipboard'
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
const mockDownloadUrlPost = vi.fn()
const mockStoragePathsPost = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
files: {
'download-url': {
$post: (...args: unknown[]) => mockDownloadUrlPost(...args),
},
'storage-paths': {
$post: (...args: unknown[]) => mockStoragePathsPost(...args),
},
},
},
},
}))
describe('useCopyActions', () => {
const dummyFile: AssetInfo = {
id: 'f1',
name: 'document.pdf',
type: 'file',
status: 'processed',
sizeByte: 1024,
fileCount: 0,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
}
const dummyFolder: AssetInfo = {
id: 'd1',
name: 'Folder1',
type: 'folder',
status: 'processed',
sizeByte: 0,
fileCount: 2,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
}
const dummyImage: AssetInfo = {
id: 'img1',
name: 'photo.jpg',
type: 'file',
proxyType: 'image',
status: 'processed',
sizeByte: 2048,
fileCount: 0,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
media: {
imageTranscodes: [
{ id: 't1', url: '', key: 'files/img1/proxy-768p.webp', width: 768, height: 1024, size: 500 },
],
},
}
beforeEach(() => {
vi.restoreAllMocks()
vi.clearAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('R2 Regression: Empty download links or storage paths', () => {
it('does not touch clipboard and does not toast success when all files are archived', async () => {
const getDownloadLinks = vi.fn().mockResolvedValue({
files: [],
skippedArchivedCount: 2,
})
const copyDeferredSpy = vi.spyOn(clipboardModule, 'copyToClipboardDeferred')
const copyTextSpy = vi.spyOn(clipboardModule, 'copyToClipboard')
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks,
}),
)
await act(async () => {
await result.current.handleCopy('download-link', [dummyFile, { ...dummyFile, id: 'f2' }])
})
// Must show error toast
expect(toast.error).toHaveBeenCalled()
// Must NOT show success toast
expect(toast.success).not.toHaveBeenCalled()
// Must NOT have copied empty string with copyToClipboard
expect(copyTextSpy).not.toHaveBeenCalled()
// If deferred was called, it should have returned false and avoided success
if (copyDeferredSpy.mock.results.length > 0) {
expect(await copyDeferredSpy.mock.results[0].value).toBe(false)
}
})
it('does not toast success and shows error toast when storage paths return empty array', async () => {
mockStoragePathsPost.mockResolvedValueOnce({
ok: true,
json: async () => ({ paths: [] }),
})
const copyDeferredSpy = vi.spyOn(clipboardModule, 'copyToClipboardDeferred')
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('storage-path', [dummyFile])
})
expect(toast.error).toHaveBeenCalled()
expect(toast.success).not.toHaveBeenCalled()
if (copyDeferredSpy.mock.results.length > 0) {
expect(await copyDeferredSpy.mock.results[0].value).toBe(false)
}
})
})
describe('image copying', () => {
it('resolves download URL on demand for transcode key and copies image to clipboard', async () => {
mockDownloadUrlPost.mockResolvedValueOnce({
ok: true,
json: async () => ({ url: 'https://cdn/proxy-768p.webp' }),
})
const copyImageSpy = vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('image', [dummyImage])
})
expect(mockDownloadUrlPost).toHaveBeenCalledWith({
json: { key: 'files/img1/proxy-768p.webp', assetId: 'img1' },
})
expect(copyImageSpy).toHaveBeenCalled()
expect(toast.success).toHaveBeenCalled()
})
it('falls back to thumbnail URL if no transcodes are present', async () => {
const imageWithThumb: AssetInfo = {
...dummyImage,
media: undefined,
preview: {
thumbnailUrl: 'https://cdn/thumb.webp',
},
}
const copyImageSpy = vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('image', [imageWithThumb])
})
expect(copyImageSpy).toHaveBeenCalled()
expect(toast.success).toHaveBeenCalled()
})
it('toasts error if copying image fails or is unsupported', async () => {
vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(false)
mockDownloadUrlPost.mockResolvedValueOnce({
ok: true,
json: async () => ({ url: 'https://cdn/proxy-768p.webp' }),
})
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('image', [dummyImage])
})
expect(toast.error).toHaveBeenCalled()
expect(toast.success).not.toHaveBeenCalled()
})
})
describe('download links copying', () => {
it('copies download links and shows skipped folders suffix when folders are included', async () => {
const getDownloadLinks = vi.fn().mockResolvedValue({
files: [{ id: 'f1', name: 'document.pdf', url: 'https://cdn/download-1' }],
})
vi.spyOn(clipboardModule, 'copyToClipboardDeferred').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks,
}),
)
await act(async () => {
await result.current.handleCopy('download-link', [dummyFile, dummyFolder])
})
expect(getDownloadLinks).toHaveBeenCalledWith({ json: { ids: ['f1'] } })
expect(toast.success).toHaveBeenCalled()
})
})
describe('storage paths copying', () => {
it('fetches storage paths and copies via deferred clipboard', async () => {
mockStoragePathsPost.mockResolvedValueOnce({
ok: true,
json: async () => ({
paths: [
{
id: 'f1',
name: 'document.pdf',
path: '/data/shumai/files/1',
backend: 'local',
isArchived: false,
},
],
}),
})
vi.spyOn(clipboardModule, 'copyToClipboardDeferred').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('storage-path', [dummyFile])
})
expect(mockStoragePathsPost).toHaveBeenCalledWith({ json: { ids: ['f1'] } })
expect(toast.success).toHaveBeenCalled()
})
})
describe('text copying formats', () => {
it('copies name, link, id, markdown, and tsv with success toasts', async () => {
vi.spyOn(clipboardModule, 'copyToClipboard').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
for (const kind of ['name', 'link', 'id', 'markdown', 'tsv'] as const) {
vi.clearAllMocks()
await act(async () => {
await result.current.handleCopy(kind, [dummyFile, dummyFolder])
})
expect(clipboardModule.copyToClipboard).toHaveBeenCalled()
expect(toast.success).toHaveBeenCalled()
}
})
})
})
@@ -0,0 +1,223 @@
'use client'
import { client } from '@/ui/api/client'
import type { AssetInfo } from '@shumai/dtos'
import { toast } from 'sonner'
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard'
import { type CopyKind, formatCopyText, pickClipboardTranscode } from './copy-options'
import { m } from '@/ui/paraglide/messages.js'
export interface UseCopyActionsProps {
projectId?: string
isPublic?: boolean
shareId?: string
getDownloadLinks: (args: { json: { ids: string[] } }) => Promise<{
files: Array<{ id: string; name: string; url: string }>
skippedArchivedCount?: number
}>
}
export function useCopyActions({
projectId,
isPublic,
shareId,
getDownloadLinks,
}: UseCopyActionsProps) {
const handleCopy = async (kind: CopyKind, items: AssetInfo[]) => {
if (items.length === 0) return
if (kind === 'image') {
const item = items[0]
const transcode = pickClipboardTranscode(item.media?.imageTranscodes)
if (!transcode && !item.preview?.thumbnailUrl && item.status !== 'processed') {
toast.error(m.copy_image_failed())
return
}
const fetchImageUrl = async (): Promise<string> => {
if (transcode?.url) return transcode.url
if (transcode?.key && item.id) {
if (isPublic && shareId) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
{
param: { shareId, fileId: item.id },
json: { key: transcode.key },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.ok) {
const { url } = await res.json()
return url
}
} else {
const res = await client.api.files['download-url'].$post({
json: { key: transcode.key, assetId: item.id },
})
if (res.ok) {
const { url } = await res.json()
return url
}
}
}
if (item.preview?.thumbnailUrl) {
return item.preview.thumbnailUrl
}
throw new Error('No image URL available')
}
try {
const ok = await copyImageToClipboard(fetchImageUrl())
if (ok) {
toast.success(m.copied_image_toast())
} else {
toast.error(m.copy_image_failed())
}
} catch {
toast.error(m.copy_image_failed())
}
return
}
if (kind === 'download-link') {
const targetFiles = items.filter((i) => i.type !== 'folder')
if (targetFiles.length === 0) return
let hasShownEmptyError = false
try {
const fetchDownloadLinksPromise = (async () => {
const res = await getDownloadLinks({
json: { ids: targetFiles.map((i) => i.id!) },
})
const files = res.files
if (files.length === 0) {
hasShownEmptyError = true
if ((res.skippedArchivedCount ?? 0) > 0) {
toast.error(m.download_all_archived_error())
} else {
toast.error(m.copy_failed())
}
throw new Error('NO_FILES_TO_COPY')
}
return files.map((f) => f.url).join('\n')
})()
const ok = await copyToClipboardDeferred(fetchDownloadLinksPromise)
if (ok) {
const skippedFolders = items.length - targetFiles.length
if (targetFiles.length === 1 && skippedFolders === 0) {
toast.success(m.copied_download_link_toast())
} else {
const baseToast = m.copied_download_links_toast({ count: targetFiles.length })
const msg =
skippedFolders > 0
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
: baseToast
toast.success(msg)
}
} else if (!hasShownEmptyError) {
toast.error(m.copy_failed())
}
} catch (err) {
if (!hasShownEmptyError) {
console.error('Failed to copy download links:', err)
toast.error(m.copy_failed())
}
}
return
}
if (kind === 'storage-path') {
const targetFiles = items.filter((i) => i.type !== 'folder')
if (targetFiles.length === 0) return
let hasShownEmptyError = false
try {
const fetchStoragePathsPromise = (async () => {
const res = await client.api.files['storage-paths'].$post({
json: { ids: targetFiles.map((i) => i.id!) },
})
if (!res.ok) throw new Error('Failed to fetch storage paths')
const data = await res.json()
if (!data.paths || data.paths.length === 0) {
hasShownEmptyError = true
toast.error(m.copy_failed())
throw new Error('NO_PATHS_TO_COPY')
}
return data.paths.map((p) => p.path).join('\n')
})()
const ok = await copyToClipboardDeferred(fetchStoragePathsPromise)
if (ok) {
const skippedFolders = items.length - targetFiles.length
if (targetFiles.length === 1 && skippedFolders === 0) {
toast.success(m.copied_storage_path_toast())
} else {
const baseToast = m.copied_storage_paths_toast({ count: targetFiles.length })
const msg =
skippedFolders > 0
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
: baseToast
toast.success(msg)
}
} else if (!hasShownEmptyError) {
toast.error(m.copy_failed())
}
} catch (err) {
if (!hasShownEmptyError) {
console.error('Failed to copy storage paths:', err)
toast.error(m.copy_failed())
}
}
return
}
// Synchronous text copy
const origin = typeof window !== 'undefined' ? window.location.origin : ''
const text = formatCopyText(kind, items, { origin, projectId })
const ok = await copyToClipboard(text)
if (ok) {
switch (kind) {
case 'name':
toast.success(
items.length === 1
? m.copied_name_toast()
: m.copied_names_toast({ count: items.length }),
)
break
case 'link':
toast.success(
items.length === 1
? m.copied_link_toast()
: m.copied_links_toast({ count: items.length }),
)
break
case 'id':
toast.success(
items.length === 1 ? m.copied_id_toast() : m.copied_ids_toast({ count: items.length }),
)
break
case 'markdown':
toast.success(
items.length === 1
? m.copied_markdown_link_toast()
: m.copied_markdown_links_toast({ count: items.length }),
)
break
case 'tsv':
toast.success(m.copied_table_toast({ count: items.length }))
break
}
} else {
toast.error(m.copy_failed())
}
}
return { handleCopy }
}
@@ -6,8 +6,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { useState } from 'react'
import { toast } from 'sonner'
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard'
import { type CopyKind, formatCopyText, pickClipboardTranscode } from './copy-options'
import { useCopyActions } from './use-copy-actions'
import { m } from '@/ui/paraglide/messages.js'
interface UseFileActionsProps {
@@ -317,183 +316,12 @@ export function useFileActions({
}
}
const handleCopy = async (kind: CopyKind, items: AssetInfo[]) => {
if (items.length === 0) return
if (kind === 'image') {
const item = items[0]
const transcode = pickClipboardTranscode(item.media?.imageTranscodes)
if (!transcode && !item.preview?.thumbnailUrl && item.status !== 'processed') {
toast.error(m.copy_image_failed())
return
}
const urlPromise = (async () => {
if (transcode?.url) return transcode.url
if (transcode?.key && item.id) {
if (isPublic && shareId) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
{
param: { shareId, fileId: item.id },
json: { key: transcode.key },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.ok) {
const { url } = await res.json()
return url
}
} else {
const res = await client.api.files['download-url'].$post({
json: { key: transcode.key, assetId: item.id },
})
if (res.ok) {
const { url } = await res.json()
return url
}
}
}
if (item.preview?.thumbnailUrl) {
return item.preview.thumbnailUrl
}
throw new Error('No image URL available')
})()
const ok = await copyImageToClipboard(urlPromise)
if (ok) {
toast.success(m.copied_image_toast())
} else {
toast.error(m.copy_image_failed())
}
return
}
if (kind === 'download-link') {
const targetFiles = items.filter((i) => i.type !== 'folder')
if (targetFiles.length === 0) return
try {
const fetchDownloadLinksPromise = (async () => {
const res = await getDownloadLinks({
json: { ids: targetFiles.map((i) => i.id!) },
})
const files = res.files
if (files.length === 0) {
if ((res.skippedArchivedCount ?? 0) > 0) {
toast.error(m.download_all_archived_error())
}
return ''
}
return files.map((f) => f.url).join('\n')
})()
const ok = await copyToClipboardDeferred(fetchDownloadLinksPromise)
if (ok) {
const skippedFolders = items.length - targetFiles.length
if (targetFiles.length === 1 && skippedFolders === 0) {
toast.success(m.copied_download_link_toast())
} else {
const baseToast = m.copied_download_links_toast({ count: targetFiles.length })
const msg =
skippedFolders > 0
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
: baseToast
toast.success(msg)
}
} else {
toast.error(m.copy_failed())
}
} catch (err) {
console.error('Failed to copy download links:', err)
toast.error(m.copy_failed())
}
return
}
if (kind === 'storage-path') {
const targetFiles = items.filter((i) => i.type !== 'folder')
if (targetFiles.length === 0) return
try {
const fetchStoragePathsPromise = (async () => {
const res = await client.api.files['storage-paths'].$post({
json: { ids: targetFiles.map((i) => i.id!) },
})
if (!res.ok) throw new Error('Failed to fetch storage paths')
const data = (await res.json()) as { paths: Array<{ path: string }> }
return data.paths.map((p) => p.path).join('\n')
})()
const ok = await copyToClipboardDeferred(fetchStoragePathsPromise)
if (ok) {
const skippedFolders = items.length - targetFiles.length
if (targetFiles.length === 1 && skippedFolders === 0) {
toast.success(m.copied_storage_path_toast())
} else {
const baseToast = m.copied_storage_paths_toast({ count: targetFiles.length })
const msg =
skippedFolders > 0
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
: baseToast
toast.success(msg)
}
} else {
toast.error(m.copy_failed())
}
} catch (err) {
console.error('Failed to copy storage paths:', err)
toast.error(m.copy_failed())
}
return
}
// Synchronous text copy
const origin = typeof window !== 'undefined' ? window.location.origin : ''
const text = formatCopyText(kind, items, { origin, projectId })
const ok = await copyToClipboard(text)
if (ok) {
switch (kind) {
case 'name':
toast.success(
items.length === 1
? m.copied_name_toast()
: m.copied_names_toast({ count: items.length }),
)
break
case 'link':
toast.success(
items.length === 1
? m.copied_link_toast()
: m.copied_links_toast({ count: items.length }),
)
break
case 'id':
toast.success(
items.length === 1 ? m.copied_id_toast() : m.copied_ids_toast({ count: items.length }),
)
break
case 'markdown':
toast.success(
items.length === 1
? m.copied_markdown_link_toast()
: m.copied_markdown_links_toast({ count: items.length }),
)
break
case 'tsv':
toast.success(m.copied_table_toast({ count: items.length }))
break
}
} else {
toast.error(m.copy_failed())
}
}
const { handleCopy } = useCopyActions({
projectId,
isPublic,
shareId,
getDownloadLinks: (args) => getDownloadLinks(args),
})
const handleArchive = (items: AssetInfo[]) => {
if (items.length === 0) return
@@ -702,10 +530,6 @@ export function useFileActions({
}
}
const handleCopyNameAndDownloadLink = (items: AssetInfo[]) => {
handleCopy('download-link', items)
}
return {
editingItemId,
setEditingItemId,
@@ -714,7 +538,6 @@ export function useFileActions({
handleRestore,
handleDownload,
handleCopy,
handleCopyNameAndDownloadLink,
handleArchive,
handleRestoreArchive,
handleNewFolder,
+8 -1
View File
@@ -54,12 +54,18 @@ export async function copyToClipboardDeferred(textPromise: Promise<string>): Pro
typeof ClipboardItem !== 'undefined'
) {
try {
const blobPromise = textPromise.then((text) => new Blob([text], { type: 'text/plain' }))
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
@@ -68,6 +74,7 @@ export async function copyToClipboardDeferred(textPromise: Promise<string>): Pro
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)