fix(app): add clipboard fallback for web copy

This commit is contained in:
t8y2 committed 2026-05-19 13:51:38 +08:00
1 parent 69ee7f2d8b
commit c1ba7235b9
6 files changed
+155 -26

No files matched your search

@@ -13,6 +13,7 @@ import {
import { useToast } from "@/composables/useToast"; import { useToast } from "@/composables/useToast";
import { displayCellValue, type CellValue } from "@/lib/cellValue"; import { displayCellValue, type CellValue } from "@/lib/cellValue";
import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/actionActivation"; import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/actionActivation";
import { copyToClipboard } from "@/lib/clipboard";
interface RowItem { interface RowItem {
id: number; id: number;
@@ -65,9 +66,13 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
hasRowSelection, hasRowSelection,
} = options; } = options;
function copyText(text: string) { async function copyText(text: string) {
navigator.clipboard.writeText(text); try {
toast(t("grid.copied")); 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[] { function rowsToExport(rowIds?: number[]): RowItem[] {
@@ -77,35 +82,35 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
} }
// --- Selection copy functions --- // --- Selection copy functions ---
function copySelectionTsv() { async function copySelectionTsv() {
if (!hasCellSelection.value) return; if (!hasCellSelection.value) return;
copyText(formatSelectionAsTsv(selectedCells.value)); await copyText(formatSelectionAsTsv(selectedCells.value));
} }
function copySelectionCsv() { async function copySelectionCsv() {
if (!hasCellSelection.value) return; if (!hasCellSelection.value) return;
copyText(formatSelectionAsCsv(selectedCells.value)); await copyText(formatSelectionAsCsv(selectedCells.value));
} }
function copySelectionJson() { async function copySelectionJson() {
if (!hasCellSelection.value) return; if (!hasCellSelection.value) return;
copyText(formatSelectionAsJson(selectedCells.value)); await copyText(formatSelectionAsJson(selectedCells.value));
} }
function copySelectionSqlInList() { async function copySelectionSqlInList() {
if (!hasCellSelection.value) return; if (!hasCellSelection.value) return;
copyText(formatSelectionAsSqlInList(selectedCells.value)); await copyText(formatSelectionAsSqlInList(selectedCells.value));
} }
// --- Cell/row copy --- // --- Cell/row copy ---
function copyCell() { async function copyCell() {
if (!contextCell.value || contextCell.value.col < 0) return; if (!contextCell.value || contextCell.value.col < 0) return;
const item = getRowItem(contextCell.value.rowId); const item = getRowItem(contextCell.value.rowId);
const val = item?.data[contextCell.value.col] ?? null; 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) { if (hasRowSelection.value && selectedRowIds.value.size > 0) {
const items = displayItems.value.filter((item) => selectedRowIds.value.has(item.id)); const items = displayItems.value.filter((item) => selectedRowIds.value.has(item.id));
const objects = items.map((item) => { const objects = items.map((item) => {
@@ -115,7 +120,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
}); });
return obj; return obj;
}); });
copyText(JSON.stringify(objects, null, 2)); await copyText(JSON.stringify(objects, null, 2));
return; return;
} }
const range = selectedRange.value; const range = selectedRange.value;
@@ -128,7 +133,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
}); });
return obj; return obj;
}); });
copyText(JSON.stringify(objects, null, 2)); await copyText(JSON.stringify(objects, null, 2));
return; return;
} }
if (!contextCell.value) return; if (!contextCell.value) return;
@@ -138,10 +143,10 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
columns.value.forEach((col, i) => { columns.value.forEach((col, i) => {
obj[col] = item.data[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 const table = tableMeta.value
? (tableMeta.value.schema ? `${quoteIdent(tableMeta.value.schema)}.` : "") + quoteIdent(tableMeta.value.tableName) ? (tableMeta.value.schema ? `${quoteIdent(tableMeta.value.schema)}.` : "") + quoteIdent(tableMeta.value.tableName)
: "table_name"; : "table_name";
@@ -153,7 +158,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const vals = item.data.map((v) => escapeVal(v)).join(", "); const vals = item.data.map((v) => escapeVal(v)).join(", ");
return `INSERT INTO ${table} (${cols}) VALUES (${vals});`; return `INSERT INTO ${table} (${cols}) VALUES (${vals});`;
}); });
copyText(statements.join("\n")); await copyText(statements.join("\n"));
return; return;
} }
@@ -164,7 +169,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const vals = item.data.map((v) => escapeVal(v)).join(", "); const vals = item.data.map((v) => escapeVal(v)).join(", ");
return `INSERT INTO ${table} (${cols}) VALUES (${vals});`; return `INSERT INTO ${table} (${cols}) VALUES (${vals});`;
}); });
copyText(statements.join("\n")); await copyText(statements.join("\n"));
return; return;
} }
@@ -172,13 +177,13 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const item = getRowItem(contextCell.value.rowId); const item = getRowItem(contextCell.value.rowId);
if (!item) return; if (!item) return;
const vals = item.data.map((v) => escapeVal(v)).join(", "); 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 header = columns.value.join("\t");
const body = displayItems.value.map((item) => item.data.map((c) => displayCellValue(c)).join("\t")).join("\n"); 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 --- // --- File save helpers ---
@@ -311,10 +316,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
}); });
} }
function copySql() { async function copySql() {
if (!sql.value) return; if (!sql.value) return;
navigator.clipboard.writeText(sql.value); await copyText(sql.value);
toast(t("grid.copied"));
} }
return { return {
+1
View File
@@ -266,6 +266,7 @@ export default {
exportSelectedRowsMarkdown: "Export Selected Rows as Markdown", exportSelectedRowsMarkdown: "Export Selected Rows as Markdown",
exported: "Exported", exported: "Exported",
exportFailed: "Export failed: {message}", exportFailed: "Export failed: {message}",
copyFailed: "Copy failed: {message}",
filter: "Filter", filter: "Filter",
localFilter: "Local column filter", localFilter: "Local column filter",
localFilterFor: "Local Filter For '{column}'", localFilterFor: "Local Filter For '{column}'",
+1
View File
@@ -261,6 +261,7 @@ export default {
exportSelectedRowsMarkdown: "Exportar filas seleccionadas como Markdown", exportSelectedRowsMarkdown: "Exportar filas seleccionadas como Markdown",
exported: "Exportado", exported: "Exportado",
exportFailed: "Error al exportar: {message}", exportFailed: "Error al exportar: {message}",
copyFailed: "Error al copiar: {message}",
filter: "Filtrar", filter: "Filtrar",
localFilter: "Filtro local de columna", localFilter: "Filtro local de columna",
localFilterFor: "Filtro local para '{column}'", localFilterFor: "Filtro local para '{column}'",
+1
View File
@@ -264,6 +264,7 @@ export default {
exportSelectedRowsMarkdown: "导出选中行为 Markdown", exportSelectedRowsMarkdown: "导出选中行为 Markdown",
exported: "导出完成", exported: "导出完成",
exportFailed: "导出失败:{message}", exportFailed: "导出失败:{message}",
copyFailed: "复制失败:{message}",
filter: "筛选", filter: "筛选",
localFilter: "本地列筛选", localFilter: "本地列筛选",
localFilterFor: "本地筛选“{column}”", localFilterFor: "本地筛选“{column}”",
+72
View File
@@ -0,0 +1,72 @@
interface ClipboardApi {
writeText?: (text: string) => Promise<void> | 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<void> {
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);
}
}
+50
View File
@@ -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<string, string>,
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);
});