Files
monkey-ai-web/test/unit/clipboard.test.js
T
zhanjunhao 2aa9d73325 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

313 lines
9.5 KiB
JavaScript

import assert from 'node:assert/strict';
import test from 'node:test';
import { readFile } from 'node:fs/promises';
import {
copyText,
writeClipboardText,
writeClipboardImage,
} from '../../src/helpers/clipboard.js';
function globals(t, values) {
for (const [key, value] of Object.entries(values)) {
const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
Object.defineProperty(globalThis, key, { value, configurable: true });
t.after(() => {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else delete globalThis[key];
});
}
}
function fallback({ result = true, throws = false, modal = false } = {}) {
const calls = [];
let textarea;
const container = { appendChild: () => calls.push(modal ? 'modal' : 'body') };
const active = {
selectionStart: 2,
selectionEnd: 4,
selectionDirection: 'backward',
closest: () => (modal ? container : null),
focus: () => calls.push('restore-focus'),
setSelectionRange: (...range) => calls.push(['restore-input', ...range]),
};
const doc = {
body: modal
? { appendChild: () => assert.fail('must stay in modal') }
: container,
activeElement: active,
createElement: (tag) => {
assert.equal(tag, 'textarea');
textarea = {
style: {},
focus: () => calls.push('focus'),
select: () => calls.push('select'),
setSelectionRange: (...range) => calls.push(['select-range', ...range]),
remove: () => calls.push('remove'),
};
return textarea;
},
execCommand: (command) => {
assert.equal(command, 'copy');
calls.push(['copy', textarea.value]);
if (throws) throw new Error('Copy blocked');
return result;
},
};
return { doc, calls };
}
test('modern clipboard preserves full multiline and Unicode text', async (t) => {
const values = [];
globals(t, {
navigator: {
clipboard: { writeText: async (value) => values.push(value) },
},
document: undefined,
});
const text = 'fixture-key-unmasked\n\u4e2d\u6587\nlast line';
assert.equal(await copyText(text), true);
assert.deepEqual(values, [text]);
});
for (const mode of ['missing', 'partial', 'reject', 'sync-throw']) {
test(`text fallback works when Clipboard API is ${mode}`, async (t) => {
const { doc, calls } = fallback();
const clipboard =
mode === 'partial'
? {}
: {
writeText:
mode === 'reject'
? async () => {
throw new Error('Permission denied');
}
: () => {
throw new Error('Unavailable');
},
};
globals(t, {
navigator: mode === 'missing' ? {} : { clipboard },
document: doc,
});
assert.equal(await copyText('complete-fixture-key'), true);
assert.ok(
calls.some(
(call) =>
Array.isArray(call) &&
call[0] === 'copy' &&
call[1] === 'complete-fixture-key',
),
);
assert.ok(calls.includes('remove'));
assert.deepEqual(calls.at(-1), ['restore-input', 2, 4, 'backward']);
});
}
test('legacy selection stays within the active modal and restores DOM selection', async (t) => {
const { doc, calls } = fallback({ modal: true });
const range = {};
doc.getSelection = () => ({
rangeCount: 1,
getRangeAt: () => ({ cloneRange: () => range }),
removeAllRanges: () => calls.push('clear-ranges'),
addRange: (value) => {
assert.equal(value, range);
calls.push('restore-range');
},
});
globals(t, { navigator: {}, document: doc });
assert.equal(await copyText('modal-fixture'), true);
assert.ok(calls.includes('modal'));
assert.equal(calls.at(-1), 'restore-range');
});
for (const failure of [{ result: false }, { throws: true }]) {
test(`failed legacy copy reports failure and cleans up (${JSON.stringify(failure)})`, async (t) => {
const { doc, calls } = fallback(failure);
globals(t, { navigator: {}, document: doc });
assert.equal(await copyText('fixture'), false);
await assert.rejects(
writeClipboardText('fixture'),
/Clipboard copy failed/,
);
assert.equal(calls.filter((call) => call === 'remove').length, 2);
assert.ok(calls.includes('restore-focus'));
});
}
test('unsupported environments and absent values fail without throwing', async (t) => {
globals(t, { navigator: undefined, document: undefined });
assert.equal(await copyText('fixture'), false);
assert.equal(await copyText(null), false);
assert.equal(await copyText(undefined), false);
});
test('zero and empty text are copied without converting them to undefined', async (t) => {
const values = [];
globals(t, {
navigator: {
clipboard: { writeText: async (value) => values.push(value) },
},
});
assert.equal(await copyText(0), true);
assert.equal(await copyText(''), true);
assert.deepEqual(values, ['0', '']);
});
test('PNG image copy keeps the original blob', async (t) => {
const png = new Blob(['fixture'], { type: 'image/png' });
const items = [];
globals(t, {
navigator: { clipboard: { write: async (value) => items.push(value) } },
ClipboardItem: class {
constructor(data) {
this.data = data;
}
},
});
await writeClipboardImage(png);
assert.equal(items[0][0].data['image/png'], png);
});
test('JPEG image bytes are converted to PNG before writing and bitmap is released', async (t) => {
const png = new Blob(['converted'], { type: 'image/png' });
let closed = false;
let written;
globals(t, {
navigator: {
clipboard: {
write: async (value) => {
written = value;
},
},
},
ClipboardItem: class {
constructor(data) {
this.data = data;
}
},
createImageBitmap: async () => ({
width: 10,
height: 20,
close: () => {
closed = true;
},
}),
document: {
createElement: () => ({
getContext: () => ({ drawImage() {} }),
toBlob: (callback, type) => {
assert.equal(type, 'image/png');
callback(png);
},
}),
},
});
await writeClipboardImage(new Blob(['jpeg'], { type: 'image/jpeg' }));
assert.equal(written[0].data['image/png'], png);
assert.equal(closed, true);
});
test('unsupported image clipboard rejects instead of pretending success', async (t) => {
globals(t, { navigator: {}, ClipboardItem: undefined });
await assert.rejects(
writeClipboardImage(new Blob()),
/Image clipboard unavailable/,
);
});
const orgSource = (
await readFile(
new URL('../../src/pages/Organization/OrgTokens.jsx', import.meta.url),
'utf8',
)
).replaceAll('\r\n', '\n');
function orgHandler(name, bindings) {
const match = orgSource.match(
new RegExp(`(?:^|\n)([ \\t]*)const ${name} = ([\\s\\S]*?)\n\\1};`),
);
assert.ok(match, `Missing current handler: ${name}`);
return new Function(...Object.keys(bindings), `return ${match[2]}\n};`)(
...Object.values(bindings),
);
}
for (const name of ['copyText', 'handleCopyKey', 'handleCopyModel']) {
for (const succeeds of [true, false]) {
test(`org tokens ${name} reports the actual copy result (${succeeds})`, async () => {
const feedback = [];
const copied = [];
const state = [];
const cleared = [];
const timers = [];
const t = (text) => text;
const copyText = orgHandler('copyText', {
copy: async (text) => {
copied.push(text);
return succeeds;
},
Toast: {
success: (text) => feedback.push(['success', text]),
error: (text) => feedback.push(['error', text]),
},
});
const handler =
name === 'copyText'
? (text) => copyText(text, t)
: orgHandler(name, {
copyText,
t,
loadFullKey: async (id) => {
assert.equal(id, 42);
return 'full-fixture-key';
},
setCopiedId: (value) => state.push(value),
setCopiedModel: (value) => state.push(value),
copiedTimer: { current: 'previous-key-timer' },
copiedModelTimer: { current: 'previous-model-timer' },
clearTimeout: (value) => cleared.push(value),
setTimeout: (callback, delay) => {
assert.equal(delay, 1500);
timers.push(callback);
return 'next-timer';
},
});
const result = await handler(
name === 'handleCopyKey' ? 42 : 'full-fixture-key',
);
assert.deepEqual(copied, ['full-fixture-key']);
assert.deepEqual(feedback, [
[
succeeds ? 'success' : 'error',
succeeds
? name === 'handleCopyModel'
? '已复制模型名称'
: '已复制到剪贴板'
: '复制失败,请手动复制',
],
]);
if (name === 'copyText') assert.equal(result, succeeds);
else {
assert.deepEqual(
state,
succeeds ? [name === 'handleCopyKey' ? 42 : 'full-fixture-key'] : [],
);
assert.deepEqual(
cleared,
succeeds
? [
name === 'handleCopyKey'
? 'previous-key-timer'
: 'previous-model-timer',
]
: [],
);
assert.equal(timers.length, succeeds ? 1 : 0);
if (succeeds) {
timers[0]();
assert.equal(state.at(-1), null);
}
}
});
}
}