feat: redesign the web console with Vue and isolated account workspaces
This commit is contained in:
@@ -0,0 +1,320 @@
|
||||
// Run with node --test frontend/tests/table-*.test.mjs. Uses the project's
|
||||
// Python Playwright and a system Chromium; every request is served in memory.
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {spawnSync} from 'node:child_process';
|
||||
import test from 'node:test';
|
||||
|
||||
const sources = Object.fromEntries(['dom.js', 'forms.js', 'table.js', 'pages.js', 'ui.js'].map(name =>
|
||||
[`/static/${name}`, readFileSync(new URL(`../../ranch_web/static/${name}`, import.meta.url), 'utf8')]));
|
||||
|
||||
const bootstrap = async () => {
|
||||
const {DataTable, GroupedTables} = await import('/static/table.js');
|
||||
const {PageView} = await import('/static/pages.js');
|
||||
const {control, PolicyForm} = await import('/static/forms.js');
|
||||
const {getPath, setPath} = await import('/static/dom.js');
|
||||
Object.assign(globalThis, {DataTable, GroupedTables, PageView, control, PolicyForm});
|
||||
globalThis.check = (condition, message) => { if (!condition) throw new Error(message); };
|
||||
globalThis.tick = () => new Promise(resolve => setTimeout(resolve, 0));
|
||||
globalThis.fixture = (count = 1000, options = {}) => {
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
const config = {rules: {}, targets: {}};
|
||||
const rows = Array.from({length: count}, (_, index) => {
|
||||
const id = String(index + 1);
|
||||
config.rules[id] = {priority: count - index, enabled: index % 2 === 0};
|
||||
return {id, name: `条目 ${id}`, priority: index + 1, enabled: false, revision: 1};
|
||||
});
|
||||
const columns = [{key: 'name', label: '名称'},
|
||||
{key: 'priority', label: '优先级', edit: {type: 'integer', min: 0, path: ['rules', '{id}', 'priority']}},
|
||||
{key: 'enabled', label: '启用', edit: {type: 'boolean', path: ['rules', '{id}', 'enabled']}}];
|
||||
const writes = [], selections = [];
|
||||
const context = {
|
||||
get: (path, fallback) => getPath(config, path, fallback),
|
||||
set: (path, value, field, row) => { setPath(config, path, value); writes.push({path, value, field, row}); },
|
||||
onSelection: selected => selections.push(selected),
|
||||
};
|
||||
const table = new DataTable(host, context, options);
|
||||
table.update(columns, rows);
|
||||
const ids = () => [...table.body.children].map(row => row.dataset.rowId);
|
||||
return {host, config, rows, columns, context, table, writes, selections, ids};
|
||||
};
|
||||
};
|
||||
|
||||
const cases = {
|
||||
'1000 rows create only current-page editors and all page sizes stay bounded': async () => {
|
||||
const {host, table, columns, rows, ids} = fixture();
|
||||
check(table.nodes.size === 50 && table.body.children.length === 50, '默认页应只有 50 行');
|
||||
check(host.querySelectorAll('td input[type=number]').length === 50, '不可为其余 950 行创建编辑器');
|
||||
check(table.count.textContent === '共 1000 项,显示 1–50 项', '中文总数和范围应正确');
|
||||
check([...table.sizeSelect.options].map(option => option.value).join(',') === '25,50,100', '分页选项应为 25/50/100');
|
||||
check(table.firstPage.disabled && !table.nextPage.disabled, '首页按钮边界应正确');
|
||||
for (let page = 2; page <= 20; page++) {
|
||||
table.setPage(page);
|
||||
check(table.nodes.size === 50 && table.body.children.length === 50, '翻页后不可保留之前的 DOM 行');
|
||||
}
|
||||
check(ids()[0] === '951' && table.nextPage.disabled, '末页范围和按钮应正确');
|
||||
table.sizeSelect.value = '25';
|
||||
table.sizeSelect.dispatchEvent(new Event('change'));
|
||||
check(table.page === 39 && table.pageCount === 40 && ids()[0] === '951', '改变页大小应保留原首条的位置');
|
||||
check(table.nodes.size === 25, '25 条分页应只创建 25 行');
|
||||
table.sizeSelect.value = '100';
|
||||
table.sizeSelect.dispatchEvent(new Event('change'));
|
||||
check(table.page === 10 && table.nodes.size === 100, '100 条分页应正确限制节点数量');
|
||||
table.update(columns, rows);
|
||||
check(table.body.children.length === 100, '轮询不得扩大 DOM');
|
||||
table.pageInput.value = '0';
|
||||
table.pageInput.dispatchEvent(new Event('change'));
|
||||
check(table.pageInput.validationMessage === '请输入 1 到 10 之间的页码', '无效页码必须有中文错误');
|
||||
},
|
||||
'sorting uses all live configuration values before slicing a page': async () => {
|
||||
const {table, columns, rows, config, ids} = fixture();
|
||||
table.head.querySelector('[data-column=priority] button').click();
|
||||
check(ids()[0] === '1000' && ids()[49] === '951', '应按全部 1000 条当前配置排序,而非快照或当前页');
|
||||
check(table.body.querySelector('td[data-column=priority] input').value === '1', '编辑值必须与排序值相同');
|
||||
config.rules['20'].priority = 0;
|
||||
table.update(columns, rows);
|
||||
check(ids()[0] === '20', '未渲染行的新配置应参与全局排序');
|
||||
table.head.querySelector('[data-column=priority] button').click();
|
||||
check(ids()[0] === '1', '降序应使用当前配置');
|
||||
table.head.querySelector('[data-column=enabled] button').click();
|
||||
check(ids().every(id => Number(id) % 2 === 0), '布尔编辑列应按配置排序');
|
||||
const targetColumn = {key: 'selected', label: '目标', edit: {type: 'target', path: ['targets', '{id}']}};
|
||||
config.targets['999'] = 100;
|
||||
const overridden = rows.map(row => ({...row, selected: true, edits: {selected: {path: ['targets', row.id]}}}));
|
||||
table.update([...columns, targetColumn], overridden);
|
||||
table.head.querySelector('[data-column=selected] button').click();
|
||||
table.head.querySelector('[data-column=selected] button').click();
|
||||
check(ids()[0] === '999', '目标开关须按实际配置是否存在排序,不能读快照布尔值');
|
||||
},
|
||||
'selection persists across pages with explicit current-page and filtered scopes': async () => {
|
||||
const {table, rows, columns, selections} = fixture();
|
||||
table.nodes.get('1').check.click();
|
||||
table.setPage(2);
|
||||
check(table.selectedRows().length === 1 && table.selectedRows()[0].id === '1', '离开页面不应丢失选择');
|
||||
check(table.allCheck.getAttribute('aria-label') === '选择本页全部 50 项', '表头全选范围应明确');
|
||||
table.allCheck.click();
|
||||
check(table.selectedRows().length === 51, '本页全选应保留其他分页的选择');
|
||||
table.allCheck.click();
|
||||
check(table.selectedRows().length === 1, '取消本页全选不得清除其他页');
|
||||
table.selectFiltered.click();
|
||||
check(table.selectedRows().length === 1000, '筛选全选应覆盖全部分页');
|
||||
check(table.selectionCount.textContent === '已选择 1000 项(含其他分页)', '跨页总数应明确');
|
||||
table.setPage(1);
|
||||
check(table.nodes.get('1').check.checked, '回页后应恢复选中状态');
|
||||
const fresh = rows.slice(499, 503).map(row => ({...row, revision: 2}));
|
||||
table.update(columns, fresh);
|
||||
check(table.selected.size === 4 && table.selectedRows().every(row => row.revision === 2), '缩减数据必须清除离页旧选择并返回最新行');
|
||||
check(selections.at(-1).length === 4, '操作按钮应收到最新选择');
|
||||
table.clearSelection.click();
|
||||
check(table.selectedRows().length === 0 && table.clearSelection.disabled, '清除选择应涵盖所有分页');
|
||||
},
|
||||
'polling preserves a focused native editor and defers movement until blur': async () => {
|
||||
const {table, columns, rows, config, ids, writes} = fixture();
|
||||
for (const row of rows) config.rules[row.id].priority = Number(row.id);
|
||||
table.head.querySelector('[data-column=priority] button').click();
|
||||
const input = table.nodes.get('1').cells.get('priority').control.root;
|
||||
input.focus();
|
||||
input.value = '2000';
|
||||
input.dispatchEvent(new Event('input', {bubbles: true}));
|
||||
const fresh = rows.map(row => ({...row, revision: 2}));
|
||||
table.update(columns, fresh);
|
||||
check(document.activeElement === input && input.isConnected && input.value === '2000', '轮询不可替换、移动或覆盖正在编辑的输入框');
|
||||
check(ids()[0] === '1' && table.pendingRender, '编辑中应暂缓将该行排到其他页');
|
||||
check(table.nodes.size === 50, '编辑保护也必须保持 DOM 上限');
|
||||
input.value = '2001';
|
||||
input.dispatchEvent(new Event('input', {bubbles: true}));
|
||||
check(writes.at(-1).row.revision === 2, '复用编辑器必须使用最新行,而非创建时的旧快照');
|
||||
input.blur();
|
||||
await tick();
|
||||
check(ids()[0] === '2' && !table.nodes.has('1') && !table.pendingRender, '失焦后应立即完成排序和分页');
|
||||
const other = table.nodes.get('2').cells.get('priority').control.root;
|
||||
other.focus();
|
||||
other.value = '';
|
||||
table.update([...columns, {key: 'revision', label: '版本'}], fresh);
|
||||
check(document.activeElement === other && other.value === '', '列变化时也必须保留未完成编辑');
|
||||
other.blur();
|
||||
await tick();
|
||||
check(table.head.querySelector('[data-column=revision]'), '失焦后应应用延后的列变化');
|
||||
},
|
||||
'shrinking data clamps the page and removes even a deleted focused row': async () => {
|
||||
const {table, columns, rows, ids} = fixture();
|
||||
table.selectFiltered.click();
|
||||
table.lastPage.click();
|
||||
const removed = table.nodes.get('1000').cells.get('priority').control.root;
|
||||
removed.focus();
|
||||
table.update(columns, rows.slice(0, 3));
|
||||
check(table.page === 1 && table.pageCount === 1, '数据缩减后应夹紧页码');
|
||||
check(ids().join(',') === '1,2,3' && !removed.isConnected, '已删除的聚焦行不可残留');
|
||||
check(table.selectedRows().length === 3 && table.selected.size === 3, '所有已删除选择均应清理');
|
||||
table.update(columns, []);
|
||||
check(table.nodes.size === 0 && table.body.children.length === 0, '空结果不可残留行');
|
||||
check(!table.empty.hidden && table.count.textContent === '共 0 项,显示 0–0 项', '空状态及中文数量应正确');
|
||||
check(table.allCheck.disabled && table.nextPage.disabled, '空结果应禁用选择与翻页');
|
||||
},
|
||||
'reused editors read fresh fallback rows and synchronize form disabled state': async () => {
|
||||
const {table, columns, rows, config} = fixture(2);
|
||||
delete config.rules['1'].priority;
|
||||
const input = table.nodes.get('1').cells.get('priority').control.root;
|
||||
table.update(columns, rows.map(row => ({...row, priority: 48, revision: 2})));
|
||||
check(table.nodes.get('1').cells.get('priority').control.root === input && input.value === '48', '配置缺省时复用控件仍应读取最新行值');
|
||||
const field = {type: 'integer', path: ['n'], label: '数量', value: 3};
|
||||
const entry = control(field, {get: (_, fallback) => fallback, set: () => {}});
|
||||
document.body.append(entry.root);
|
||||
entry.root.focus();
|
||||
entry.root.value = '12';
|
||||
field.value = 9;
|
||||
field.disabled = true;
|
||||
entry.sync();
|
||||
check(entry.root.value === '12' && !entry.root.disabled, '表单刷新应保留聚焦编辑');
|
||||
entry.root.blur();
|
||||
entry.sync();
|
||||
check(entry.root.value === '9' && entry.root.disabled, '失焦后应同步最新值与禁用状态');
|
||||
},
|
||||
'closed grouped tables stay lazy and closed-group selections use current rows': async () => {
|
||||
const {context, columns, rows, host} = fixture();
|
||||
host.replaceChildren();
|
||||
const grouped = new GroupedTables(host, context);
|
||||
const items = rows.map((row, index) => ({...row, group: index < 500 ? 'a' : 'b'}));
|
||||
grouped.update(columns, items, 'group', {a: '地区甲', b: '地区乙'});
|
||||
check(host.querySelectorAll('tbody tr').length === 0, '折叠分组不可创建任何行或编辑器');
|
||||
const group = grouped.groups.get('a');
|
||||
group.root.open = true;
|
||||
await tick();
|
||||
check(group.table.nodes.size === 50 && grouped.groups.get('b').table === null, '仅展开的组应创建当前页');
|
||||
group.table.selectFiltered.click();
|
||||
group.root.open = false;
|
||||
await tick();
|
||||
const fresh = items.filter(row => row.group === 'b' || Number(row.id) <= 2).map(row => ({...row, revision: 5}));
|
||||
grouped.update(columns, fresh, 'group');
|
||||
check(grouped.selectedRows().length === 2 && grouped.selectedRows().every(row => row.revision === 5), '折叠组的选择不能返回过时行');
|
||||
group.root.open = true;
|
||||
await tick();
|
||||
check(group.table.nodes.size === 2 && group.table.body.children.length === 2, '重新展开时不得残留缩减前的行');
|
||||
grouped.update(columns, [], 'group');
|
||||
check(grouped.groups.size === 0 && group.table.destroyed, '移除组应清理表格');
|
||||
},
|
||||
'polling preserves incomplete member choices without changing the three-member protocol': async () => {
|
||||
const {table, rows, context, writes} = fixture(1);
|
||||
const columns = [{key: 'members', label: '探险队', edit: {type: 'members', path: ['team'],
|
||||
options: [{value: 1, label: '队长', level: 10}, {value: 2, label: '队员甲', level: 9}, {value: 3, label: '队员乙', level: 8}]}}];
|
||||
table.update(columns, [{...rows[0], members: []}]);
|
||||
const editor = table.nodes.get('1').cells.get('members').control.root;
|
||||
const selects = [...editor.querySelectorAll('select')];
|
||||
selects[0].focus();
|
||||
selects[0].value = '1';
|
||||
selects[0].dispatchEvent(new Event('change'));
|
||||
check(writes.length === 0, '不完整队伍不可提交');
|
||||
table.update(columns, [{...rows[0], name: '最新队伍', members: []}]);
|
||||
check(document.activeElement === selects[0] && selects[0].value === '1', '轮询不可清空队伍草稿');
|
||||
selects[1].value = '2';
|
||||
selects[1].dispatchEvent(new Event('change'));
|
||||
selects[2].value = '3';
|
||||
selects[2].dispatchEvent(new Event('change'));
|
||||
check(writes.length === 1 && writes[0].value.join(',') === '1,2,3', '只有完整三人队才应保存');
|
||||
check(context.get(['team']).join(',') === '1,2,3', '保存的队伍配置格式不得变化');
|
||||
},
|
||||
'statistics retain lazy grouping and their measured chart source with a paginated table': async () => {
|
||||
const account = {config: {}, edits: new Map()};
|
||||
const options = {edit: () => {}, schema: () => [], load: () => {}, action: async () => {}, perform: async () => {}, command: () => {}};
|
||||
const view = new PageView(account, 'statistics', options);
|
||||
document.body.append(view.root);
|
||||
view.root.hidden = false;
|
||||
const stages = Array.from({length: 120}, (_, index) => ({id: String(index + 1), city_id: Math.floor(index / 30) + 1,
|
||||
city_name: `地区 ${Math.floor(index / 30) + 1}`, label: `关卡 ${index + 1}`, levels: [{level: 1}, {level: 2}, {level: 3}]}));
|
||||
const rows = Array.from({length: 1000}, (_, index) => ({id: String(index + 1), name: `实测物品 ${index + 1}`, rate: .5}));
|
||||
const data = {columns: [{key: 'name', label: '物品'}, {key: 'rate', label: '实测概率'}], rows, stages,
|
||||
chart: {series: [{label: '实际记录', value: .125}], max: 1}};
|
||||
view.render(data);
|
||||
check(view.statisticsPicker.querySelectorAll('.statistics-city').length === 4, '应按四个真实地区分组');
|
||||
check(view.statisticsPicker.querySelectorAll('.statistics-levels button').length === 0, '统计难度列表必须保持惰性');
|
||||
const city = view.statisticsPicker.querySelector('details');
|
||||
city.open = true;
|
||||
await tick();
|
||||
check(view.statisticsPicker.querySelectorAll('.statistics-stage').length === 30, '展开地区应只创建该地区关卡');
|
||||
city.querySelector('.statistics-stage').open = true;
|
||||
await tick();
|
||||
check(view.statisticsPicker.querySelectorAll('.statistics-levels button').length === 3, '展开关卡应只创建三种难度');
|
||||
check(view.statisticsTable.nodes.size === 50 && view.statisticsTableHost.querySelectorAll('.selection-cell').length === 0, '统计表应分页且无选择列');
|
||||
check(view.chart.querySelectorAll('.chart-bar').length === 1 && view.chart.textContent.includes('实际记录') && view.chart.textContent.includes('12.50%'), '图表应继续使用接口实测序列,而非当前分页或虚构数据');
|
||||
view.statisticsTable.lastPage.click();
|
||||
view.render({...data, rows: rows.slice(0, 3)});
|
||||
check(view.statisticsTable.page === 1 && view.statisticsTable.nodes.size === 3, '统计表缩减后应清理末页');
|
||||
check(view.chart.querySelectorAll('.chart-bar').length === 1, '分页不应改变图表来源');
|
||||
view.destroy();
|
||||
},
|
||||
'destroy cancels deferred query loads and ignores late renders': async () => {
|
||||
let loads = 0;
|
||||
const view = new PageView({config: {}, edits: new Map()}, 'bag', {
|
||||
edit: () => {}, schema: () => [], load: () => { loads++; }, action: async () => {}, perform: async () => {}, command: () => {},
|
||||
});
|
||||
document.body.append(view.root);
|
||||
view.setQuery('search', '离线测试');
|
||||
view.destroy();
|
||||
view.setQuery('search', '不得重新安排');
|
||||
view.render({rows: [], columns: []});
|
||||
await new Promise(resolve => setTimeout(resolve, 260));
|
||||
check(loads === 0 && !view.root.isConnected && view.data === null, '销毁后不可加载或重建页面');
|
||||
},
|
||||
};
|
||||
|
||||
const pythonHarness = String.raw`
|
||||
import json, os, sys
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
payload = json.loads(sys.stdin.buffer.read().decode('utf-8'))
|
||||
results = {}
|
||||
with sync_playwright() as playwright:
|
||||
candidates = [os.environ.get('RANCH_WEB_BROWSER', ''),
|
||||
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
|
||||
'C:/Program Files/Google/Chrome/Application/chrome.exe']
|
||||
executable = next((path for path in candidates if path and Path(path).is_file()), None)
|
||||
browser = playwright.chromium.launch(headless=True, **({'executable_path': executable} if executable else {}))
|
||||
for name, source in payload['cases'].items():
|
||||
page = browser.new_page()
|
||||
unexpected = []
|
||||
errors = []
|
||||
def serve(route):
|
||||
path = route.request.url.removeprefix('http://table.test')
|
||||
if path == '/':
|
||||
route.fulfill(status=200, content_type='text/html; charset=utf-8', body='<!doctype html><html lang="zh-CN"><body><div id="notice" hidden></div></body></html>')
|
||||
elif path in payload['sources']:
|
||||
route.fulfill(status=200, content_type='text/javascript; charset=utf-8', body=payload['sources'][path])
|
||||
else:
|
||||
unexpected.append(route.request.url)
|
||||
route.abort()
|
||||
page.route('**/*', serve)
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
try:
|
||||
page.goto('http://table.test/')
|
||||
page.evaluate(payload['bootstrap'])
|
||||
page.evaluate(source)
|
||||
assert not unexpected, 'Unexpected request: ' + str(unexpected)
|
||||
assert not errors, 'Browser errors: ' + str(errors)
|
||||
results[name] = {'ok': True}
|
||||
except Exception as error:
|
||||
results[name] = {'ok': False, 'error': str(error)}
|
||||
finally:
|
||||
page.close()
|
||||
browser.close()
|
||||
print(json.dumps(results, ensure_ascii=True))
|
||||
`;
|
||||
|
||||
const run = spawnSync(process.env.PYTHON || 'python', ['-c', pythonHarness], {
|
||||
input: JSON.stringify({sources, bootstrap: `(${bootstrap.toString()})`, cases: Object.fromEntries(
|
||||
Object.entries(cases).map(([name, callback]) => [name, `(${callback.toString()})`]))}),
|
||||
encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 2 * 1024 * 1024,
|
||||
});
|
||||
let results;
|
||||
test('offline Chromium harness completes without external requests', () => {
|
||||
assert.ifError(run.error);
|
||||
assert.equal(run.status, 0, run.stderr);
|
||||
results = JSON.parse(run.stdout.trim());
|
||||
});
|
||||
for (const name of Object.keys(cases)) {
|
||||
test(name, () => {
|
||||
assert.ok(results, 'Browser harness did not complete');
|
||||
assert.deepEqual(results[name], {ok: true}, results[name]?.error);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user