diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 36b6099f..b3ba93e3 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -9,6 +9,7 @@ import { AssetService } from './asset' vi.mock('@shumai/core/src/s3/s3', () => ({ s3Service: { presign: vi.fn().mockResolvedValue('http://mock-s3-url'), + getAbsolutePathOrUrl: vi.fn().mockResolvedValue('http://mock-s3-url'), putObject: vi.fn().mockResolvedValue(undefined), deleteObject: vi.fn().mockResolvedValue(1), deletePrefix: vi.fn().mockResolvedValue(1), diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index fe6f90e5..dcff4a5c 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -1969,7 +1969,7 @@ export class AssetService { const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null if (!key) return null - const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true) + const url = await s3Service.getAbsolutePathOrUrl(process.env.S3_BUCKET || 'shumai', key) return { id: file.id, diff --git a/packages/core/src/s3/s3.ts b/packages/core/src/s3/s3.ts index 10ea5bf3..54a4c409 100644 --- a/packages/core/src/s3/s3.ts +++ b/packages/core/src/s3/s3.ts @@ -55,6 +55,7 @@ export interface S3Service { uploadFile(filePath: string, contentType: string): Promise uploadFileToKey(filePath: string, key: string, contentType: string): Promise presign(bucket: string, key: string, method: string, download?: boolean): Promise + getAbsolutePathOrUrl(bucket: string, key: string): Promise } export class S3StorageService implements S3Service { @@ -230,6 +231,10 @@ export class S3StorageService implements S3Service { return url } + + async getAbsolutePathOrUrl(bucket: string, key: string): Promise { + return this.presign(bucket, key, 'GET', true) + } } export class LocalStorageService implements S3Service { @@ -441,6 +446,10 @@ export class LocalStorageService implements S3Service { } return url } + + async getAbsolutePathOrUrl(bucket: string, key: string): Promise { + return this.getFilePath(bucket, key) + } } const storageBackend = process.env.STORAGE_BACKEND || 'local' diff --git a/packages/webui/components/file-browser/context-menu.tsx b/packages/webui/components/file-browser/context-menu.tsx index 03c69da7..0eac5080 100644 --- a/packages/webui/components/file-browser/context-menu.tsx +++ b/packages/webui/components/file-browser/context-menu.tsx @@ -30,6 +30,7 @@ interface FileBrowserContextMenuProps { onRename: (item: AssetInfo) => void onDelete: (items: AssetInfo[]) => void onDownload: (items: AssetInfo[]) => void + onCopyNameAndPath?: (items: AssetInfo[]) => void onRestore: (items: AssetInfo[]) => void onNewFolder: (name: string) => void onUploadFile: () => void @@ -55,6 +56,7 @@ export function FileBrowserContextMenu({ onRename, onDelete, onDownload, + onCopyNameAndPath, onRestore, onNewFolder, onUploadFile, @@ -98,6 +100,14 @@ export function FileBrowserContextMenu({ } } + const handleCopyNameAndPath = () => { + if (isItemSelected) { + onCopyNameAndPath?.(selectedItems) + } else if (item) { + onCopyNameAndPath?.([item]) + } + } + const handleRestore = () => { onRestore(itemsToRestore) } @@ -110,6 +120,10 @@ export function FileBrowserContextMenu({ {m.download()} + + + {m.copy_name_and_path()} + {canEdit && ( onRemoveFromShare?.(itemsToModify)} @@ -177,6 +191,10 @@ export function FileBrowserContextMenu({ {m.download()} + + + {m.copy_name_and_path()} + {canEdit && ( onMoveTo(itemsToModify)}> @@ -247,6 +265,10 @@ export function FileBrowserContextMenu({ {m.download()} + + + {m.copy_name_and_path()} + {canEdit && ( onMoveTo(itemsToModify)}> diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index 581db6e6..580f1c7a 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -400,6 +400,7 @@ export function FileBrowser({ handleRename, handleRestore, handleDownload, + handleCopyNameAndPath, handleAction, onRenameSubmit, isDeleteDialogOpen, @@ -1161,6 +1162,7 @@ export function FileBrowser({ onRename={handleRename} onDelete={handleDelete} onDownload={handleDownload} + onCopyNameAndPath={handleCopyNameAndPath} onNewFolder={handleNewFolder} onUploadFile={handleUploadFilesClick} onUploadFolder={handleUploadFolderClick} diff --git a/packages/webui/components/file-browser/use-file-actions.ts b/packages/webui/components/file-browser/use-file-actions.ts index dca44080..8a936cf2 100644 --- a/packages/webui/components/file-browser/use-file-actions.ts +++ b/packages/webui/components/file-browser/use-file-actions.ts @@ -6,6 +6,8 @@ import { useMutation, useQueryClient } from '@tanstack/react-query' import type { InferRequestType, InferResponseType } from 'hono/client' import { useState } from 'react' import { toast } from 'sonner' +import { copyToClipboard } from '@/ui/lib/clipboard' +import { m } from '@/ui/paraglide/messages.js' interface UseFileActionsProps { teamId: string @@ -226,6 +228,32 @@ export function useFileActions({ } } + const handleCopyNameAndPath = async (items: AssetInfo[]) => { + if (items.length === 0) return + try { + const res = await getDownloadLinks({ + json: { ids: items.map((i) => i.id!) }, + }) + const files = res.files + if (files.length === 0) return + + let text = '' + if (files.length === 1) { + text = `Name: ${files[0].name}\nPath: ${files[0].url}` + } else { + text = files.map((f) => `${f.name}\t${f.url}`).join('\n') + } + + const ok = await copyToClipboard(text) + if (ok) { + toast.success(m.copied_name_and_path_to_clipboard()) + } + } catch (error) { + toast.error('Failed to copy name and path') + console.error(error) + } + } + const startDownload = () => { const files = [...resolvedFiles] setIsDownloadDialogOpen(false) @@ -321,7 +349,10 @@ export function useFileActions({ } } - const handleAction = (action: 'rename' | 'delete' | 'download' | 'restore', item: AssetInfo) => { + const handleAction = ( + action: 'rename' | 'delete' | 'download' | 'restore' | 'copy-name-and-path', + item: AssetInfo, + ) => { const isSelected = selectedIds.has(item.id!) const targetItems = isSelected ? [...folders, ...files].filter((i) => selectedIds.has(i.id!)) @@ -340,6 +371,9 @@ export function useFileActions({ case 'restore': handleRestore(targetItems) break + case 'copy-name-and-path': + handleCopyNameAndPath(targetItems) + break } } @@ -350,6 +384,7 @@ export function useFileActions({ handleDelete, handleRestore, handleDownload, + handleCopyNameAndPath, handleNewFolder, handleAction, onRenameSubmit, diff --git a/packages/webui/components/members-dialog.tsx b/packages/webui/components/members-dialog.tsx index f65e3776..959b657b 100644 --- a/packages/webui/components/members-dialog.tsx +++ b/packages/webui/components/members-dialog.tsx @@ -22,6 +22,7 @@ import { Input } from '@/ui/components/ui/input' import { ChevronDown, Copy, Loader2, Trash2 } from 'lucide-react' import { useState } from 'react' import { toast } from 'sonner' +import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard' import { m } from '@/ui/paraglide/messages.js' export interface Member { @@ -131,10 +132,12 @@ export function MembersDialog({ } } - const copyToClipboard = () => { + const copyToClipboard = async () => { if (inviteLink) { - navigator.clipboard.writeText(inviteLink) - toast.success(m.invite_link_copied()) + const ok = await copyTextToClipboard(inviteLink) + if (ok) { + toast.success(m.invite_link_copied()) + } } } diff --git a/packages/webui/components/settings/DeveloperSettings.tsx b/packages/webui/components/settings/DeveloperSettings.tsx index 27b4afe5..a43233e7 100644 --- a/packages/webui/components/settings/DeveloperSettings.tsx +++ b/packages/webui/components/settings/DeveloperSettings.tsx @@ -14,6 +14,7 @@ import { } from '@/ui/components/ui/table' import { Loader2, Plus, Trash2, Copy, Check } from 'lucide-react' import { toast } from 'sonner' +import { copyToClipboard } from '@/ui/lib/clipboard' import type { ApiTokenResponse } from '@shumai/dtos' import { m } from '@/ui/paraglide/messages.js' @@ -75,8 +76,8 @@ export function DeveloperSettings({ teamId }: { teamId: string }) { createToken(tokenName.trim()) } - const handleCopy = (id: string, token: string) => { - navigator.clipboard.writeText(token) + const handleCopy = async (id: string, token: string) => { + await copyToClipboard(token) setCopiedId(id) toast.success(m.copied_api_token_to_clipboard()) setTimeout(() => setCopiedId(null), 2000) diff --git a/packages/webui/components/share-settings-sidebar.tsx b/packages/webui/components/share-settings-sidebar.tsx index 001a2136..86bda079 100644 --- a/packages/webui/components/share-settings-sidebar.tsx +++ b/packages/webui/components/share-settings-sidebar.tsx @@ -21,6 +21,7 @@ import { } from 'lucide-react' import React, { useState } from 'react' import { toast } from 'sonner' +import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard' import { DateTimePicker } from '@/ui/components/datetime-picker' import { Select, @@ -88,9 +89,11 @@ export function ShareSettingsSidebar({ const shareUrl = `${window.location.origin}/share/${shareLink.id}` - const copyToClipboard = (text: string) => { - navigator.clipboard.writeText(text) - toast.success(m.copied_to_clipboard()) + const copyToClipboard = async (text: string) => { + const ok = await copyTextToClipboard(text) + if (ok) { + toast.success(m.copied_to_clipboard()) + } } const toggleFieldVisibility = (fieldId: string) => { diff --git a/packages/webui/lib/clipboard.test.ts b/packages/webui/lib/clipboard.test.ts new file mode 100644 index 00000000..d9856789 --- /dev/null +++ b/packages/webui/lib/clipboard.test.ts @@ -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') + }) +}) diff --git a/packages/webui/lib/clipboard.ts b/packages/webui/lib/clipboard.ts new file mode 100644 index 00000000..c6e74f5e --- /dev/null +++ b/packages/webui/lib/clipboard.ts @@ -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 { + 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 + } +} diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 52f8205c..517ba13a 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -269,6 +269,8 @@ "failed_to_revoke_token": "Failed to revoke token", "copied_to_clipboard": "Copied to clipboard", "copied_api_token_to_clipboard": "Copied API token to clipboard", + "copy_name_and_path": "Copy name and path", + "copied_name_and_path_to_clipboard": "Copied name and path to clipboard", "ai": "AI", "providers": "Providers", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index 0277341a..9afa185d 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -269,6 +269,8 @@ "failed_to_revoke_token": "撤销令牌失败", "copied_to_clipboard": "已复制到剪贴板", "copied_api_token_to_clipboard": "已将 API 令牌复制到剪贴板", + "copy_name_and_path": "复制名称和路径", + "copied_name_and_path_to_clipboard": "已复制名称和路径到剪贴板", "ai": "AI", "providers": "提供商", diff --git a/packages/webui/paraglide/messages/_index.d.ts b/packages/webui/paraglide/messages/_index.d.ts index fc58ca07..3cc45ffd 100644 --- a/packages/webui/paraglide/messages/_index.d.ts +++ b/packages/webui/paraglide/messages/_index.d.ts @@ -254,6 +254,8 @@ export * from "./api_token_revoked_successfully.js"; export * from "./failed_to_revoke_token.js"; export * from "./copied_to_clipboard.js"; export * from "./copied_api_token_to_clipboard.js"; +export * from "./copy_name_and_path.js"; +export * from "./copied_name_and_path_to_clipboard.js"; export * from "./ai.js"; export * from "./providers.js"; export * from "./providers_description.js"; diff --git a/packages/webui/paraglide/messages/_index.js b/packages/webui/paraglide/messages/_index.js index a33c34f2..3892f7cf 100644 --- a/packages/webui/paraglide/messages/_index.js +++ b/packages/webui/paraglide/messages/_index.js @@ -256,6 +256,8 @@ export * from './api_token_revoked_successfully.js' export * from './failed_to_revoke_token.js' export * from './copied_to_clipboard.js' export * from './copied_api_token_to_clipboard.js' +export * from './copy_name_and_path.js' +export * from './copied_name_and_path_to_clipboard.js' export * from './ai.js' export * from './providers.js' export * from './providers_description.js' diff --git a/packages/webui/paraglide/messages/copied_name_and_path_to_clipboard.d.ts b/packages/webui/paraglide/messages/copied_name_and_path_to_clipboard.d.ts new file mode 100644 index 00000000..3727db58 --- /dev/null +++ b/packages/webui/paraglide/messages/copied_name_and_path_to_clipboard.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Copied name and path to clipboard" | +* +* @param {Copied_Name_And_Path_To_ClipboardInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const copied_name_and_path_to_clipboard: ((inputs?: Copied_Name_And_Path_To_ClipboardInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Copied_Name_And_Path_To_ClipboardInputs = {}; diff --git a/packages/webui/paraglide/messages/copied_name_and_path_to_clipboard.js b/packages/webui/paraglide/messages/copied_name_and_path_to_clipboard.js new file mode 100644 index 00000000..1d8060c9 --- /dev/null +++ b/packages/webui/paraglide/messages/copied_name_and_path_to_clipboard.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Copied_Name_And_Path_To_ClipboardInputs */ + +const en_copied_name_and_path_to_clipboard = /** @type {(inputs: Copied_Name_And_Path_To_ClipboardInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Copied name and path to clipboard`) +}; + +const zh_copied_name_and_path_to_clipboard = /** @type {(inputs: Copied_Name_And_Path_To_ClipboardInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`已复制名称和路径到剪贴板`) +}; + +/** +* | output | +* | --- | +* | "Copied name and path to clipboard" | +* +* @param {Copied_Name_And_Path_To_ClipboardInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const copied_name_and_path_to_clipboard = /** @type {((inputs?: Copied_Name_And_Path_To_ClipboardInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_copied_name_and_path_to_clipboard(inputs) + return zh_copied_name_and_path_to_clipboard(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/copy_name_and_path.d.ts b/packages/webui/paraglide/messages/copy_name_and_path.d.ts new file mode 100644 index 00000000..03605394 --- /dev/null +++ b/packages/webui/paraglide/messages/copy_name_and_path.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Copy name and path" | +* +* @param {Copy_Name_And_PathInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const copy_name_and_path: ((inputs?: Copy_Name_And_PathInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Copy_Name_And_PathInputs = {}; diff --git a/packages/webui/paraglide/messages/copy_name_and_path.js b/packages/webui/paraglide/messages/copy_name_and_path.js new file mode 100644 index 00000000..5a7bf697 --- /dev/null +++ b/packages/webui/paraglide/messages/copy_name_and_path.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Copy_Name_And_PathInputs */ + +const en_copy_name_and_path = /** @type {(inputs: Copy_Name_And_PathInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Copy name and path`) +}; + +const zh_copy_name_and_path = /** @type {(inputs: Copy_Name_And_PathInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`复制名称和路径`) +}; + +/** +* | output | +* | --- | +* | "Copy name and path" | +* +* @param {Copy_Name_And_PathInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const copy_name_and_path = /** @type {((inputs?: Copy_Name_And_PathInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_copy_name_and_path(inputs) + return zh_copy_name_and_path(inputs) +}); \ No newline at end of file diff --git a/packages/webui/routes/projects/$projectId/shares/index.lazy.tsx b/packages/webui/routes/projects/$projectId/shares/index.lazy.tsx index 6f79c7da..ee981001 100644 --- a/packages/webui/routes/projects/$projectId/shares/index.lazy.tsx +++ b/packages/webui/routes/projects/$projectId/shares/index.lazy.tsx @@ -3,6 +3,7 @@ import { client } from '@/ui/api/client' import { FolderTree } from '@/ui/components/folder-tree' import { ResizeHandle } from '@/ui/components/resize-handle' import { m } from '@/ui/paraglide/messages.js' +import { copyToClipboard } from '@/ui/lib/clipboard' import { Switch } from '@/ui/components/ui/switch' import { Button } from '@/ui/components/ui/button' import { @@ -117,10 +118,12 @@ function SharesPage() { return } - const handleCopyLink = (shareId: string) => { + const handleCopyLink = async (shareId: string) => { const url = `${window.location.origin}/share/${shareId}` - navigator.clipboard.writeText(url) - toast.success(m.link_copied()) + const ok = await copyToClipboard(url) + if (ok) { + toast.success(m.link_copied()) + } } return (