feat: 1.统一右侧抽屉关闭按钮布局 2.统一 UI 组件为 Ant Design 移除 radix-ui、floating-ui 组件 3. 修复 ESLint 文件格式错误的问题
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { setImmediate } from 'node:timers/promises';
|
||||
import React from 'react';
|
||||
import { createHookRuntime } from './helpers/hookRuntime.js';
|
||||
import { loadFrontendModule } from './helpers/frontendModule.js';
|
||||
|
||||
async function harness() {
|
||||
const runtime = createHookRuntime();
|
||||
const { useEffectEvent } = await loadFrontendModule(
|
||||
new URL('../../src/hooks/common/useEffectEvent.js', import.meta.url),
|
||||
{ react: runtime.react },
|
||||
);
|
||||
return { runtime, useEffectEvent };
|
||||
}
|
||||
|
||||
test('effect events keep identity and only expose the latest committed callback', async () => {
|
||||
const { runtime, useEffectEvent } = await harness();
|
||||
const Component = ({ value }) => useEffectEvent((extra) => value + extra);
|
||||
const first = runtime.render(Component, { value: 1 });
|
||||
runtime.commit();
|
||||
assert.equal(first(2), 3);
|
||||
const updated = runtime.render(Component, { value: 10 });
|
||||
assert.equal(updated, first);
|
||||
assert.equal(
|
||||
first(2),
|
||||
3,
|
||||
'An uncommitted render must not leak to external handlers',
|
||||
);
|
||||
runtime.commit();
|
||||
assert.equal(first(2), 12);
|
||||
});
|
||||
|
||||
test('explicit scope changes run once and cleanup keeps its original resource', async () => {
|
||||
const { runtime, useEffectEvent } = await harness();
|
||||
const calls = [];
|
||||
const cleanups = [];
|
||||
const Component = ({ scope, draft }) => {
|
||||
const onChange = useEffectEvent(() => {
|
||||
calls.push([scope, draft]);
|
||||
return () => cleanups.push(scope);
|
||||
});
|
||||
runtime.react.useEffect(() => onChange(), [onChange, scope]);
|
||||
};
|
||||
runtime.render(Component, { scope: 1, draft: 'a' });
|
||||
runtime.flush();
|
||||
runtime.render(Component, { scope: 1, draft: 'b' });
|
||||
runtime.flush();
|
||||
assert.deepEqual(
|
||||
calls,
|
||||
[[1, 'a']],
|
||||
'Editing a draft must not reinitialize the form',
|
||||
);
|
||||
runtime.render(Component, { scope: 2, draft: 'b' });
|
||||
runtime.flush();
|
||||
assert.deepEqual(calls, [
|
||||
[1, 'a'],
|
||||
[2, 'b'],
|
||||
]);
|
||||
assert.deepEqual(cleanups, [1]);
|
||||
runtime.unmount();
|
||||
assert.deepEqual(cleanups, [1, 2]);
|
||||
});
|
||||
|
||||
test('event callbacks preserve return values, async results, and errors', async () => {
|
||||
const { runtime, useEffectEvent } = await harness();
|
||||
const AsyncComponent = () => useEffectEvent(async (value) => value * 2);
|
||||
const asyncEvent = runtime.render(AsyncComponent);
|
||||
runtime.commit();
|
||||
assert.equal(await asyncEvent(4), 8);
|
||||
const ThrowingComponent = () =>
|
||||
useEffectEvent(() => {
|
||||
throw new Error('expected failure');
|
||||
});
|
||||
runtime.render(ThrowingComponent);
|
||||
runtime.commit();
|
||||
assert.throws(asyncEvent, /expected failure/);
|
||||
});
|
||||
|
||||
test('settings mount and manual refresh settle without repeated option requests', async () => {
|
||||
const { runtime, useEffectEvent } = await harness();
|
||||
const requests = [];
|
||||
const { default: Settings } = await loadFrontendModule(
|
||||
new URL('../../src/components/settings/ChatsSetting.jsx', import.meta.url),
|
||||
{
|
||||
react: runtime.react,
|
||||
'../../hooks/common/useEffectEvent': { useEffectEvent },
|
||||
'@/components/ui': { Card: 'Card', Spin: 'Spin' },
|
||||
'../../pages/Setting/Chat/SettingsChats': {
|
||||
default: 'SettingsChats',
|
||||
__esModule: true,
|
||||
},
|
||||
'../../helpers': {
|
||||
API: {
|
||||
get: async (url) => {
|
||||
requests.push(url);
|
||||
return {
|
||||
data: { success: true, data: [{ key: 'Chats', value: '[]' }] },
|
||||
};
|
||||
},
|
||||
},
|
||||
showError: assert.fail,
|
||||
toBoolean: (value) => value === 'true',
|
||||
},
|
||||
},
|
||||
);
|
||||
runtime.render(Settings);
|
||||
runtime.flush();
|
||||
await setImmediate();
|
||||
let tree = runtime.flush();
|
||||
assert.deepEqual(requests, ['/api/option/']);
|
||||
const find = (node) =>
|
||||
React.isValidElement(node)
|
||||
? node.type === 'SettingsChats'
|
||||
? node
|
||||
: React.Children.toArray(node.props.children).map(find).find(Boolean)
|
||||
: undefined;
|
||||
await find(tree).props.refresh();
|
||||
tree = runtime.flush();
|
||||
assert.deepEqual(requests, ['/api/option/', '/api/option/']);
|
||||
assert.equal(find(tree).props.options.Chats, '[]');
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"src/pages/AdminOrganizations/index.jsx": 1,
|
||||
"src/pages/AdminInvoice/index.jsx": 1,
|
||||
"src/components/settings/DataSecuritySetting.jsx": 4,
|
||||
"src/pages/Organization/OrgPrivateSkills.jsx": 2,
|
||||
"src/pages/Organization/OrgSkillAssignments.jsx": 1,
|
||||
"src/pages/Organization/OrgEffectiveness.jsx": 4,
|
||||
"src/pages/Organization/OrgMemberAccounts.jsx": 1,
|
||||
"src/pages/Organization/OrgDeptManage.jsx": 2,
|
||||
"src/pages/Organization/OrgProjectManage.jsx": 1,
|
||||
"src/pages/Organization/OrgProjects.jsx": 2,
|
||||
"src/pages/Organization/OrgBudgets.jsx": 1,
|
||||
"src/pages/Organization/OrgLogs.jsx": 1,
|
||||
"src/pages/Organization/components/OrgTaskRecords.jsx": 1,
|
||||
"src/pages/Organization/datasecurity/OrgDsRules.jsx": 2
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { transformWithEsbuild } from 'vite';
|
||||
|
||||
export async function loadFrontendModule(filename, mocks) {
|
||||
const { code } = await transformWithEsbuild(
|
||||
await readFile(filename, 'utf8'),
|
||||
filename.pathname,
|
||||
{
|
||||
loader: 'jsx',
|
||||
format: 'cjs',
|
||||
jsx: 'transform',
|
||||
define: { 'import.meta.env': '{}' },
|
||||
},
|
||||
);
|
||||
const module = { exports: {} };
|
||||
new Function('require', 'module', 'exports', code)(
|
||||
(name) => {
|
||||
assert.ok(Object.hasOwn(mocks, name), 'Missing test dependency: ' + name);
|
||||
return mocks[name];
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import React from 'react';
|
||||
|
||||
// A deterministic controller harness, not a replacement for React's DOM scheduler.
|
||||
export function createHookRuntime() {
|
||||
const slots = [];
|
||||
let cursor = 0;
|
||||
let dirty = false;
|
||||
let renderCurrent;
|
||||
let output;
|
||||
let pending = [];
|
||||
const changed = (before, after) =>
|
||||
!before ||
|
||||
!after ||
|
||||
before.length !== after.length ||
|
||||
after.some((v, i) => !Object.is(v, before[i]));
|
||||
const react = {
|
||||
...React,
|
||||
useState(initial) {
|
||||
const index = cursor++;
|
||||
if (!slots[index]) {
|
||||
const slot = {
|
||||
value: typeof initial === 'function' ? initial() : initial,
|
||||
};
|
||||
slot.set = (next) => {
|
||||
const value = typeof next === 'function' ? next(slot.value) : next;
|
||||
if (!Object.is(value, slot.value)) {
|
||||
slot.value = value;
|
||||
dirty = true;
|
||||
}
|
||||
};
|
||||
slots[index] = slot;
|
||||
}
|
||||
return [slots[index].value, slots[index].set];
|
||||
},
|
||||
useRef(initial) {
|
||||
const index = cursor++;
|
||||
slots[index] ??= { current: initial };
|
||||
return slots[index];
|
||||
},
|
||||
useMemo(factory, dependencies) {
|
||||
const index = cursor++;
|
||||
if (changed(slots[index]?.dependencies, dependencies))
|
||||
slots[index] = { value: factory(), dependencies };
|
||||
return slots[index].value;
|
||||
},
|
||||
useCallback(callback, dependencies) {
|
||||
return react.useMemo(() => callback, dependencies);
|
||||
},
|
||||
useEffect(callback, dependencies) {
|
||||
const index = cursor++;
|
||||
if (changed(slots[index]?.dependencies, dependencies))
|
||||
pending.push({ index, callback, dependencies });
|
||||
},
|
||||
};
|
||||
react.useLayoutEffect = react.useEffect;
|
||||
const runtime = {
|
||||
react,
|
||||
render(component, props = {}) {
|
||||
cursor = 0;
|
||||
pending = [];
|
||||
dirty = false;
|
||||
renderCurrent = () => runtime.render(component, props);
|
||||
output = component(props);
|
||||
return output;
|
||||
},
|
||||
commit() {
|
||||
const effects = pending;
|
||||
pending = [];
|
||||
for (const { index, callback, dependencies } of effects) {
|
||||
slots[index]?.cleanup?.();
|
||||
slots[index] = { dependencies, cleanup: callback() };
|
||||
}
|
||||
},
|
||||
flush() {
|
||||
for (let i = 0; ; i++) {
|
||||
assert.ok(i < 20, 'Effects must settle without a render/request loop');
|
||||
runtime.commit();
|
||||
if (!dirty) return output;
|
||||
renderCurrent();
|
||||
}
|
||||
},
|
||||
unmount() {
|
||||
for (const slot of slots) slot?.cleanup?.();
|
||||
},
|
||||
};
|
||||
return runtime;
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { Table as AntTable } from 'antd';
|
||||
import { loadFrontendModule } from './helpers/frontendModule.js';
|
||||
|
||||
async function fixture(kind) {
|
||||
const calls = [];
|
||||
const models = Array.from(
|
||||
{ length: 24 },
|
||||
(_, i) => 'aa-' + String(i + 1).padStart(2, '0'),
|
||||
);
|
||||
const states =
|
||||
kind === 'Missing' ? [5, false, models, 'AA', 2] : [5, {}, 2, 'AA'];
|
||||
let cursor = 0;
|
||||
const react = {
|
||||
...React,
|
||||
useEffect: () => {},
|
||||
useMemo: (fn) => fn(),
|
||||
useCallback: (fn) => fn,
|
||||
useState: () => {
|
||||
const index = cursor++;
|
||||
return [states[index], (value) => calls.push([index, value])];
|
||||
},
|
||||
};
|
||||
const ui = {
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'Modal',
|
||||
'Table',
|
||||
'Spin',
|
||||
'Button',
|
||||
'Empty',
|
||||
'Input',
|
||||
'Checkbox',
|
||||
'Tag',
|
||||
'Popover',
|
||||
].map((name) => [name, name]),
|
||||
),
|
||||
Typography: { Text: 'Text' },
|
||||
};
|
||||
const file =
|
||||
kind === 'Missing' ? 'MissingModelsModal' : 'UpstreamConflictModal';
|
||||
const { default: Component } = await loadFrontendModule(
|
||||
new URL(
|
||||
'../../src/components/table/models/modals/' + file + '.jsx',
|
||||
import.meta.url,
|
||||
),
|
||||
{
|
||||
react,
|
||||
'@/components/ui': ui,
|
||||
'../../../../hooks/common/useEffectEvent': {
|
||||
useEffectEvent: (callback) => callback,
|
||||
},
|
||||
'../../../../hooks/common/useIsMobile': { useIsMobile: () => false },
|
||||
'../../../../constants': { MODEL_TABLE_PAGE_SIZE: 10 },
|
||||
'../../../../helpers': {
|
||||
API: {
|
||||
get: () => assert.fail('Local pagination must not send requests'),
|
||||
},
|
||||
showError: assert.fail,
|
||||
hoverOrClickTrigger: () => 'hover',
|
||||
},
|
||||
'../../../common/illustrations': {
|
||||
IllustrationNoResult: 'Illustration',
|
||||
IllustrationNoResultDark: 'Illustration',
|
||||
},
|
||||
'@/components/ui/icons': { IconSearch: 'Search' },
|
||||
'lucide-react': { MousePointerClick: 'Pointer' },
|
||||
},
|
||||
);
|
||||
const tree = Component({
|
||||
visible: true,
|
||||
t: (key) => key,
|
||||
conflicts: models.map((model_name) => ({ model_name, fields: [] })),
|
||||
});
|
||||
const find = (type, node = tree) =>
|
||||
React.isValidElement(node)
|
||||
? [
|
||||
...(node.type === type ? [node] : []),
|
||||
...React.Children.toArray(node.props.children).flatMap((child) =>
|
||||
find(type, child),
|
||||
),
|
||||
]
|
||||
: [];
|
||||
return {
|
||||
calls,
|
||||
models,
|
||||
table: find('Table')[0].props,
|
||||
input: find('Input')[0].props,
|
||||
};
|
||||
}
|
||||
|
||||
for (const kind of ['Missing', 'Upstream']) {
|
||||
test(
|
||||
kind + ': case-insensitive local filtering uses selected page and size',
|
||||
async () => {
|
||||
const { table, models } = await fixture(kind);
|
||||
assert.deepEqual(
|
||||
Array.from(table.dataSource, (row) => row.model || row.model_name),
|
||||
models.slice(5, 10),
|
||||
);
|
||||
assert.equal(table.pagination.total, 24);
|
||||
assert.equal(table.pagination.pageSize, 5);
|
||||
assert.equal(table.pagination.currentPage, 2);
|
||||
},
|
||||
);
|
||||
test(
|
||||
kind +
|
||||
': search and size changes reset the current page without network calls',
|
||||
async () => {
|
||||
const { calls, table, input } = await fixture(kind);
|
||||
table.pagination.onPageSizeChange(20);
|
||||
assert.ok(calls.some(([, value]) => value === 1));
|
||||
assert.ok(calls.some(([, value]) => value === 20));
|
||||
calls.length = 0;
|
||||
input.onChange('aa-24');
|
||||
assert.ok(calls.some(([, value]) => value === 'aa-24'));
|
||||
assert.ok(calls.some(([, value]) => value === 1));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function modelTestFixture() {
|
||||
const calls = [];
|
||||
const models = Array.from({ length: 24 }, (_, index) => `aa-${index + 1}`);
|
||||
const { default: Component } = await loadFrontendModule(
|
||||
new URL(
|
||||
'../../src/components/table/channels/modals/ModelTestModal.jsx',
|
||||
import.meta.url,
|
||||
),
|
||||
{
|
||||
react: {
|
||||
...React,
|
||||
useState: () => [5, (value) => calls.push(['size', value])],
|
||||
},
|
||||
antd: {
|
||||
...Object.fromEntries(
|
||||
['Modal', 'Button', 'Input', 'Table', 'Tag', 'Select'].map((name) => [
|
||||
name,
|
||||
name,
|
||||
]),
|
||||
),
|
||||
Typography: { Text: 'Text' },
|
||||
},
|
||||
'lucide-react': { Search: 'Search' },
|
||||
'./model-test-modal.css': {},
|
||||
'../../../../helpers': {},
|
||||
'../../../../constants': { MODEL_TABLE_PAGE_SIZE: 10 },
|
||||
},
|
||||
);
|
||||
const tree = Component({
|
||||
currentTestChannel: { id: 7, name: 'channel', models: models.join(',') },
|
||||
modelSearchKeyword: 'AA',
|
||||
modelTablePage: 2,
|
||||
selectedModelKeys: [],
|
||||
modelTestResults: {},
|
||||
testingModels: new Set(),
|
||||
setModelTablePage: (value) => calls.push(['page', value]),
|
||||
setModelSearchKeyword: (value) => calls.push(['search', value]),
|
||||
t: (key) => key,
|
||||
});
|
||||
const find = (type, node = tree) =>
|
||||
React.isValidElement(node)
|
||||
? [
|
||||
...(node.type === type ? [node] : []),
|
||||
...React.Children.toArray(node.props.children).flatMap((child) =>
|
||||
find(type, child),
|
||||
),
|
||||
]
|
||||
: [];
|
||||
return {
|
||||
calls,
|
||||
models,
|
||||
table: find('Table')[0].props,
|
||||
input: find('Input')[0].props,
|
||||
};
|
||||
}
|
||||
|
||||
test('Model test dialog passes the complete filtered list to native Ant pagination', async () => {
|
||||
const { table, models } = await modelTestFixture();
|
||||
assert.deepEqual(
|
||||
Array.from(table.dataSource, (row) => row.model),
|
||||
models,
|
||||
);
|
||||
assert.equal(table.pagination.total, 24);
|
||||
assert.equal(table.pagination.current, 2);
|
||||
assert.equal(table.pagination.pageSize, 5);
|
||||
const html = renderToStaticMarkup(React.createElement(AntTable, table));
|
||||
assert.deepEqual(
|
||||
Array.from(html.matchAll(/data-row-key="([^"]+)"/g), (match) => match[1]),
|
||||
models.slice(5, 10),
|
||||
'Ant Table renders only the selected page, with no second manual slice',
|
||||
);
|
||||
});
|
||||
|
||||
test('Model test dialog preserves page changes and resets after search or size changes', async () => {
|
||||
const { calls, table, input } = await modelTestFixture();
|
||||
table.pagination.onChange(3, 5);
|
||||
assert.deepEqual(calls.splice(0), [
|
||||
['page', 3],
|
||||
['size', 5],
|
||||
]);
|
||||
table.pagination.onChange(3, 20);
|
||||
assert.deepEqual(calls.splice(0), [
|
||||
['page', 1],
|
||||
['size', 20],
|
||||
]);
|
||||
input.onChange({ target: { value: 'aa-24' } });
|
||||
assert.deepEqual(calls, [
|
||||
['search', 'aa-24'],
|
||||
['page', 1],
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,555 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import fs from 'node:fs/promises';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import { parse } from '@babel/parser';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import * as Ant from 'antd';
|
||||
import { transformWithEsbuild } from 'vite';
|
||||
import i18next from 'i18next';
|
||||
import * as pagination from '../../src/components/ui/pagination.js';
|
||||
|
||||
await i18next.init({
|
||||
lng: 'zh',
|
||||
initImmediate: false,
|
||||
resources: { zh: { translation: { '共 {{total}} 条': '共 {{total}} 条' } } },
|
||||
});
|
||||
const walk = (node, visit) => {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (node.type) visit(node);
|
||||
for (const [key, val] of Object.entries(node))
|
||||
if (!['loc', 'start', 'end'].includes(key)) {
|
||||
if (Array.isArray(val)) val.forEach((n) => walk(n, visit));
|
||||
else if (val && typeof val === 'object') walk(val, visit);
|
||||
}
|
||||
};
|
||||
async function callback(file, name, rootName) {
|
||||
const source = await fs.readFile(file, 'utf8');
|
||||
const ast = parse(source, { sourceType: 'module', plugins: ['jsx'] });
|
||||
let root = ast;
|
||||
if (rootName)
|
||||
walk(ast, (n) => {
|
||||
if (n.type === 'FunctionDeclaration' && n.id?.name === rootName) root = n;
|
||||
});
|
||||
let found;
|
||||
walk(root, (n) => {
|
||||
if (!found && n.type === 'VariableDeclarator' && n.id.name === name)
|
||||
found =
|
||||
n.init?.callee?.name === 'useCallback' ? n.init.arguments[0] : n.init;
|
||||
});
|
||||
assert.ok(found, `${file}: ${name} exists`);
|
||||
return { source: source.slice(found.start, found.end), root, text: source };
|
||||
}
|
||||
const sentinel = { id: 42, name: 'pagination-fixture' };
|
||||
async function exercise(
|
||||
{
|
||||
file,
|
||||
fn,
|
||||
root,
|
||||
args = [],
|
||||
expectedPath,
|
||||
expectedSize = 50,
|
||||
expectedPage = 3,
|
||||
pageKey = 'p',
|
||||
values = {},
|
||||
},
|
||||
failure = false,
|
||||
) {
|
||||
const { source, root: ast } = await callback(file, fn, root);
|
||||
const states = {},
|
||||
calls = [],
|
||||
errors = [];
|
||||
const context = {
|
||||
URLSearchParams,
|
||||
Date,
|
||||
Promise,
|
||||
console: { error() {} },
|
||||
page: 3,
|
||||
pageSize: 50,
|
||||
orgId: 77,
|
||||
pageSizeRef: { current: 50 },
|
||||
requestSeq: { current: 0 },
|
||||
seqRef: { current: 0 },
|
||||
orgRef: { current: 77 },
|
||||
fetchSeqRef: { current: 0 },
|
||||
searchKeyword: 'pagination-fixture',
|
||||
appliedKeyword: 'pagination-fixture',
|
||||
appliedOrderId: 42,
|
||||
appliedUserId: 7,
|
||||
statusFilter: '',
|
||||
paymentMethodFilter: '',
|
||||
dateRange: [],
|
||||
appliedMinMoney: undefined,
|
||||
appliedMaxMoney: undefined,
|
||||
levelFilter: '',
|
||||
salesRepFilter: '',
|
||||
alertFilter: '',
|
||||
userIdFilter: '',
|
||||
sortBy: '',
|
||||
sortOrder: '',
|
||||
endDateRange: [],
|
||||
quickFilter: '',
|
||||
planTypes: [],
|
||||
tiers: [],
|
||||
statuses: [],
|
||||
sources: [],
|
||||
getOrgHeaders: (id) => ({ 'X-Org-Id': String(id) }),
|
||||
t: (key) => key,
|
||||
showError: (e) => errors.push(e),
|
||||
getFormValues: () => ({
|
||||
username: '',
|
||||
token_name: '',
|
||||
model_name: '',
|
||||
start_timestamp: '2026-11-02 00:00:00',
|
||||
end_timestamp: '2026-11-07 23:44:54',
|
||||
channel: '',
|
||||
group: '',
|
||||
user_id: '',
|
||||
logType: 0,
|
||||
channel_id: '',
|
||||
mj_id: '',
|
||||
}),
|
||||
isAdminUser: true,
|
||||
listRequestIdRef: { current: 0 },
|
||||
logsRequestIdRef: { current: 0 },
|
||||
appliedExportParamsRef: { current: {} },
|
||||
...values,
|
||||
API: {
|
||||
get: async (url, options = {}) => {
|
||||
calls.push({ url, options });
|
||||
if (failure) throw new Error('simulated pagination failure');
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
items: [sentinel],
|
||||
list: [sentinel],
|
||||
total: 156,
|
||||
page: expectedPage,
|
||||
page_size: expectedSize,
|
||||
requests: { items: [sentinel], total: 156 },
|
||||
audits: { items: [sentinel], total: 156 },
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
walk(ast, (n) => {
|
||||
if (n.type === 'Identifier' && /^set[A-Z]/.test(n.name))
|
||||
context[n.name] ||= (val) => {
|
||||
states[n.name] = typeof val === 'function' ? val(states[n.name]) : val;
|
||||
};
|
||||
});
|
||||
const run = runInNewContext(`(${source})`, context);
|
||||
await run(...args);
|
||||
assert.ok(calls.length > 0, 'Uses the existing API wrapper');
|
||||
const request = calls.find((c) => c.url.startsWith(expectedPath));
|
||||
assert.ok(request, `${expectedPath} requested`);
|
||||
const u = new URL(request.url, 'http://localhost');
|
||||
const params = {
|
||||
...Object.fromEntries(u.searchParams),
|
||||
...request.options.params,
|
||||
};
|
||||
assert.equal(
|
||||
Number(params.page_size),
|
||||
expectedSize,
|
||||
'Selected page size reaches API',
|
||||
);
|
||||
assert.equal(
|
||||
Number(params[pageKey]),
|
||||
expectedPage,
|
||||
'Requested page reaches API without changing indexing',
|
||||
);
|
||||
if (failure) {
|
||||
if ('setLoading' in states)
|
||||
assert.equal(states.setLoading, false, 'Failure releases loading');
|
||||
assert.ok(
|
||||
errors.length > 0 || Boolean(states.setError),
|
||||
'Failure is reported by a message or inline error',
|
||||
);
|
||||
} else if ('setTotal' in states)
|
||||
assert.equal(states.setTotal, 156, 'Response total maps to pagination');
|
||||
return { calls, states, errors };
|
||||
}
|
||||
|
||||
for (const cfg of [
|
||||
{
|
||||
file: 'src/pages/AdminOrder/index.jsx',
|
||||
fn: 'fetchOrders',
|
||||
expectedPath: '/api/order/search',
|
||||
},
|
||||
{
|
||||
file: 'src/pages/AdminInvoice/index.jsx',
|
||||
fn: 'fetchInvoices',
|
||||
expectedPath: '/api/invoice/list',
|
||||
},
|
||||
{
|
||||
file: 'src/pages/AdminOrganizations/index.jsx',
|
||||
fn: 'fetchOrgs',
|
||||
expectedPath: '/api/admin/organizations',
|
||||
},
|
||||
{
|
||||
file: 'src/pages/Subscription/index.jsx',
|
||||
fn: 'fetchList',
|
||||
expectedPath: '/api/user/membership/manage/subscriptions',
|
||||
pageKey: 'page',
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/org/useOrgMembers.js',
|
||||
fn: 'fetch',
|
||||
root: 'useOrgMembers',
|
||||
args: [3, 50],
|
||||
expectedPath: '/api/org/members',
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/org/useOrgData.js',
|
||||
fn: 'fetch',
|
||||
root: 'useOrgTokens',
|
||||
args: [3, 50],
|
||||
expectedPath: '/api/org/tokens',
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/org/useOrgData.js',
|
||||
fn: 'fetch',
|
||||
root: 'useOrgAuditLogs',
|
||||
args: [3, 50, ''],
|
||||
expectedPath: '/api/org/audit',
|
||||
values: { seqRef: { current: 0 }, orgRef: { current: 77 } },
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/org/useOrgData.js',
|
||||
fn: 'fetch',
|
||||
root: 'useOrgPromptRecords',
|
||||
args: [3, 50, {}],
|
||||
expectedPath: '/api/org/prompt-archive/records',
|
||||
values: { seqRef: { current: 0 } },
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/org/useOrgData.js',
|
||||
fn: 'fetch',
|
||||
root: 'useOrgMemberLogs',
|
||||
args: [3, 50, {}],
|
||||
expectedPath: '/api/org/logs',
|
||||
values: { buildOrgLogFilters: (x) => x },
|
||||
},
|
||||
{
|
||||
file: 'src/pages/Organization/OrgRecharge.jsx',
|
||||
fn: 'fetchHistory',
|
||||
args: [3],
|
||||
expectedPath: '/api/org/topup',
|
||||
values: { historyPageSize: 50, orgHeaders: { 'X-Org-Id': '77' } },
|
||||
},
|
||||
{
|
||||
file: 'src/pages/Organization/OrgDashboard.jsx',
|
||||
fn: 'fetchLogs',
|
||||
args: [3, {}, 50],
|
||||
expectedPath: '/api/org/logs',
|
||||
values: { member: { user_id: 9 }, appliedFilters: {} },
|
||||
},
|
||||
{
|
||||
file: 'src/pages/Organization/datasecurity/OrgDsChanges.jsx',
|
||||
fn: 'fetchChanges',
|
||||
args: [{ reqP: 3, auditP: 2, section: 'requests' }],
|
||||
expectedPath: '/api/org/data-security/changes',
|
||||
pageKey: 'page',
|
||||
values: {
|
||||
reqSizeRef: { current: 50 },
|
||||
auditSizeRef: { current: 20 },
|
||||
headers: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
file: 'src/pages/Organization/datasecurity/OrgDsChanges.jsx',
|
||||
fn: 'fetchChanges',
|
||||
args: [{ reqP: 1, auditP: 3, section: 'audits' }],
|
||||
expectedPath: '/api/org/data-security/changes',
|
||||
pageKey: 'page',
|
||||
values: {
|
||||
reqSizeRef: { current: 20 },
|
||||
auditSizeRef: { current: 50 },
|
||||
headers: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
file: 'src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx',
|
||||
fn: 'refreshFeePolicy',
|
||||
args: [3, true],
|
||||
expectedPath: '/api/option/paypal/fee-policy/audits',
|
||||
values: { isRoot: () => true, feeAuditSizeRef: { current: 50 } },
|
||||
},
|
||||
{
|
||||
file: 'src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx',
|
||||
fn: 'refreshOperations',
|
||||
args: [3],
|
||||
expectedPath: '/api/option/paypal/operations/preflight',
|
||||
values: {
|
||||
isRoot: () => true,
|
||||
operationsSizeRef: { current: 50 },
|
||||
normalizePayPalOperations: (d) => d,
|
||||
},
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/analytics/useRiskControlData.js',
|
||||
fn: 'fetchBanLogs',
|
||||
args: [{ page: 3, pageSize: 50 }],
|
||||
expectedPath: '/api/analytics/risk/ban-logs',
|
||||
pageKey: 'page',
|
||||
values: { banLogStatus: 0, banLogPage: 1, banLogPageSize: 20 },
|
||||
},
|
||||
...[
|
||||
['loadAudits', 'audit', '/api/desensitize/config-audit'],
|
||||
['loadHitLogs', 'hitLog', '/api/desensitize/logs'],
|
||||
['loadChangeRequests', 'changeReq', '/api/desensitize/change-requests'],
|
||||
].map(([fn, name, expectedPath]) => ({
|
||||
file: 'src/components/settings/DataSecuritySetting.jsx',
|
||||
fn,
|
||||
args: [3],
|
||||
expectedPath,
|
||||
pageKey: 'page',
|
||||
values: { [`${name}PageSize`]: 50 },
|
||||
})),
|
||||
{
|
||||
file: 'src/pages/Organization/datasecurity/OrgDsHitLogs.jsx',
|
||||
fn: 'fetchLogs',
|
||||
args: [3, false],
|
||||
expectedPath: '/api/org/data-security/logs',
|
||||
pageKey: 'page',
|
||||
values: {
|
||||
logsSeqRef: { current: 0 },
|
||||
lastAttemptedPageRef: { current: 1 },
|
||||
headers: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/usage-logs/useUsageLogsData.jsx',
|
||||
fn: 'loadLogs',
|
||||
args: [3, 50],
|
||||
expectedPath: '/api/log/',
|
||||
values: { setLogsFormat: () => {} },
|
||||
},
|
||||
{
|
||||
file: 'src/hooks/mj-logs/useMjLogsData.js',
|
||||
fn: 'loadLogs',
|
||||
args: [3, 50],
|
||||
expectedPath: '/api/mj/',
|
||||
values: { syncPageData: () => {} },
|
||||
},
|
||||
]) {
|
||||
test(`${cfg.file}: selected page and size use existing request contract`, () =>
|
||||
exercise(cfg));
|
||||
test(`${cfg.file}: network failure exits loading and reports error`, () =>
|
||||
exercise(cfg, true));
|
||||
}
|
||||
|
||||
test('Resizing emits one size callback and never a stale page request', () => {
|
||||
const calls = [];
|
||||
const events = pagination.centerPaginationEvents({
|
||||
pageSize: 10,
|
||||
onPageSizeChange: (s) => calls.push(['size', s]),
|
||||
onPageChange: (p) => calls.push(['page', p]),
|
||||
onChange: (p, s) => calls.push(['change', p, s]),
|
||||
});
|
||||
events.onChange(3, 50);
|
||||
assert.deepEqual(calls, [['size', 50]]);
|
||||
events.onChange(2, 10);
|
||||
assert.deepEqual(calls.slice(1), [
|
||||
['page', 2],
|
||||
['change', 2, 10],
|
||||
]);
|
||||
});
|
||||
test('Legacy Ant resize handlers receive page one exactly once', () => {
|
||||
const calls = [];
|
||||
pagination
|
||||
.centerPaginationEvents({
|
||||
pageSize: 10,
|
||||
onShowSizeChange: (p, s) => calls.push([p, s]),
|
||||
onChange: () => calls.push('duplicate'),
|
||||
})
|
||||
.onChange(4, 20);
|
||||
assert.deepEqual(calls, [[1, 20]]);
|
||||
});
|
||||
test('Desktop and mobile share size options and translated totals; only mobile has jump input', () => {
|
||||
for (const mobile of [false, true]) {
|
||||
const opts = pagination.centerPaginationOptions({}, mobile);
|
||||
assert.equal(opts.size, 'small');
|
||||
assert.equal(opts.showTotal(156), '共 156 条');
|
||||
assert.equal(opts.showQuickJumper, mobile);
|
||||
assert.deepEqual(opts.pageSizeOptions, [10, 20, 50, 100]);
|
||||
}
|
||||
});
|
||||
|
||||
const uiFile = 'src/components/ui/index.jsx';
|
||||
const transformed = await transformWithEsbuild(
|
||||
await fs.readFile(uiFile, 'utf8'),
|
||||
uiFile,
|
||||
{ loader: 'jsx', format: 'cjs', target: 'node22', jsx: 'transform' },
|
||||
);
|
||||
const modules = {
|
||||
'./pagination.css': {},
|
||||
'../../hooks/common/useIsMobile': { useIsMobile: () => false },
|
||||
react: React,
|
||||
antd: Ant,
|
||||
'./controls': { controlSize: (s) => s },
|
||||
'./pagination': pagination,
|
||||
'./overlayPolicy': {},
|
||||
'./form': {},
|
||||
'./chat': {},
|
||||
'../console/ConsoleContext': { useConsolePage: () => null },
|
||||
'../console/ConsolePrimitives': {},
|
||||
'../console/consoleTableAdapter': {},
|
||||
};
|
||||
const module = { exports: {} };
|
||||
runInNewContext(transformed.code, {
|
||||
module,
|
||||
exports: module.exports,
|
||||
window: { matchMedia: () => ({ matches: false }) },
|
||||
require(name) {
|
||||
assert.ok(name in modules, name);
|
||||
return modules[name];
|
||||
},
|
||||
});
|
||||
const { Table } = module.exports;
|
||||
test('Tables with pagination false or omitted never gain a paginator', () => {
|
||||
for (const config of [false, undefined]) {
|
||||
const el = Table({
|
||||
pagination: config,
|
||||
columns: [{ dataIndex: 'id' }],
|
||||
dataSource: [sentinel],
|
||||
});
|
||||
assert.equal(el.props.pagination, false);
|
||||
assert.doesNotMatch(renderToStaticMarkup(el), /ant-pagination/);
|
||||
}
|
||||
});
|
||||
|
||||
test('Existing unpaginated tables keep pagination disabled after other UI edits', async () => {
|
||||
const expected = JSON.parse(
|
||||
await fs.readFile(
|
||||
new URL('./fixtures/unpaginated-tables.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
let compared = 0;
|
||||
for (const [file, count] of Object.entries(expected)) {
|
||||
const ast = parse(await fs.readFile(file, 'utf8'), {
|
||||
sourceType: 'module',
|
||||
plugins: ['jsx'],
|
||||
});
|
||||
let actual = 0;
|
||||
walk(ast, (node) => {
|
||||
if (
|
||||
node.type !== 'JSXOpeningElement' ||
|
||||
!/Table$/.test(node.name.name || '')
|
||||
)
|
||||
return;
|
||||
if (
|
||||
node.attributes.some(
|
||||
(attr) =>
|
||||
attr.name?.name === 'pagination' &&
|
||||
attr.value?.expression?.value === false,
|
||||
)
|
||||
)
|
||||
actual++;
|
||||
});
|
||||
assert.equal(actual, count, file + ': unpaginated table count');
|
||||
compared += actual;
|
||||
}
|
||||
assert.ok(compared > 20, 'Covers the original unpaginated tables');
|
||||
});
|
||||
|
||||
test('Visual model editor keeps frontend filtering and supports size reset', async () => {
|
||||
const file = 'src/pages/Setting/Ratio/ModelSettingsVisualEditor.jsx';
|
||||
const after = await fs.readFile(file, 'utf8');
|
||||
const calls = [];
|
||||
walk(parse(after, { sourceType: 'module', plugins: ['jsx'] }), (node) => {
|
||||
if (node.type === 'CallExpression' && node.callee.object?.name === 'API')
|
||||
calls.push(node);
|
||||
});
|
||||
assert.equal(calls.length, 1, 'Only the existing save request is present');
|
||||
assert.equal(calls[0].callee.property.name, 'put');
|
||||
assert.equal(calls[0].arguments[0].value, '/api/option/');
|
||||
assert.match(after, /\[pageSize, setPageSize\] = useState\(10\)/);
|
||||
assert.match(
|
||||
after,
|
||||
/onPageSizeChange: \(size\) => \{\s*setPageSize\(size\);\s*setCurrentPage\(1\);/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Multi-key read pagination preserves existing POST action and response fields', async () => {
|
||||
const { source } = await callback(
|
||||
'src/components/table/channels/modals/MultiKeyManageModal.jsx',
|
||||
'loadKeyStatus',
|
||||
);
|
||||
const calls = [],
|
||||
states = {};
|
||||
const context = {
|
||||
channel: { id: 7 },
|
||||
currentPage: 3,
|
||||
pageSize: 50,
|
||||
statusFilter: 1,
|
||||
API: {
|
||||
post: async (path, data) => {
|
||||
calls.push({ path, data });
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
keys: [sentinel],
|
||||
total: 156,
|
||||
page: 3,
|
||||
page_size: 50,
|
||||
total_pages: 4,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
setLoading: (x) => {
|
||||
states.loading = x;
|
||||
},
|
||||
setKeyStatusList: (x) => {
|
||||
states.rows = x;
|
||||
},
|
||||
setTotal: (x) => {
|
||||
states.total = x;
|
||||
},
|
||||
setCurrentPage: () => {},
|
||||
setPageSize: () => {},
|
||||
setTotalPages: () => {},
|
||||
setEnabledCount: () => {},
|
||||
setManualDisabledCount: () => {},
|
||||
setAutoDisabledCount: () => {},
|
||||
showError: assert.fail,
|
||||
t: (x) => x,
|
||||
console,
|
||||
};
|
||||
await runInNewContext('(' + source + ')', context)(3, 50, 1);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].path, '/api/channel/multi_key/manage');
|
||||
assert.equal(calls[0].data.action, 'get_key_status');
|
||||
assert.equal(calls[0].data.page, 3);
|
||||
assert.equal(calls[0].data.page_size, 50);
|
||||
assert.equal(states.total, 156);
|
||||
assert.equal(states.rows[0], sentinel);
|
||||
assert.equal(states.loading, false);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { findUnitTests } from '../../scripts/test.mjs';
|
||||
|
||||
test('unit discovery includes source and maintained suites and excludes evidence scripts', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'monkey-unit-discovery-'));
|
||||
try {
|
||||
for (const name of [
|
||||
'src/nested',
|
||||
'tests/helpers',
|
||||
'test/unit',
|
||||
'report',
|
||||
'logs',
|
||||
'e2e',
|
||||
])
|
||||
await mkdir(path.join(root, name), { recursive: true });
|
||||
for (const name of [
|
||||
'src/nested/model.test.js',
|
||||
'tests/legacy.test.js',
|
||||
'test/unit/new.test.js',
|
||||
'tests/helpers/loader.js',
|
||||
'report/prototype-test.mjs',
|
||||
'report/contracts.test.mjs',
|
||||
'logs/output.test.js',
|
||||
'e2e/page.spec.js',
|
||||
])
|
||||
await writeFile(path.join(root, name), '');
|
||||
const files = await findUnitTests(root);
|
||||
assert.deepEqual(
|
||||
files.map((file) => path.relative(root, file).replaceAll('\\', '/')),
|
||||
[
|
||||
'src/nested/model.test.js',
|
||||
'test/unit/new.test.js',
|
||||
'tests/legacy.test.js',
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user