feat: redesign the web console with Vue and isolated account workspaces
This commit is contained in:
@@ -0,0 +1,329 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {createContext, runInContext} from 'node:vm';
|
||||
import {shallowReactive, isReactive} from 'vue';
|
||||
|
||||
// Exercise orchestration with fake APIs and time. No server or game is contacted.
|
||||
const source = await readFile(new URL('../src/controller.js', import.meta.url), 'utf8');
|
||||
const dom = await readFile(new URL('../../ranch_web/static/dom.js', import.meta.url), 'utf8');
|
||||
const paths = await readFile(new URL('../../ranch_web/static/paths.js', import.meta.url), 'utf8');
|
||||
const keys = ['login','incubator','bag','ranch','daily','hatching','mainline','battles','gifts','commissions','exploration','maps','statistics','plans','yields'];
|
||||
const plain = value => JSON.parse(JSON.stringify(value));
|
||||
const settle = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); };
|
||||
function deferred() {
|
||||
let resolve, reject;
|
||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
||||
return {promise, resolve, reject};
|
||||
}
|
||||
|
||||
class Element extends EventTarget {
|
||||
constructor(tag = 'div') {
|
||||
super(); Object.assign(this, {tagName:tag.toUpperCase(), children:[], dataset:{}, value:'', hidden:false, isConnected:true, textContent:'', attributes:{}});
|
||||
this.classList = {add(){}, toggle(){}};
|
||||
}
|
||||
append(...nodes) { this.children.push(...nodes); }
|
||||
replaceChildren(...nodes) { this.children = nodes; }
|
||||
setAttribute(key, value) { this.attributes[key] = value; }
|
||||
querySelector(selector) { return selector === ':invalid' ? this.invalid : null; }
|
||||
querySelectorAll() { return []; }
|
||||
remove() { this.isConnected = false; }
|
||||
focus() {}
|
||||
click() {}
|
||||
close() { this.open = false; }
|
||||
}
|
||||
|
||||
async function fixture(t) {
|
||||
const h = {calls:[], pages:[], notices:[], confirms:[], files:[], overrides:{}, now:100000, timers:new Map(), timerId:0};
|
||||
h.accounts = new Map(['a', 'b'].map(id => [id, {id, label:id, connected:true, running:false, demo:true, revision:0, player:{name:id}}]));
|
||||
h.configs = new Map(['a', 'b'].map(id => [id, {interval:30, policy:{egg_rules:{}}, log_visible:true, log_sizes:[420,140]}]));
|
||||
h.base = {
|
||||
auth:() => ({required:false, access_mode:'local'}), meta:() => ({version:'2.0.0', nested:{}}), schema:() => ({pages:[]}),
|
||||
accounts:() => [...h.accounts.values()].map(value => structuredClone(value)),
|
||||
config:id => ({config:structuredClone(h.configs.get(id)), revision:h.accounts.get(id).revision}),
|
||||
save:(id, config) => { h.configs.set(id, structuredClone(config)); h.accounts.get(id).revision++; return h.base.config(id); },
|
||||
status:id => structuredClone(h.accounts.get(id)),
|
||||
view:(id, key) => ({data:{columns:[{key:'id'}], rows:[], marker:`${id}/${key}`}, loading:false}),
|
||||
action:(id, operation) => {
|
||||
if (operation === 'start' || operation === 'stop') h.accounts.get(id).running = operation === 'start';
|
||||
return {id:`${id}/${operation}`, status:'succeeded', result:{}};
|
||||
},
|
||||
logs:() => ({entries:[], next:0}),
|
||||
remove:id => { h.accounts.delete(id); },
|
||||
job:() => ({status:'succeeded', result:{}}),
|
||||
};
|
||||
const api = new Proxy({}, {get:(_, name) => (...args) => {
|
||||
h.calls.push({name, args:structuredClone(args), at:h.now});
|
||||
return Promise.resolve().then(() => {
|
||||
const fn = h.overrides[name] || h.base[name];
|
||||
if (!fn) throw new Error(`Unexpected API call: ${String(name)}`);
|
||||
return fn(...args);
|
||||
});
|
||||
}});
|
||||
class PageView {
|
||||
constructor(account, key, options) {
|
||||
Object.assign(this, {account, key, options, root:new Element(), query:{}, data:null, renders:[], selected:[]});
|
||||
this.login = key === 'login' ? {clearPassword(){}, update(){}} : null;
|
||||
h.pages.push(this);
|
||||
}
|
||||
render(data) { this.data = data; this.renders.push(data); }
|
||||
clearError() {}
|
||||
showError(message) { this.error = message; }
|
||||
selectedRows() { return this.selected; }
|
||||
destroy() { this.destroyed = true; }
|
||||
}
|
||||
const document = Object.assign(new EventTarget(), {
|
||||
hidden:false, body:new Element('body'), activeElement:null,
|
||||
querySelector:selector => {
|
||||
if (selector.startsWith('meta[')) return null;
|
||||
if (selector === '#action-dialog') return {open:true, close(){}};
|
||||
if (selector === '#notice') return null;
|
||||
throw new Error(`Unexpected shell DOM query: ${selector}`);
|
||||
},
|
||||
querySelectorAll:() => [], createElement:tag => new Element(tag), createTextNode:text => Object.assign(new Element(), {textContent:text}),
|
||||
});
|
||||
const context = createContext({
|
||||
shallowReactive, api, PageView, PAGES:keys.map(key => [key,key]), document, window:new EventTarget(),
|
||||
location:{origin:'http://console.invalid', replace:target => { h.redirect = target; }},
|
||||
structuredClone, AbortController, URL, Blob, Node:Element,
|
||||
Date:class extends Date { static now() { return h.now; } },
|
||||
setTimeout:(callback, delay = 0) => { const id = ++h.timerId; h.timers.set(id, {callback, at:h.now + delay}); return id; },
|
||||
clearTimeout:id => h.timers.delete(id),
|
||||
notice:(message, error) => h.notices.push({message,error}),
|
||||
confirm:() => Promise.resolve(h.confirms.length ? h.confirms.shift() : true),
|
||||
dialog:() => Promise.resolve(h.confirms.length ? h.confirms.shift() : null),
|
||||
filePicker:() => Promise.resolve(h.files.shift() || null), fileBase64:async () => 'Zml4dHVyZQ==',
|
||||
request:async path => { h.detailPath = path; return {details:{safe:true}}; },
|
||||
});
|
||||
runInContext(dom.replace(/^export /gm, ''), context);
|
||||
runInContext(paths.replace(/^export /gm, ''), context);
|
||||
runInContext(source.replace(/^import .+;\r?\n/gm, '').replace('export function createConsoleController', 'function createConsoleController'), context);
|
||||
h.controller = runInContext('createConsoleController()', context);
|
||||
h.document = document;
|
||||
h.context = context;
|
||||
h.advance = async duration => {
|
||||
const until = h.now + duration;
|
||||
for (;;) {
|
||||
const next = [...h.timers].filter(([,timer]) => timer.at <= until).sort((a,b) => a[1].at - b[1].at)[0];
|
||||
if (!next) break;
|
||||
h.now = next[1].at; h.timers.delete(next[0]); next[1].callback(); await settle();
|
||||
}
|
||||
h.now = until; await settle();
|
||||
};
|
||||
h.findPage = (key, id = h.controller.state.activeId) => h.pages.find(page => page.key === key && page.account.id === id);
|
||||
t.after(() => h.controller.dispose());
|
||||
await h.controller.init(new Element()); await settle();
|
||||
assert.equal(h.controller.state.error, null);
|
||||
assert.equal(h.controller.state.ready, true);
|
||||
return h;
|
||||
}
|
||||
|
||||
test('exports the contract, keeps snapshots raw and skips APIs on shell pages', async t => {
|
||||
const h = await fixture(t), c = h.controller;
|
||||
assert.deepEqual(Object.keys(c).sort(), ['state','init','navigate','selectAccount','command','refresh','setInterval','retrySave','setLogDebug','inspectLog','dispose'].sort());
|
||||
assert.ok(isReactive(c.state));
|
||||
assert.equal(isReactive(c.state.accounts), false);
|
||||
assert.equal(isReactive(c.state.meta.nested), false);
|
||||
assert.equal(c.state.currentConfig.policy, undefined);
|
||||
assert.ok(Object.isFrozen(c.state.currentConfig));
|
||||
for (const key of ['overview','accounts','activity','system']) await c.navigate(key);
|
||||
assert.equal(h.calls.filter(call => call.name === 'view').length, 0);
|
||||
for (const key of keys) await c.navigate(key);
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'view').map(call => call.args[1]), keys);
|
||||
});
|
||||
|
||||
test('serializes edits added during an in-flight save and renders only the visible page', async t => {
|
||||
const h = await fixture(t), c = h.controller, pending = deferred();
|
||||
await c.navigate('bag'); const bag = h.findPage('bag');
|
||||
await c.navigate('hatching'); const page = h.findPage('hatching');
|
||||
const hiddenRenders = bag.renders.length;
|
||||
h.overrides.save = (id, config) => h.calls.filter(call => call.name === 'save').length === 1 ? pending.promise : h.base.save(id, config);
|
||||
c.setInterval(60); const saving = c.retrySave(); await settle();
|
||||
c.setInterval(120); await settle();
|
||||
assert.equal(h.calls.filter(call => call.name === 'save').length, 1);
|
||||
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
|
||||
await saving; await settle();
|
||||
const saves = h.calls.filter(call => call.name === 'save');
|
||||
assert.deepEqual(saves.map(call => call.args[1].interval), [60,120]);
|
||||
assert.equal(c.state.currentConfig.dirty, false);
|
||||
assert.equal(c.state.interval, 120);
|
||||
assert.equal(bag.renders.length, hiddenRenders);
|
||||
assert.ok(page.renders.length > 1);
|
||||
await c.navigate('bag');
|
||||
assert.ok(bag.renders.length > hiddenRenders);
|
||||
});
|
||||
|
||||
test('conflict rebasing retains explicit edits and respects server defaults and linked rules', async t => {
|
||||
const h = await fixture(t), c = h.controller;
|
||||
await c.navigate('bag'); const page = h.findPage('bag');
|
||||
page.options.edit(page.account, ['policy','egg_rules','7','enabled'], true, {}, {
|
||||
rule_path:['policy','egg_rules','7'], rule_defaults:{action:'feed', priority:1},
|
||||
});
|
||||
h.overrides.save = () => Promise.reject(Object.assign(new Error('conflict'), {status:409}));
|
||||
h.configs.set('a', {interval:30, policy:{external:true, egg_rules:{7:{action:'feed', priority:8}}}});
|
||||
h.accounts.get('a').revision = 8;
|
||||
await c.retrySave();
|
||||
assert.ok(c.state.saveError);
|
||||
assert.equal(c.state.currentConfig.dirty, true);
|
||||
h.overrides.save = h.base.save;
|
||||
await c.retrySave();
|
||||
const policy = h.configs.get('a').policy;
|
||||
assert.deepEqual(plain(policy.egg_rules[7]), {action:'feed', priority:8, enabled:true});
|
||||
assert.equal(policy.feed, true); assert.equal(policy.collect, true); assert.equal(policy.external, true);
|
||||
assert.equal(c.state.saveError, null);
|
||||
});
|
||||
|
||||
test('stop suppresses an unsent start waiting for a save after switching accounts', async t => {
|
||||
const h = await fixture(t), c = h.controller, pending = deferred();
|
||||
h.overrides.save = () => pending.promise;
|
||||
c.setInterval(60); const saving = c.retrySave(); await settle();
|
||||
const starting = c.command('start', 'a'); await settle();
|
||||
await c.selectAccount('b');
|
||||
await c.command('stop', 'a');
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','stop']]);
|
||||
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
|
||||
await Promise.all([saving, starting]);
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','stop']]);
|
||||
assert.equal(c.state.accounts.find(account => account.id === 'a').running, false);
|
||||
assert.equal(c.state.activeId, 'b');
|
||||
});
|
||||
|
||||
test('a delayed start stays bound to its original account when switching accounts without stop', async t => {
|
||||
const h = await fixture(t), c = h.controller, pending = deferred();
|
||||
h.overrides.save = () => pending.promise;
|
||||
c.setInterval(60); const saving = c.retrySave(); await settle();
|
||||
const starting = c.command('start', 'a'); await settle();
|
||||
await c.selectAccount('b');
|
||||
assert.equal(h.calls.filter(call => call.name === 'action').length, 0);
|
||||
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
|
||||
await Promise.all([saving, starting]);
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start']]);
|
||||
assert.equal(c.state.activeId, 'b');
|
||||
});
|
||||
|
||||
test('discards hidden-page responses and coalesces generation changes without overlapping views', async t => {
|
||||
const h = await fixture(t), c = h.controller, pending = deferred();
|
||||
let reads = 0;
|
||||
h.overrides.view = () => ++reads === 1 ? pending.promise : {data:{marker:'fresh'}};
|
||||
const navigation = c.navigate('bag'); await settle(); const page = h.findPage('bag');
|
||||
page.query.search = 'new'; page.generation = 1;
|
||||
const reloading = page.options.load(page, true); await settle(); assert.equal(reads, 1);
|
||||
pending.resolve({data:{marker:'stale'}}); await Promise.all([navigation,reloading]);
|
||||
assert.deepEqual(page.renders.map(data => data.marker), ['fresh']);
|
||||
const hidden = deferred(); h.overrides.view = () => hidden.promise;
|
||||
const second = c.navigate('ranch'); await settle(); await c.navigate('overview');
|
||||
hidden.resolve({data:{marker:'hidden'}}); await second;
|
||||
assert.equal(h.findPage('ranch').renders.length, 0);
|
||||
});
|
||||
|
||||
test('removes the captured account without changing a newer selection, then selects after active removal', async t => {
|
||||
const h = await fixture(t), c = h.controller, confirmation = deferred();
|
||||
h.confirms.push(confirmation.promise);
|
||||
const removing = c.command('remove-account', 'a'); await settle();
|
||||
await c.selectAccount('b'); confirmation.resolve(true); await removing;
|
||||
assert.equal(c.state.activeId, 'b');
|
||||
assert.deepEqual(plain(c.state.accounts.map(account => account.id)), ['b']);
|
||||
await c.command('remove-account', 'b');
|
||||
assert.equal(c.state.activeId, null);
|
||||
assert.equal(c.state.accounts.length, 0);
|
||||
assert.equal(c.state.page, 'login');
|
||||
const second = await fixture(t);
|
||||
await second.controller.command('remove-account', 'a');
|
||||
assert.equal(second.controller.state.activeId, 'b');
|
||||
assert.equal(second.controller.state.page, 'login');
|
||||
});
|
||||
|
||||
test('stop suppresses an unsent start waiting for an unselected account config', async t => {
|
||||
const h = await fixture(t), c = h.controller, config = deferred();
|
||||
h.overrides.config = id => id === 'b' ? config.promise : h.base.config(id);
|
||||
const starting = c.command('start', 'b'); await settle();
|
||||
assert.equal(h.calls.filter(call => call.name === 'config' && call.args[0] === 'b').length, 1);
|
||||
assert.equal(h.calls.filter(call => call.name === 'action').length, 0);
|
||||
await c.command('stop', 'b');
|
||||
config.resolve(h.base.config('b')); await starting;
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop']]);
|
||||
assert.equal(c.state.accounts.find(account => account.id === 'b').running, false);
|
||||
assert.equal(c.state.activeId, 'a');
|
||||
});
|
||||
|
||||
test('starting is synchronous and an older start cannot clear a newer pending start', async t => {
|
||||
const h = await fixture(t), c = h.controller, config = deferred(), response = deferred();
|
||||
const summary = () => c.state.accounts.find(account => account.id === 'b');
|
||||
h.overrides.config = id => id === 'b' ? config.promise : h.base.config(id);
|
||||
h.overrides.action = (id, operation) => operation === 'start' ? response.promise : h.base.action(id, operation);
|
||||
const first = c.command('start', 'b');
|
||||
assert.equal(summary().starting, true);
|
||||
assert.equal(summary().running, false);
|
||||
const stopping = c.command('stop', 'b');
|
||||
assert.equal(summary().starting, false);
|
||||
const second = c.command('start', 'b');
|
||||
assert.equal(summary().starting, true);
|
||||
await stopping;
|
||||
config.resolve(h.base.config('b')); await first; await settle();
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop'],['b','start']]);
|
||||
assert.equal(summary().starting, true);
|
||||
assert.equal(summary().running, false);
|
||||
h.accounts.get('b').running = true;
|
||||
response.resolve({id:'latest-start', status:'succeeded', result:{}}); await second;
|
||||
assert.equal(summary().starting, false);
|
||||
assert.equal(summary().running, true);
|
||||
});
|
||||
|
||||
test('stop on another account does not suppress a delayed start', async t => {
|
||||
const h = await fixture(t), c = h.controller, pending = deferred();
|
||||
h.overrides.save = () => pending.promise;
|
||||
c.setInterval(60); const saving = c.retrySave(); await settle();
|
||||
const starting = c.command('start', 'a'); await settle();
|
||||
await c.command('stop', 'b');
|
||||
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
|
||||
await Promise.all([saving, starting]);
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop'],['a','start']]);
|
||||
});
|
||||
|
||||
test('stop preserves server tracking for a start whose request was already sent', async t => {
|
||||
const h = await fixture(t), c = h.controller, response = deferred();
|
||||
h.overrides.action = (id, operation) => operation === 'start' ? response.promise : h.base.action(id, operation);
|
||||
h.overrides.job = () => ({id:'sent-start', status:'succeeded', result:{outcome:'server-result'}});
|
||||
const starting = c.command('start', 'a'); await settle();
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start']]);
|
||||
await c.command('stop', 'a');
|
||||
response.resolve({id:'sent-start', status:'queued', operation:'start'});
|
||||
assert.deepEqual(plain(await starting), {outcome:'server-result'});
|
||||
assert.equal(h.calls.filter(call => call.name === 'job' && call.args[1] === 'sent-start').length, 1);
|
||||
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start'],['a','stop']]);
|
||||
});
|
||||
|
||||
test('jobs finish independently of blocked summaries; disposing rejects no unhandled job promises', async t => {
|
||||
const h = await fixture(t), c = h.controller, summaries = deferred();
|
||||
h.overrides.accounts = () => summaries.promise;
|
||||
h.overrides.action = () => ({id:'job', status:'queued', operation:'stop'});
|
||||
let polls = 0;
|
||||
h.overrides.job = () => ++polls === 1 ? {id:'job',status:'running'} : {id:'job',status:'succeeded',result:{}};
|
||||
const stopping = c.command('stop', 'a'); await settle();
|
||||
assert.equal(c.state.jobs.length, 1);
|
||||
await h.advance(1000); await stopping;
|
||||
assert.equal(c.state.jobs.length, 0);
|
||||
await h.advance(7000);
|
||||
assert.equal(h.calls.filter(call => call.name === 'accounts').length, 2);
|
||||
h.overrides.job = () => ({id:'job',status:'running'});
|
||||
const disposedCommand = c.command('stop', 'b'); await settle();
|
||||
c.dispose(); await disposedCommand; await settle();
|
||||
const count = h.calls.length; await h.advance(20000); assert.equal(h.calls.length, count);
|
||||
assert.equal(h.timers.size, 0);
|
||||
summaries.resolve([]); await settle();
|
||||
});
|
||||
|
||||
test('caps logs at 500, discards old debug responses and pauses hidden-document page and log reads', async t => {
|
||||
const h = await fixture(t), c = h.controller, pending = deferred();
|
||||
h.overrides.logs = (_, after, debug) => debug ? {entries:Array.from({length:650}, (_, id) => ({id, message:'debug'})), next:650} : pending.promise;
|
||||
await h.advance(3000);
|
||||
const debug = c.setLogDebug(true); await settle();
|
||||
pending.resolve({entries:[{id:9000,message:'old'}],next:9001}); await debug;
|
||||
assert.equal(c.state.logs.length, 500);
|
||||
assert.equal(c.state.logs.some(entry => entry.message === 'old'), false);
|
||||
assert.equal(c.state.logs[0].id, 150);
|
||||
await c.navigate('bag'); h.document.hidden = true;
|
||||
const before = h.calls.filter(call => call.name === 'view' || call.name === 'logs').length;
|
||||
await h.advance(16000);
|
||||
assert.equal(h.calls.filter(call => call.name === 'view' || call.name === 'logs').length, before);
|
||||
});
|
||||
@@ -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