You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/AnnouncementDrawerBehaviorT...

388 lines
24 KiB
JavaScript

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
// Exercise the shipped module through DOM events, without a browser dependency.
// Fetches deliberately remain resolvable after abort to check stale-response guards.
const source = await readFile(new URL('../public/cloud/announcements.js', import.meta.url), 'utf8');
const copyFixture = {
'common.announcements.time_missing': '时间未记录',
'common.announcements.type.notice': '通知',
'common.announcements.type.maintenance': '维护',
'common.announcements.type.incident': '故障',
'common.announcements.published_at': '发布于 {time}',
'common.announcements.updated_at': '更新于 {time}',
'common.announcements.fallback_title': '站点公告',
'common.announcements.empty': '暂无已发布的公告。',
'common.announcements.count.total': '共 {count} 条',
'common.announcements.count.visible': '已显示 {count} / {total} 条',
'common.announcements.read_at': '读取于 {time}',
'common.announcements.error.unauthorized': '登录已过期,请重新登录后查看公告。',
'common.announcements.error.forbidden': '当前账号无法读取公告。',
'common.announcements.error.response': '公告服务返回异常,请稍后重试。',
'common.announcements.error.http': '公告读取失败(状态码 {status})。',
'common.announcements.error.invalid_data': '公告数据格式无效,请稍后重试。',
'common.announcements.error.timeout': '公告读取超时,请稍后重试。',
'common.announcements.error.changed_retry': '公告数据已变化,请重试。',
'common.announcements.error.changed_refresh': '公告数据已变化,请点击刷新。',
};
const userCopy = {
locale: 'zh-CN',
text(key, parameters = {}) {
return (copyFixture[key] || key).replace(/\{([a-z_]+)\}/g,
(match, name) => Object.prototype.hasOwnProperty.call(parameters, name)
? String(parameters[name]) : match);
},
};
class Node {
constructor(tag = 'div') {
this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {};
this.attributes = new Map(); this.listeners = new Map(); this.styles = new Map();
this.style = { setProperty: (key, value) => this.styles.set(key, value), removeProperty: key => this.styles.delete(key) };
const classes = new Set();
this.classList = { add: value => classes.add(value), remove: value => classes.delete(value), contains: value => classes.has(value) };
this.hidden = false; this.disabled = false; this.isConnected = true;
this.open = false; this.replacements = 0; this.scrollWrites = 0; this._scrollTop = 0; this._text = '';
}
set textContent(value) { this._text = String(value); this.children = []; }
get textContent() { return this._text + this.children.map(child => child.textContent).join(''); }
set innerHTML(_) { throw new Error('Announcement HTML must never be interpreted.'); }
set scrollTop(value) { this._scrollTop = value; this.scrollWrites += 1; }
get scrollTop() { return this._scrollTop; }
append(...children) { this.children.push(...children); }
replaceChildren(...children) { this.replacements += 1; this._text = ''; this.children = children; }
setAttribute(key, value) { this.attributes.set(key, String(value)); }
getAttribute(key) { return this.attributes.get(key) ?? null; }
addEventListener(name, handler) {
if (!this.listeners.has(name)) this.listeners.set(name, []);
this.listeners.get(name).push(handler);
}
dispatch(name, fields = {}) {
const event = { target: this, button: 0, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...fields };
for (const handler of this.listeners.get(name) ?? []) handler(event);
}
closest(selector) { return selector === '[data-announcements-open]' && this.isTrigger ? this : null; }
focus() {}
showModal() { this.open = true; }
close() { this.open = false; }
getBoundingClientRect() { return { left: 0, top: 0, right: 540, bottom: 800 }; }
}
const flush = async () => { for (let turn = 0; turn < 16; turn += 1) await Promise.resolve(); };
function fixture() {
const names = ['drawer', 'state', 'read-time', 'refresh', 'more', 'count', 'list', 'scroll', 'close'];
const nodes = Object.fromEntries(names.map(name => [name, new Node(name === 'drawer' ? 'dialog' : 'div')]));
nodes['read-time'].hidden = true;
const document = new Node(); document.visibilityState = 'visible'; document.hidden = false;
document.documentElement = new Node(); document.body = new Node();
const trigger = new Node('button'); trigger.isTrigger = true;
document.getElementById = id => nodes[id.replace('panel-announcements-', '')] ?? null;
document.createElement = tag => new Node(tag);
document.querySelectorAll = selector => selector === '[data-announcements-open]' ? [trigger] : [];
document.querySelector = selector => document.querySelectorAll(selector)[0] ?? null;
const window = new Node(); window.scrollX = 0; window.scrollY = 125; window.scrollTo = () => {};
window.VenixDrawerMotion = {
openDrawerWithMotion(dialog) { dialog.showModal(); dialog.classList.add('is-drawer-visible'); return true; },
closeDrawerWithMotion(dialog) { dialog.classList.remove('is-drawer-visible'); dialog.close(); return Promise.resolve(true); },
};
const history = { state: null, replaceState(value) { this.state = value; } };
let now = 0; let timerId = 0;
const epoch = Date.UTC(2026, 8, 30, 6, 27, 20);
class FakeDate extends Date {
constructor(...values) { super(...(values.length ? values : [epoch + now])); }
static now() { return epoch + now; }
toLocaleTimeString(locale, options) {
assert.equal(locale, 'zh-CN'); assert.equal(options.hour12, false);
return this.toISOString().slice(11, 19);
}
toLocaleString(locale, options) {
assert.equal(locale, 'zh-CN'); assert.equal(options.hour12, false);
return this.toISOString().replace('T', ' ').slice(0, 19);
}
}
const timers = new Map(); const requests = [];
const setTimeout = (callback, delay = 0) => {
const id = ++timerId; timers.set(id, { callback, due: now + delay }); return id;
};
const fetch = (url, options) => new Promise((resolve, reject) => {
requests.push({ url, options, resolve, reject, settled: false });
});
vm.runInNewContext(source, {
document, window, history, location: { href: 'https://example.test/user/cloud' },
VenixUserCopy: userCopy,
URL, Date: FakeDate, AbortController, fetch, setTimeout, clearTimeout: id => timers.delete(id),
requestAnimationFrame: callback => setTimeout(callback, 0), console,
}, { filename: 'announcements.js' });
return {
nodes, document, window, requests,
async advance(milliseconds) {
const end = now + milliseconds;
while (true) {
const next = [...timers.entries()].filter(([, timer]) => timer.due <= end).sort((a, b) => a[1].due - b[1].due)[0];
if (!next) break;
now = next[1].due; timers.delete(next[0]); next[1].callback(); await flush();
}
now = end; await flush();
},
async click(name) {
if (name === 'open') document.dispatch('click', { target: trigger });
else if (!nodes[name].disabled) nodes[name].dispatch('click');
await flush();
},
async respond(payload, status = 200, request = requests.find(item => !item.settled)) {
assert.ok(request, 'A response requires an outstanding request.');
request.settled = true;
request.resolve({ status, ok: status >= 200 && status < 300, json: async () => payload });
await flush();
},
async visibility(value) {
document.visibilityState = value; document.hidden = value === 'hidden';
document.dispatch('visibilitychange'); await flush();
},
async lifecycle(name, fields) { window.dispatch(name, fields); await flush(); },
};
}
function announcement(id, changes = {}) {
return {
id: String(id), title: `公告 ${id}`, type: 'notice', type_label: '通知', body: `正文 ${id}`,
status: 'published', published_at: '2026-09-30 12:00:00', updated_at: '2026-09-30 12:00:00',
published_at_epoch: 1790769600, updated_at_epoch: 1790769600, ...changes,
};
}
function page(items, number = 1, total = items.length) {
return { items, pagination: { page: number, per_page: 10, total, total_pages: Math.max(1, Math.ceil(total / 10)) }, generated_at: 1 };
}
function articles(test) { return test.nodes.list.children.filter(node => node.tagName === 'ARTICLE'); }
function assertQuiet(test) {
assert.equal(test.nodes.state.textContent, '', 'Normal loading and refresh must not display a status message.');
assert.doesNotMatch(test.nodes.count.textContent, /旧内容|读取于|正在|成功/);
}
// Initial lazy read, inert closed state, unchanged polling, and literal text.
{
const test = fixture();
await test.advance(90000); assert.equal(test.requests.length, 0, 'Closed drawers do not prefetch or poll.');
await test.click('open'); assert.equal(test.requests.length, 1); assertQuiet(test);
const unsafe = announcement(1, { title: '<img src=x onerror=alert(1)>', body: '<script>alert(1)</script>\n第二行' });
await test.respond(page([unsafe]));
assert.equal(articles(test).length, 1); assert.match(test.nodes.list.textContent, /<script>alert\(1\)<\/script>/);
assert.equal(articles(test)[0].children.find(node => node.tagName === 'H3').textContent, unsafe.title);
assert.match(test.nodes.list.textContent, /发布于 2026-09-30 12:00:00/,
'Announcement publication time must be formatted from the canonical epoch in the browser.');
assertQuiet(test);
const renders = test.nodes.list.replacements;
test.nodes.scroll.scrollTop = 173; const scrollWrites = test.nodes.scroll.scrollWrites;
await test.advance(29999); assert.equal(test.requests.length, 1);
await test.advance(1); assert.equal(test.requests.length, 2); assertQuiet(test);
assert.equal(test.nodes.refresh.disabled, false, 'Silent polling must not visibly disable refresh.');
await test.respond({ ...page([unsafe]), generated_at: 99 });
assert.equal(test.nodes.list.replacements, renders, 'Server generation timestamps alone do not redraw content.');
assert.equal(test.nodes.scroll.scrollWrites, scrollWrites, 'Unchanged data must not move the scroll position.');
await test.click('close'); await test.advance(90000); assert.equal(test.requests.length, 2);
const snapshot = test.nodes.list.textContent; const readTime = test.nodes['read-time'].textContent;
await test.click('open'); assert.equal(test.requests.length, 3, 'Reopening immediately revalidates the existing snapshot.');
assert.equal(test.nodes.list.textContent, snapshot); assert.equal(test.nodes['read-time'].textContent, readTime);
assert.equal(test.nodes.refresh.disabled, false); assert.equal(test.nodes.list.getAttribute('aria-busy'), 'false'); assertQuiet(test);
await test.click('open'); await test.click('refresh');
assert.equal(test.requests.length, 3, 'Repeated clicks while refresh is pending do not create concurrent requests.');
await test.advance(5000); await test.respond(page([unsafe]));
assert.equal(test.nodes['read-time'].textContent, '读取于 06:30:55');
assert.equal(test.nodes.list.replacements, renders); assert.equal(test.nodes.scroll.scrollWrites, scrollWrites); assertQuiet(test);
await test.advance(29999); assert.equal(test.requests.length, 3, 'Polling resumes thirty seconds after completion, not opening.');
await test.advance(1); assert.equal(test.requests.length, 4);
await test.respond(page([announcement(1, { body: '已更新' })]));
assert.match(test.nodes.list.textContent, /已更新/); assert.equal(test.nodes.scroll.scrollTop, 173); assertQuiet(test);
}
// Empty responses remain visible snapshots while reopening silently revalidates them.
{
const test = fixture(); await test.click('open'); await test.respond(page([]));
assert.match(test.nodes.list.textContent, /暂无已发布/); assertQuiet(test);
const renders = test.nodes.list.replacements;
await test.click('close'); await test.click('open'); assert.equal(test.requests.length, 2);
assert.match(test.nodes.list.textContent, /暂无已发布/); assert.equal(test.nodes.refresh.disabled, false); assertQuiet(test);
await test.respond(page([])); assert.equal(test.nodes.list.replacements, renders); assertQuiet(test);
await test.advance(30000); await test.respond(page([announcement(1)]));
assert.equal(articles(test).length, 1);
await test.advance(30000); await test.respond(page([]));
assert.equal(articles(test).length, 0); assert.match(test.nodes.list.textContent, /暂无已发布/); assertQuiet(test);
}
// A fast close aborts an opening refresh; reopening can complete before its late response.
{
const test = fixture(); await test.click('open'); await test.respond(page([announcement(1)]));
const readTime = test.nodes['read-time'].textContent;
await test.click('close'); await test.click('open'); assert.equal(test.requests.length, 2);
const cancelled = test.requests.at(-1); await test.click('close');
assert.equal(cancelled.options.signal.aborted, true);
await test.advance(1000); await test.click('open'); assert.equal(test.requests.length, 3);
assert.equal(test.nodes['read-time'].textContent, readTime); assertQuiet(test);
await test.respond(page([announcement(2)]), 200, test.requests.at(-1));
assert.equal(articles(test)[0].dataset.announcementId, '2');
assert.equal(test.nodes['read-time'].textContent, '读取于 06:27:21');
const renders = test.nodes.list.replacements;
await test.advance(1000); await test.respond(page([announcement(3)]), 200, cancelled);
assert.equal(articles(test)[0].dataset.announcementId, '2');
assert.equal(test.nodes['read-time'].textContent, '读取于 06:27:21');
assert.equal(test.nodes.list.replacements, renders); assertQuiet(test);
}
// Only a complete successful read updates the independent timestamp, never status text.
{
const test = fixture(); const readTime = test.nodes['read-time'];
const first = Array.from({ length: 10 }, (_, index) => announcement(11 - index));
assert.equal(readTime.hidden, true); assert.equal(readTime.textContent, '');
await test.click('open'); await test.advance(2000);
assert.equal(readTime.hidden, true); assert.equal(readTime.textContent, '');
await test.respond(page(first, 1, 11));
assert.equal(readTime.hidden, false); assert.equal(readTime.textContent, '读取于 06:27:22'); assertQuiet(test);
await test.advance(1000); await test.click('more'); await test.advance(2000);
assert.equal(readTime.textContent, '读取于 06:27:22');
await test.respond(page([announcement(1)], 2, 11));
assert.equal(readTime.textContent, '读取于 06:27:25');
const renders = test.nodes.list.replacements;
await test.advance(30000); await test.advance(1000);
await test.respond(page(first, 1, 11));
assert.equal(readTime.textContent, '读取于 06:27:25', 'A successful first page is not a completed multi-page refresh.');
await test.advance(1000); await test.respond(page([announcement(1)], 2, 11));
assert.equal(readTime.textContent, '读取于 06:27:57');
assert.equal(test.nodes.list.replacements, renders, 'Updating read time must not redraw unchanged announcements.');
assertQuiet(test);
await test.advance(30000); await test.respond(page(first, 1, 11));
await test.advance(1000); await test.respond({ detail: '暂时不可用' }, 503);
assert.equal(readTime.textContent, '读取于 06:27:57', 'Failed automatic refreshes retain the last successful time.');
assertQuiet(test);
await test.click('refresh'); await test.respond(page(first, 1, 11));
await test.advance(1000); await test.respond({ detail: '暂时不可用' }, 503);
assert.equal(readTime.textContent, '读取于 06:27:57', 'Manual errors cannot be labelled as successful reads.');
assert.match(test.nodes.state.textContent, /暂时不可用/);
await test.click('refresh'); await test.respond(page(first, 1, 11));
await test.advance(1000); await test.respond(page([announcement(1)], 2, 11));
assert.equal(readTime.textContent, '读取于 06:28:30'); assertQuiet(test);
await test.advance(30000); const cancelled = test.requests.at(-1);
await test.click('close'); await test.advance(1000);
await test.respond(page(first, 1, 11), 200, cancelled);
assert.equal(readTime.textContent, '读取于 06:28:30', 'Cancelled reads never advance the displayed timestamp.');
}
// Refresh the entire loaded window atomically, including edits/withdrawals on later pages.
{
const test = fixture(); const first = Array.from({ length: 10 }, (_, index) => announcement(12 - index));
await test.click('open'); await test.respond(page(first, 1, 12));
await test.click('more'); assert.match(test.requests.at(-1).url, /page=2&/);
await test.respond(page([announcement(3), announcement(2), announcement(1)], 2, 12));
assert.equal(articles(test).length, 12, 'Loading more deduplicates overlapping offset pages.');
const before = test.nodes.list.replacements;
test.nodes.scroll.scrollTop = 246; const scrollWrites = test.nodes.scroll.scrollWrites;
await test.advance(30000); await test.respond(page(first, 1, 12));
await test.respond(page([announcement(2), announcement(1)], 2, 12));
assert.equal(articles(test).length, 12); assert.equal(test.nodes.list.replacements, before);
assert.equal(test.nodes.scroll.scrollWrites, scrollWrites, 'An unchanged multi-page snapshot is not redrawn or scrolled.');
await test.advance(30000); await test.respond(page(first, 1, 11));
assert.equal(test.nodes.list.replacements, before, 'Do not show a partial refresh before all loaded pages return.');
assert.match(test.requests.at(-1).url, /page=2&/);
await test.respond(page([announcement(2, { body: '第二页已修改' })], 2, 11));
assert.equal(articles(test).length, 11); assert.match(test.nodes.list.textContent, /第二页已修改/);
assert.ok(!articles(test).some(node => node.dataset.announcementId === '1'), 'A withdrawal from page two disappears.');
assert.equal(test.nodes.list.replacements, before + 1); assertQuiet(test);
const snapshot = test.nodes.list.textContent; const stableRenders = test.nodes.list.replacements;
const changedFirst = [announcement(13), ...first.slice(0, 9)];
await test.advance(30000); await test.respond(page(changedFirst, 1, 12));
await test.respond({ detail: '暂时不可用' }, 503);
assert.equal(test.nodes.list.textContent, snapshot); assert.equal(test.nodes.list.replacements, stableRenders);
assertQuiet(test); // A failed automatic refresh retains the complete snapshot silently.
await test.click('refresh'); await test.respond(page(changedFirst, 1, 12));
await test.respond({ detail: '暂时不可用' }, 503);
assert.equal(test.nodes.list.textContent, snapshot); assert.match(test.nodes.state.textContent, /暂时不可用/);
await test.click('refresh'); await test.respond(page(first, 1, 11));
await test.respond(page([announcement(2, { body: '第二页已修改' })], 2, 11));
assertQuiet(test); assert.equal(test.nodes.list.replacements, stableRenders);
}
// A failed next page is retryable; no success/loading banners accompany retry.
{
const test = fixture(); const first = Array.from({ length: 10 }, (_, index) => announcement(11 - index));
await test.click('open'); await test.respond(page(first, 1, 11));
await test.click('more'); await test.respond({ detail: '请重试' }, 503);
assert.equal(articles(test).length, 10); assert.equal(test.nodes.more.disabled, false);
await test.click('more'); await test.respond(page([announcement(1)], 2, 11));
assert.equal(articles(test).length, 11); assert.equal(test.nodes.more.hidden, true); assertQuiet(test);
}
// Failed initial reads are not disguised as an empty list; retry clears only the error.
{
const test = fixture(); await test.click('open');
await test.respond({ detail: '公告服务暂不可用' }, 503);
assert.match(test.nodes.state.textContent, /暂不可用/);
assert.equal(test.nodes['read-time'].hidden, true); assert.equal(test.nodes['read-time'].textContent, '');
assert.doesNotMatch(test.nodes.list.textContent, /暂无已发布/);
await test.click('refresh'); await test.respond(page([announcement(1)]));
assert.equal(articles(test).length, 1); assertQuiet(test);
}
// A changing page count during refresh must never commit mixed-version pages.
{
const test = fixture(); const first = Array.from({ length: 10 }, (_, index) => announcement(11 - index));
await test.click('open'); await test.respond(page(first, 1, 11));
await test.click('more'); await test.respond(page([announcement(1)], 2, 11));
const snapshot = test.nodes.list.textContent;
await test.advance(30000); await test.respond(page(first, 1, 11));
await test.respond(page([announcement(1)], 2, 12));
assert.equal(test.nodes.list.textContent, snapshot); assertQuiet(test);
await test.advance(30000); await test.respond(page(first, 1, 11));
await test.respond(page(first.slice(0, 9), 1, 9));
assert.equal(test.nodes.list.textContent, snapshot); assertQuiet(test);
// The next complete refresh can legitimately collapse to one remaining page.
await test.advance(30000); await test.respond(page([announcement(11)], 1, 1));
assert.equal(articles(test).length, 1); assert.equal(test.nodes.more.hidden, true); assertQuiet(test);
}
// Visibility, close, and page lifecycle cancel activity and reject late responses.
{
const test = fixture(); await test.click('open'); await test.respond(page([announcement(1)]));
await test.advance(30000); const hiddenRequest = test.requests.at(-1);
await test.visibility('hidden'); assert.equal(hiddenRequest.options.signal.aborted, true);
await test.advance(90000); assert.equal(test.requests.length, 2);
await test.visibility('visible'); assert.equal(test.requests.length, 2);
await test.advance(30000); assert.equal(test.requests.length, 3);
await test.respond(page([announcement(2)]), 200, test.requests.at(-1));
await test.respond(page([announcement(90)]), 200, hiddenRequest);
assert.equal(articles(test)[0].dataset.announcementId, '2', 'A late aborted response cannot replace a newer successful snapshot.');
await test.advance(30000); assert.equal(test.requests.length, 4);
const closeRequest = test.requests.at(-1); await test.click('close');
assert.equal(closeRequest.options.signal.aborted, true);
await test.advance(90000); assert.equal(test.requests.length, 4);
await test.click('open'); assert.equal(test.requests.length, 5);
// It is open again when the old response arrives, so the serial/abort guard
// (not merely dialog.open) must reject that response.
await test.respond(page([announcement(3)]), 200, closeRequest);
assert.equal(articles(test)[0].dataset.announcementId, '2');
await test.advance(1000);
const pagehideRequest = test.requests.at(-1); await test.lifecycle('pagehide');
assert.equal(pagehideRequest.options.signal.aborted, true);
await test.respond(page([announcement(4)]), 200, pagehideRequest);
await test.advance(90000); assert.equal(test.requests.length, 5);
assert.equal(articles(test)[0].dataset.announcementId, '2');
await test.lifecycle('pageshow', { persisted: true }); assert.equal(test.nodes.drawer.open, false);
await test.advance(90000); assert.equal(test.requests.length, 5);
}
// Browser fetch rejects on timeout; automatic failures remain quiet and retries work.
{
const test = fixture(); await test.click('open'); await test.respond(page([announcement(1)]));
await test.advance(30000); const automatic = test.requests.at(-1);
await test.advance(15000); assert.equal(automatic.options.signal.reason, 'timeout');
automatic.settled = true; automatic.reject(new Error('Aborted')); await flush();
assertQuiet(test); assert.equal(articles(test).length, 1);
await test.click('refresh'); const manual = test.requests.at(-1);
await test.advance(15000); assert.equal(manual.options.signal.reason, 'timeout');
manual.settled = true; manual.reject(new Error('Aborted')); await flush();
assert.match(test.nodes.state.textContent, /超时/); assert.equal(test.nodes.refresh.disabled, false);
await test.click('refresh'); await test.respond(page([announcement(1)])); assertQuiet(test);
}
console.log('Announcement drawer lazy loading, silent polling, successful read time, atomic pagination, cancellation and plain-text behavior passed.');