fix: 兼容低版本浏览器消息复制

- 为 Chrome 90 增加剪贴板兼容回退

- 统一聊天与智能体试运行的原色对勾反馈
This commit is contained in:
2026-07-22 20:07:34 +08:00
parent 5a3d4788da
commit 9f06c238d3
15 changed files with 423 additions and 83 deletions

View File

@@ -0,0 +1,108 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { copyTextToClipboard } from '../clipboard';
describe('copyTextToClipboard', () => {
const originalClipboard = Object.getOwnPropertyDescriptor(
navigator,
'clipboard',
);
const originalExecCommand = Object.getOwnPropertyDescriptor(
document,
'execCommand',
);
const originalSecureContext = Object.getOwnPropertyDescriptor(
globalThis,
'isSecureContext',
);
beforeEach(() => {
Object.defineProperty(document, 'execCommand', {
configurable: true,
value: vi.fn(() => true),
});
});
afterEach(() => {
vi.restoreAllMocks();
restoreProperty(navigator, 'clipboard', originalClipboard);
restoreProperty(document, 'execCommand', originalExecCommand);
restoreProperty(globalThis, 'isSecureContext', originalSecureContext);
document
.querySelectorAll('textarea[aria-hidden="true"]')
.forEach((node) => node.remove());
});
it('uses Clipboard API in a secure context', async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
stubSecureContext(true);
stubClipboard(writeText);
await expect(copyTextToClipboard('测试内容')).resolves.toBe(
'clipboard-api',
);
expect(writeText).toHaveBeenCalledWith('测试内容');
expect(document.execCommand).not.toHaveBeenCalled();
});
it('falls back to execCommand in an insecure context', async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
stubSecureContext(false);
stubClipboard(writeText);
await expect(copyTextToClipboard('Chrome 90')).resolves.toBe(
'exec-command',
);
expect(writeText).not.toHaveBeenCalled();
expect(document.execCommand).toHaveBeenCalledWith('copy');
expect(document.querySelector('textarea[aria-hidden="true"]')).toBeNull();
});
it('falls back when Clipboard API is denied', async () => {
const writeText = vi.fn().mockRejectedValue(new DOMException('denied'));
stubSecureContext(true);
stubClipboard(writeText);
await expect(copyTextToClipboard('兼容内容')).resolves.toBe('exec-command');
expect(document.execCommand).toHaveBeenCalledWith('copy');
});
it('throws and cleans up when all copy methods fail', async () => {
stubSecureContext(false);
Object.defineProperty(document, 'execCommand', {
configurable: true,
value: vi.fn(() => false),
});
await expect(copyTextToClipboard('失败内容')).rejects.toThrow(
'浏览器拒绝了复制操作',
);
expect(document.querySelector('textarea[aria-hidden="true"]')).toBeNull();
});
function stubClipboard(writeText: ReturnType<typeof vi.fn>) {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
}
function stubSecureContext(value: boolean) {
Object.defineProperty(globalThis, 'isSecureContext', {
configurable: true,
value,
});
}
});
function restoreProperty(
target: object,
property: PropertyKey,
descriptor?: PropertyDescriptor,
) {
if (descriptor) {
Object.defineProperty(target, property, descriptor);
return;
}
Reflect.deleteProperty(target, property);
}

View File

@@ -0,0 +1,52 @@
export type ClipboardCopyMethod = 'clipboard-api' | 'exec-command';
/**
* 将文本写入系统剪贴板,并在现代 Clipboard API 不可用时降级处理。
*
* @param text 要复制的文本。
* @returns 实际使用的复制方式。
* @throws 当浏览器环境不可用或所有复制方式均失败时抛出异常。
*/
export async function copyTextToClipboard(
text: string,
): Promise<ClipboardCopyMethod> {
if (typeof document === 'undefined' || typeof navigator === 'undefined') {
throw new TypeError('当前环境不支持剪贴板操作');
}
if (globalThis.isSecureContext && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
return 'clipboard-api';
} catch {
// 权限或浏览器策略拒绝时继续使用兼容方案。
}
}
const textArea = document.createElement('textarea');
const activeElement = document.activeElement;
textArea.value = text;
textArea.readOnly = true;
textArea.setAttribute('aria-hidden', 'true');
textArea.style.position = 'fixed';
textArea.style.top = '0';
textArea.style.left = '-9999px';
textArea.style.opacity = '0';
try {
document.body.append(textArea);
textArea.focus({ preventScroll: true });
textArea.select();
textArea.setSelectionRange(0, textArea.value.length);
if (!document.execCommand('copy')) {
throw new Error('浏览器拒绝了复制操作');
}
return 'exec-command';
} finally {
textArea.remove();
if (activeElement instanceof HTMLElement) {
activeElement.focus({ preventScroll: true });
}
}
}

View File

@@ -1,5 +1,6 @@
export * from './chat-time';
export * from './chat-variant-switch';
export * from './clipboard';
export * from './find-menu-by-path';
export * from './generate-menus';
export * from './generate-routes-backend';