From c1ba7235b910c00ffbddb1959d64b5f3e7ba6447 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 19 May 2026 13:51:38 +0800 Subject: [PATCH] fix(app): add clipboard fallback for web copy --- .../src/composables/useDataGridExport.ts | 56 ++++++++------- apps/desktop/src/i18n/locales/en.ts | 1 + apps/desktop/src/i18n/locales/es.ts | 1 + apps/desktop/src/i18n/locales/zh-CN.ts | 1 + apps/desktop/src/lib/clipboard.ts | 72 +++++++++++++++++++ packages/app-tests/clipboard.test.ts | 50 +++++++++++++ 6 files changed, 155 insertions(+), 26 deletions(-) create mode 100644 apps/desktop/src/lib/clipboard.ts create mode 100644 packages/app-tests/clipboard.test.ts diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.ts index 7476cdfc74..4a1f25cb34 100644 --- a/apps/desktop/src/composables/useDataGridExport.ts +++ b/apps/desktop/src/composables/useDataGridExport.ts @@ -13,6 +13,7 @@ import { import { useToast } from "@/composables/useToast"; import { displayCellValue, type CellValue } from "@/lib/cellValue"; import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/actionActivation"; +import { copyToClipboard } from "@/lib/clipboard"; interface RowItem { id: number; @@ -65,9 +66,13 @@ export function useDataGridExport(options: UseDataGridExportOptions) { hasRowSelection, } = options; - function copyText(text: string) { - navigator.clipboard.writeText(text); - toast(t("grid.copied")); + async function copyText(text: string) { + try { + await copyToClipboard(text); + toast(t("grid.copied")); + } catch (e: any) { + toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000); + } } function rowsToExport(rowIds?: number[]): RowItem[] { @@ -77,35 +82,35 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } // --- Selection copy functions --- - function copySelectionTsv() { + async function copySelectionTsv() { if (!hasCellSelection.value) return; - copyText(formatSelectionAsTsv(selectedCells.value)); + await copyText(formatSelectionAsTsv(selectedCells.value)); } - function copySelectionCsv() { + async function copySelectionCsv() { if (!hasCellSelection.value) return; - copyText(formatSelectionAsCsv(selectedCells.value)); + await copyText(formatSelectionAsCsv(selectedCells.value)); } - function copySelectionJson() { + async function copySelectionJson() { if (!hasCellSelection.value) return; - copyText(formatSelectionAsJson(selectedCells.value)); + await copyText(formatSelectionAsJson(selectedCells.value)); } - function copySelectionSqlInList() { + async function copySelectionSqlInList() { if (!hasCellSelection.value) return; - copyText(formatSelectionAsSqlInList(selectedCells.value)); + await copyText(formatSelectionAsSqlInList(selectedCells.value)); } // --- Cell/row copy --- - function copyCell() { + async function copyCell() { if (!contextCell.value || contextCell.value.col < 0) return; const item = getRowItem(contextCell.value.rowId); const val = item?.data[contextCell.value.col] ?? null; - copyText(displayCellValue(val)); + await copyText(displayCellValue(val)); } - function copyRow() { + async function copyRow() { if (hasRowSelection.value && selectedRowIds.value.size > 0) { const items = displayItems.value.filter((item) => selectedRowIds.value.has(item.id)); const objects = items.map((item) => { @@ -115,7 +120,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { }); return obj; }); - copyText(JSON.stringify(objects, null, 2)); + await copyText(JSON.stringify(objects, null, 2)); return; } const range = selectedRange.value; @@ -128,7 +133,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { }); return obj; }); - copyText(JSON.stringify(objects, null, 2)); + await copyText(JSON.stringify(objects, null, 2)); return; } if (!contextCell.value) return; @@ -138,10 +143,10 @@ export function useDataGridExport(options: UseDataGridExportOptions) { columns.value.forEach((col, i) => { obj[col] = item.data[i]; }); - copyText(JSON.stringify(obj, null, 2)); + await copyText(JSON.stringify(obj, null, 2)); } - function copyRowAsInsert() { + async function copyRowAsInsert() { const table = tableMeta.value ? (tableMeta.value.schema ? `${quoteIdent(tableMeta.value.schema)}.` : "") + quoteIdent(tableMeta.value.tableName) : "table_name"; @@ -153,7 +158,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { const vals = item.data.map((v) => escapeVal(v)).join(", "); return `INSERT INTO ${table} (${cols}) VALUES (${vals});`; }); - copyText(statements.join("\n")); + await copyText(statements.join("\n")); return; } @@ -164,7 +169,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { const vals = item.data.map((v) => escapeVal(v)).join(", "); return `INSERT INTO ${table} (${cols}) VALUES (${vals});`; }); - copyText(statements.join("\n")); + await copyText(statements.join("\n")); return; } @@ -172,13 +177,13 @@ export function useDataGridExport(options: UseDataGridExportOptions) { const item = getRowItem(contextCell.value.rowId); if (!item) return; const vals = item.data.map((v) => escapeVal(v)).join(", "); - copyText(`INSERT INTO ${table} (${cols}) VALUES (${vals});`); + await copyText(`INSERT INTO ${table} (${cols}) VALUES (${vals});`); } - function copyAll() { + async function copyAll() { const header = columns.value.join("\t"); const body = displayItems.value.map((item) => item.data.map((c) => displayCellValue(c)).join("\t")).join("\n"); - copyText(`${header}\n${body}`); + await copyText(`${header}\n${body}`); } // --- File save helpers --- @@ -311,10 +316,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) { }); } - function copySql() { + async function copySql() { if (!sql.value) return; - navigator.clipboard.writeText(sql.value); - toast(t("grid.copied")); + await copyText(sql.value); } return { diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index 4282f2e920..8f7304521f 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -266,6 +266,7 @@ export default { exportSelectedRowsMarkdown: "Export Selected Rows as Markdown", exported: "Exported", exportFailed: "Export failed: {message}", + copyFailed: "Copy failed: {message}", filter: "Filter", localFilter: "Local column filter", localFilterFor: "Local Filter For '{column}'", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index 12a3c57877..830eafc0a3 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -261,6 +261,7 @@ export default { exportSelectedRowsMarkdown: "Exportar filas seleccionadas como Markdown", exported: "Exportado", exportFailed: "Error al exportar: {message}", + copyFailed: "Error al copiar: {message}", filter: "Filtrar", localFilter: "Filtro local de columna", localFilterFor: "Filtro local para '{column}'", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index bd02ad2fd9..b602f625b1 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -264,6 +264,7 @@ export default { exportSelectedRowsMarkdown: "导出选中行为 Markdown", exported: "导出完成", exportFailed: "导出失败:{message}", + copyFailed: "复制失败:{message}", filter: "筛选", localFilter: "本地列筛选", localFilterFor: "本地筛选“{column}”", diff --git a/apps/desktop/src/lib/clipboard.ts b/apps/desktop/src/lib/clipboard.ts new file mode 100644 index 0000000000..3eafc5fb62 --- /dev/null +++ b/apps/desktop/src/lib/clipboard.ts @@ -0,0 +1,72 @@ +interface ClipboardApi { + writeText?: (text: string) => Promise | void; +} + +interface ClipboardNavigator { + clipboard?: ClipboardApi; +} + +interface ClipboardTextarea { + value: string; + style: { + position?: string; + top?: string; + left?: string; + opacity?: string; + }; + setAttribute(name: string, value: string): void; + select(): void; + setSelectionRange?(start: number, end: number): void; +} + +interface ClipboardDocument { + body?: { + appendChild(node: unknown): unknown; + removeChild(node: unknown): unknown; + }; + createElement(tagName: "textarea"): ClipboardTextarea; + execCommand?(command: string): boolean; +} + +export interface ClipboardEnvironment { + navigator?: ClipboardNavigator; + document?: ClipboardDocument; +} + +export async function copyToClipboard( + text: string, + env: ClipboardEnvironment = globalThis as unknown as ClipboardEnvironment, +): Promise { + try { + if (env.navigator?.clipboard?.writeText) { + await env.navigator.clipboard.writeText(text); + return; + } + } catch { + // Fall through to the legacy copy path for non-secure web contexts. + } + + const document = env.document; + if (!document?.body || !document.execCommand) { + throw new Error("Clipboard API is not available"); + } + + const textarea = document.createElement("textarea"); + textarea.value = text; + textarea.setAttribute("readonly", ""); + textarea.style.position = "fixed"; + textarea.style.top = "0"; + textarea.style.left = "-9999px"; + textarea.style.opacity = "0"; + + document.body.appendChild(textarea); + try { + textarea.select(); + textarea.setSelectionRange?.(0, text.length); + if (!document.execCommand("copy")) { + throw new Error("Clipboard copy failed"); + } + } finally { + document.body.removeChild(textarea); + } +} diff --git a/packages/app-tests/clipboard.test.ts b/packages/app-tests/clipboard.test.ts new file mode 100644 index 0000000000..ae83a5cf4c --- /dev/null +++ b/packages/app-tests/clipboard.test.ts @@ -0,0 +1,50 @@ +import { strict as assert } from "node:assert"; +import test from "node:test"; +import { copyToClipboard } from "../../apps/desktop/src/lib/clipboard.ts"; + +test("copyToClipboard falls back when navigator clipboard is unavailable", async () => { + const appended: unknown[] = []; + const removed: unknown[] = []; + const selected: string[] = []; + const commands: string[] = []; + + const textarea = { + value: "", + style: {} as Record, + setAttribute(name: string, value: string) { + this.style[name] = value; + }, + select() { + selected.push(this.value); + }, + }; + + const env = { + navigator: {}, + document: { + body: { + appendChild(node: unknown) { + appended.push(node); + }, + removeChild(node: unknown) { + removed.push(node); + }, + }, + createElement(tagName: string) { + assert.equal(tagName, "textarea"); + return textarea; + }, + execCommand(command: string) { + commands.push(command); + return true; + }, + }, + }; + + await copyToClipboard("orders\t42", env); + + assert.deepEqual(selected, ["orders\t42"]); + assert.deepEqual(commands, ["copy"]); + assert.equal(appended[0], textarea); + assert.equal(removed[0], textarea); +});