Repository navigation
Expand file tree
/
Copy pathsheet-clipboard-write-fallback.ts
More file actions
204 lines (193 loc) · 8.4 KB
/
Copy pathsheet-clipboard-write-fallback.ts
File metadata and controls
204 lines (193 loc) · 8.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import { useEffect } from "react";
/**
* Copy and cut in a spreadsheet work inside a host that denies the page the Clipboard API.
*
* 问题:表格是画布应用,没有 DOM 选区,复制和剪切只能由页面自己调用浏览器的异步剪贴板接口
* (`navigator.clipboard.write()`),而这个接口要先通过浏览器的权限检查。像 DeepSeek Harness(DSH)
* 桌面端这样的宿主,对内嵌网页的会话一律拒绝所有权限,写入就以 `NotAllowedError` 失败:表格引擎弹出
* “无法访问剪贴板”,内容根本没进系统剪贴板,Cmd+C / Cmd+X 完全不可用。有选区的普通网页还能靠右键菜单
* 或菜单栏的原生复制,画布类应用没有任何替代路径。
*
* 做法:只针对“写入被权限拒绝”这一种失败,改走浏览器更早的复制方式:临时监听一次 `copy` 事件,把要复制
* 的文本和 HTML 写进事件自带的剪贴板数据,再调用 `document.execCommand("copy")`。它不经过权限检查,只要求
* 页面有焦点,并且仍处于用户的按键或点击之后。表格引擎自己带着这份实现,但只在浏览器完全没有异步剪贴板
* 接口时才用;这里补上“接口存在、却被拒绝”的情况。
*
* 范围:普通浏览器里异步接口会成功,这里什么都不做;只有被拒绝时才回退,且回退只写 `text/plain` 和
* `text/html`。读取剪贴板、粘贴和其它错误都不碰。表格视图关闭后还原。
*
* 为什么也包 `writeText`:它和 `write` 一样要过权限检查。表格页面打开期间,页面上会调用它的地方是
* “分享”对话框里的“复制链接”按钮;不一起处理的话,同一个页面里表格能复制、按钮却失败,说不通。
* 这个包装是页面级的,所以它只在表格视图存在时生效,别的页面不受影响。
*
* The old command is deprecated but every current browser still ships it. A browser that drops it makes copy fail
* again in a denying host, where the denial itself has to be fixed (DSH: discussion 10603).
*/
/** The two text formats the old way of copying can write. */
type TextFormats = { text?: string; html?: string };
const PLAIN = "text/plain";
const HTML = "text/html";
/** Chromium reports a denied permission under this name, as it does an unfocused document. */
const DENIED = "NotAllowedError";
const isDenied = (error: unknown): boolean =>
(error as { name?: unknown } | null)?.name === DENIED;
/** Whether a key press or click of the user still counts; the old command only runs inside one. */
const insideUserAction = (): boolean =>
!navigator.userActivation || navigator.userActivation.isActive;
/** Reads the text formats of what the page asked to write; rejects when the browser cannot tell. */
async function textFormats(
items: readonly ClipboardItem[],
): Promise<TextFormats> {
const formats: TextFormats = {};
for (const item of items) {
for (const [type, key] of [
[PLAIN, "text"],
[HTML, "html"],
] as const) {
if (formats[key] !== undefined || !item.types.includes(type)) continue;
const data = await item.getType(type);
formats[key] = typeof data === "string" ? data : await data.text();
}
}
return formats;
}
/**
* The browser's earlier way of copying: a `copy` event carries the data and the browser's own copy command runs it.
* The answer is false when the browser did not run the command with that data.
*/
function legacyCopy(formats: TextFormats): boolean {
let handled = false;
const onCopy = (event: ClipboardEvent) => {
if (!event.clipboardData) return;
event.preventDefault();
if (formats.text !== undefined)
event.clipboardData.setData(PLAIN, formats.text);
if (formats.html !== undefined)
event.clipboardData.setData(HTML, formats.html);
handled = true;
};
const copy = () =>
typeof document.execCommand === "function" &&
document.execCommand("copy");
document.addEventListener("copy", onCopy);
try {
// What counts is the event carrying the data, not the command's answer: browsers differ on it once a listener
// has taken the event over.
copy();
if (handled) return true;
// With no caret or selection to act on, a browser may skip the event; a field holding the text gives it one.
handled = false;
const active = document.activeElement as HTMLElement | null;
const selection = document.getSelection();
const ranges = selection
? Array.from(
{ length: selection.rangeCount },
(_, index) => selection.getRangeAt(index).cloneRange(),
)
: [];
const field = document.createElement("textarea");
field.value = formats.text ?? "";
field.readOnly = true;
field.tabIndex = -1;
// 16px keeps iOS from zooming into a focused field; the field itself stays off the page.
field.style.cssText =
"position:fixed;left:-9999px;top:0;font-size:16px;opacity:0";
document.body.append(field);
try {
// Focusing the field must not scroll the sheet to make it visible.
field.focus({ preventScroll: true });
field.select();
field.setSelectionRange(0, field.value.length);
copy();
return handled;
} finally {
field.remove();
active?.focus({ preventScroll: true });
if (selection) {
selection.removeAllRanges();
for (const range of ranges) selection.addRange(range);
}
}
} finally {
document.removeEventListener("copy", onCopy);
}
}
/**
* Puts the fallback in front of one write method of the page's clipboard; the returned function takes it back out.
* `write` carries the grid's copy and cut, `writeText` the share dialog's copy-link button of the same page.
*/
function wrapClipboardMethod(
clipboard: Clipboard,
name: "write" | "writeText",
): (() => void) | undefined {
const original = clipboard[name];
if (typeof original !== "function") return undefined;
const write = async function (
this: Clipboard,
argument: ClipboardItem[] | string,
): Promise<void> {
try {
return await (original as (...values: unknown[]) => Promise<void>).call(
this,
argument,
);
} catch (error) {
// Only a write denied inside the user's own action is tried again the old way, and only for text.
if (!isDenied(error) || !insideUserAction()) throw error;
let formats: TextFormats;
try {
formats =
name === "writeText"
? { text: argument as string }
: await textFormats(argument as ClipboardItem[]);
} catch {
throw error;
}
if (formats.text === undefined && formats.html === undefined) throw error;
if (!legacyCopy(formats)) throw error;
}
};
const own = Object.getOwnPropertyDescriptor(clipboard, name);
Object.defineProperty(clipboard, name, {
configurable: true,
writable: true,
value: write,
});
return () => {
if (own) Object.defineProperty(clipboard, name, own);
else delete (clipboard as unknown as Record<string, unknown>)[name];
};
}
const restoreFns: (() => void)[] = [];
let views = 0;
/**
* While at least one spreadsheet view is open, a copy or cut the page is denied falls back to the old way.
* Call it once per view; each returned function closes that view.
*/
export function installSheetClipboardWriteFallback(): () => void {
views += 1;
const clipboard = navigator.clipboard;
if (views === 1 && clipboard) {
for (const name of ["write", "writeText"] as const) {
const takeBack = wrapClipboardMethod(clipboard, name);
if (takeBack) restoreFns.push(takeBack);
}
}
let closed = false;
return () => {
if (closed) return;
closed = true;
if (--views > 0) return;
for (const restore of restoreFns.splice(0)) restore();
};
}
/**
* Keeps the clipboard fallback of the spreadsheet in place for as long as the view is mounted.
*
* 每个挂载表格编辑器的组件都要调用它——完整文档页、只读预览(回收站、引用预览)和模板里的表格。
* 漏掉一处,那一处的复制在拒绝权限的宿主里就仍然失败;新增挂载点时请一并加上。
* `enabled` 为 false 时什么都不做,留给同一组件有时显示表格、有时显示其它格式的情况。
*/
export function useSheetClipboardWriteFallback(enabled: boolean = true): void {
useEffect(() => (enabled ? installSheetClipboardWriteFallback() : undefined), [enabled]);
}