fix: refresh announcement drawer silently

dev
admin 2 months ago
parent 6902215b2f
commit 1df35d092d

@ -1,9 +1,10 @@
// User announcements are independent of the VM session and engine bootstrap.
const dialog = document.getElementById('panel-announcements-drawer');
const byId = id => document.getElementById(id);
const refreshInterval = 30000;
const state = {
items: [], pagination: null, request: null, serial: 0, loading: false,
stale: false, receivedAt: '', opener: null, scroll: null,
foreground: false, timer: null, opener: null, scroll: null,
};
function element(tag, className = '', value) {
@ -15,9 +16,12 @@ function element(tag, className = '', value) {
function setMessage(message, tone = '') {
const node = byId('panel-announcements-state');
node.textContent = message;
node.className = `panel-announcements-state${tone ? ` is-${tone}` : ''}`;
node.setAttribute('role', tone === 'error' ? 'alert' : 'status');
if (node.textContent !== message) node.textContent = message;
const className = `panel-announcements-state${tone ? ` is-${tone}` : ''}`;
if (node.className !== className) node.className = className;
if (node.hidden !== !message) node.hidden = !message;
const role = tone === 'error' ? 'alert' : 'status';
if (node.getAttribute('role') !== role) node.setAttribute('role', role);
}
function dateText(value) {
@ -49,13 +53,67 @@ function renderItems() {
}
function renderControls() {
byId('panel-announcements-refresh').disabled = state.loading;
const busy = state.loading && state.foreground;
const refresh = byId('panel-announcements-refresh');
if (refresh.disabled !== busy) refresh.disabled = busy;
const more = byId('panel-announcements-more');
more.hidden = !state.pagination || state.pagination.page >= state.pagination.total_pages;
more.disabled = state.loading || state.stale;
byId('panel-announcements-count').textContent = state.pagination
? `已加载 ${state.items.length} / ${state.pagination.total} 条${state.stale ? '(旧内容)' : ''}` : '';
byId('panel-announcements-list').setAttribute('aria-busy', String(state.loading));
const lastPage = !state.pagination || state.pagination.page >= state.pagination.total_pages;
if (more.hidden !== lastPage) more.hidden = lastPage;
if (more.disabled !== busy) more.disabled = busy;
const count = state.pagination
? (lastPage ? `共 ${state.pagination.total} 条` : `已显示 ${state.items.length} / ${state.pagination.total} 条`) : '';
if (byId('panel-announcements-count').textContent !== count) byId('panel-announcements-count').textContent = count;
const list = byId('panel-announcements-list');
if (list.getAttribute('aria-busy') !== String(busy)) list.setAttribute('aria-busy', String(busy));
}
function canRefresh() {
return Boolean(dialog?.open) && document.visibilityState === 'visible';
}
function clearRefreshTimer() {
if (state.timer !== null) clearTimeout(state.timer);
state.timer = null;
}
function scheduleRefresh() {
clearRefreshTimer();
if (!canRefresh() || state.loading) return;
state.timer = setTimeout(() => {
state.timer = null;
void load(1, 'auto');
}, refreshInterval);
}
function stopRequests() {
clearRefreshTimer();
state.request?.abort();
state.request = null;
state.serial += 1;
state.loading = false;
state.foreground = false;
}
function publishedItems(items) {
const seen = new Set();
return items.filter(item => {
if (!item || item.status !== 'published') return false;
const id = String(item.id);
if (seen.has(id)) return false;
seen.add(id);
return true;
});
}
function contentSignature(items) {
// Compare only rendered data, not response timestamps or other API metadata.
return JSON.stringify(items.map(item => {
const type = ['notice', 'maintenance', 'incident'].includes(item.type) ? item.type : 'notice';
const fallback = { notice: '通知', maintenance: '维护', incident: '故障' }[type];
return [String(item.id), type, String(item.type_label || fallback),
String(item.title || '站点公告'), String(item.body ?? ''), dateText(item.published_at),
item.updated_at && item.updated_at !== item.published_at ? dateText(item.updated_at) : ''];
}));
}
async function requestPage(page, controller) {
@ -76,7 +134,8 @@ async function requestPage(page, controller) {
const pagination = payload?.pagination;
if (!Array.isArray(payload?.items) || !pagination
|| ![pagination.page, pagination.per_page, pagination.total, pagination.total_pages].every(Number.isInteger)
|| pagination.page < 1 || pagination.per_page !== 10 || pagination.total < 0 || pagination.total_pages < 1) {
|| pagination.page < 1 || pagination.per_page !== 10 || pagination.total < 0
|| pagination.total_pages < 1 || pagination.page > pagination.total_pages) {
throw new Error('公告数据格式无效,请稍后重试。');
}
return payload;
@ -86,43 +145,66 @@ async function requestPage(page, controller) {
} finally { clearTimeout(timeout); }
}
async function load(page = 1) {
if (!dialog?.open) return;
if (page !== 1 && (state.loading || state.stale || !state.pagination)) return;
state.request?.abort();
async function load(page = 1, source = 'manual') {
if (!canRefresh() || state.loading || (page !== 1 && !state.pagination)) return;
clearRefreshTimer();
const controller = new AbortController(); state.request = controller;
const serial = ++state.serial;
const hadSnapshot = Boolean(state.pagination);
const currentRequest = () => !controller.signal.aborted && serial === state.serial && canRefresh();
state.loading = true;
if (page === 1 && state.pagination) state.stale = true;
setMessage(page === 1
? (state.pagination ? `正在刷新;下方暂显示 ${state.receivedAt} 读取的旧内容。` : '正在读取最新公告…')
: '正在加载更多公告…', state.stale ? 'stale' : '');
renderControls();
state.foreground = source !== 'auto';
if (state.foreground) renderControls();
try {
const payload = await requestPage(page, controller);
if (controller.signal.aborted || serial !== state.serial || !dialog.open) return;
const published = payload.items.filter(item => item && item.status === 'published');
// Offset pagination can repeat an item if a new notice is published between
// requests. Keep one record per ID without changing server publication order.
const replaces = page === 1 || payload.pagination.page === 1;
const combined = replaces ? published : [...state.items, ...published];
const seen = new Set();
state.items = combined.filter(item => {
const id = String(item.id);
if (seen.has(id)) return false;
seen.add(id); return true;
});
state.pagination = payload.pagination; state.stale = false;
state.receivedAt = new Date().toLocaleTimeString('zh-CN', { hour12: false });
renderItems();
setMessage(`读取于 ${state.receivedAt};按发布时间倒序显示。`);
if (replaces) byId('panel-announcements-scroll').scrollTop = 0;
let payload = await requestPage(page, controller);
if (!currentRequest()) return;
let items;
if (page === 1) {
// Revalidate the whole visible range atomically so a withdrawn notice on
// an already loaded later page disappears without collapsing to page one.
const loadedPages = state.pagination?.page || 1;
if (payload.pagination.page !== 1) throw new Error('公告数据已变化,请重试。');
const expectedTotal = payload.pagination.total;
const expectedTotalPages = payload.pagination.total_pages;
const targetPages = Math.min(loadedPages, expectedTotalPages);
items = payload.items;
for (let nextPage = 2; nextPage <= targetPages; nextPage += 1) {
payload = await requestPage(nextPage, controller);
if (!currentRequest()) return;
// A deletion can shrink the result between requests and clamp the page.
// Retry later rather than combine two incompatible page ranges.
if (payload.pagination.page !== nextPage || payload.pagination.total !== expectedTotal
|| payload.pagination.total_pages !== expectedTotalPages) throw new Error('公告数据已变化,请重试。');
items = [...items, ...payload.items];
}
} else if (payload.pagination.page !== page) {
// The requested next page disappeared. Revalidate the loaded range on the
// next refresh instead of replacing it with a clamped partial response.
throw new Error('公告数据已变化,请点击刷新。');
} else {
items = [...state.items, ...payload.items];
}
items = publishedItems(items);
const changed = !hadSnapshot || contentSignature(state.items) !== contentSignature(items);
state.items = items;
state.pagination = payload.pagination;
if (changed) {
const scroll = byId('panel-announcements-scroll');
const scrollTop = scroll.scrollTop;
renderItems();
scroll.scrollTop = scrollTop;
}
setMessage('');
} catch (error) {
if (serial !== state.serial || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
state.stale = Boolean(state.pagination);
setMessage(`${error.message}${state.pagination ? ` 下方保留 ${state.receivedAt} 读取的旧内容,请刷新确认最新公告。` : ''}`, 'error');
if (serial !== state.serial || !canRefresh() || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
if (source !== 'auto' || !hadSnapshot) setMessage(error.message, 'error');
} finally {
if (serial === state.serial) { state.request = null; state.loading = false; renderControls(); }
if (serial === state.serial) {
state.request = null;
state.loading = false;
state.foreground = false;
if (canRefresh()) { renderControls(); scheduleRefresh(); }
}
}
}
@ -131,7 +213,7 @@ function historyData(changes = {}) {
}
function close() {
state.request?.abort(); state.request = null; state.serial += 1; state.loading = false;
stopRequests();
if (dialog.open) dialog.close();
document.documentElement.classList.remove('panel-announcements-open');
document.body.style.removeProperty('--panel-announcements-scroll-top');
@ -152,9 +234,10 @@ function open(opener) {
dialog.showModal();
byId('panel-announcements-close').focus({ preventScroll: true });
document.querySelectorAll('[data-announcements-open]').forEach(button => button.setAttribute('aria-expanded', 'true'));
// Always refresh page one on reopening: a previously published notice may
// have been withdrawn. Do not treat the old in-memory list as current data.
void load(1);
// Opening an existing snapshot only resumes the timer. It must not flash a
// refresh state or throw away content merely because the drawer was reopened.
if (state.pagination) scheduleRefresh();
else void load(1, 'initial');
}
if (dialog) {
@ -165,7 +248,15 @@ if (dialog) {
});
byId('panel-announcements-close').addEventListener('click', close);
byId('panel-announcements-refresh').addEventListener('click', () => { void load(1); });
byId('panel-announcements-more').addEventListener('click', () => { void load(state.pagination.page + 1); });
byId('panel-announcements-more').addEventListener('click', () => {
if (state.pagination) void load(state.pagination.page + 1);
});
document.addEventListener('visibilitychange', () => {
if (!canRefresh()) {
stopRequests();
if (dialog.open) renderControls();
} else scheduleRefresh();
});
dialog.addEventListener('cancel', event => { event.preventDefault(); close(); });
dialog.addEventListener('click', event => {
if (event.target !== dialog) return;
@ -174,7 +265,7 @@ if (dialog) {
});
window.addEventListener('popstate', () => { if (dialog.open) close(); });
window.addEventListener('pagehide', () => {
state.request?.abort(); state.serial += 1; state.loading = false;
stopRequests();
if (state.scroll) history.replaceState(historyData({ panelAnnouncementsScroll: state.scroll }), '', location.href);
});
window.addEventListener('pageshow', event => { if (event.persisted && dialog.open) close(); });

@ -49,9 +49,9 @@ html.panel-announcements-open body { position: fixed; top: var(--panel-announcem
.panel-announcements-header h2 { margin: 0 0 7px; font-size: 19px; line-height: 1.5; font-weight: 800; }
.panel-announcements-header p { margin: 0; color: #7a8c9d; font-size: 12px; line-height: 1.7; }
.panel-announcements-toolbar { display: flex; flex: 0 0 auto; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 14px 24px; border-bottom: 1px solid #e5edf2; background: #f8fbfc; }
.panel-announcements-toolbar .button { flex: 0 0 auto; min-height: 44px; }
.panel-announcements-toolbar .button { flex: 0 0 auto; min-height: 44px; margin-left: auto; }
.panel-announcements-state { margin: 0; color: #647d90; font-size: 12px; line-height: 1.8; overflow-wrap: anywhere; }
.panel-announcements-state.is-stale { color: #91601e; }
.panel-announcements-state[hidden] { display: none; }
.panel-announcements-state.is-error { color: #ba4350; }
.panel-announcements-scroll { min-height: 0; flex: 1 1 auto; overflow-y: auto; overscroll-behavior-y: contain; padding: 0 24px max(20px, env(safe-area-inset-bottom)); }
.panel-announcements-item { padding: 22px 0; border-bottom: 1px solid #e5edf2; }

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026093008' scope='global'}
{assign var=venix_asset_version value='2026093009' scope='global'}

@ -3,7 +3,7 @@
<div><h2 id="panel-announcements-title">公告与维护信息</h2><p id="panel-announcements-description">按发布时间查看站点通知、维护安排与故障说明。</p></div>
<button class="button button-ghost panel-announcements-close" id="panel-announcements-close" type="button" aria-label="关闭公告" autofocus><i class="mdi mdi-close" aria-hidden="true"></i></button>
</header>
<div class="panel-announcements-toolbar"><p id="panel-announcements-state" class="panel-announcements-state" role="status" aria-live="polite">打开后读取最新公告。</p><button class="button button-outline small" id="panel-announcements-refresh" type="button">刷新</button></div>
<div class="panel-announcements-toolbar"><p id="panel-announcements-state" class="panel-announcements-state" role="alert" hidden></p><button class="button button-outline small" id="panel-announcements-refresh" type="button">刷新</button></div>
<div class="panel-announcements-scroll" id="panel-announcements-scroll" tabindex="0" aria-label="公告内容">
<div class="panel-announcements-list" id="panel-announcements-list" aria-busy="false"></div>
<div class="panel-announcements-pagination"><p id="panel-announcements-count"></p><button class="button button-outline" id="panel-announcements-more" type="button" hidden>加载更多</button></div>

@ -0,0 +1,267 @@
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');
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', 'refresh', 'more', 'count', 'list', 'scroll', 'close'];
const nodes = Object.fromEntries(names.map(name => [name, new Node(name === 'drawer' ? 'dialog' : 'div')]));
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 = () => {};
const history = { state: null, replaceState(value) { this.state = value; } };
let now = 0; let timerId = 0;
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' },
URL, 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', ...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);
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);
await test.click('open'); assert.equal(test.requests.length, 2, 'Reopening a loaded drawer uses its snapshot.');
await test.advance(30000); assert.equal(test.requests.length, 3);
await test.respond(page([announcement(1, { body: '已更新' })]));
assert.match(test.nodes.list.textContent, /已更新/); assert.equal(test.nodes.scroll.scrollTop, 173); assertQuiet(test);
}
// Empty responses are valid snapshots, not a reason to refetch on every opening.
{
const test = fixture(); await test.click('open'); await test.respond(page([]));
assert.match(test.nodes.list.textContent, /暂无已发布/); assertQuiet(test);
await test.click('close'); await test.click('open'); assert.equal(test.requests.length, 1);
await test.advance(30000); await test.respond(page([])); assert.equal(test.requests.length, 2); 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);
}
// 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.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');
// 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(30000);
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, atomic pagination, cancellation and plain-text behavior passed.');

@ -73,6 +73,11 @@ foreach (['account' => $accountHtml, 'cloud' => $cloudHtml] as $mode => $html) {
$assert($xpath->query('//a[@href="/user/announcement"]')->length === 0, $mode . ': retired announcement navigation remains.');
$assert($xpath->query('//*[@id="panel-announcements-list"]/*')->length === 0,
$mode . ': should not preload unrelated announcement content into every user response.');
$assert($xpath->query('//*[@id="panel-announcements-state" and @hidden and @role="alert"]')->length === 1
&& trim($xpath->query('//*[@id="panel-announcements-state"]')->item(0)->textContent) === '',
$mode . ': routine announcement loading and refresh must not display status messages.');
$assert($xpath->query('//button[@id="panel-announcements-refresh" and not(@hidden)]')->length === 1,
$mode . ': retain the manual refresh button.');
$assert($xpath->query('//link[contains(@href,"admin-home.css")]')->length === 0,
$mode . ': user shell must not load the administrator theme.');
$assert($xpath->query('//button[@id="panel-announcements-close" and @autofocus]')->length === 1,
@ -91,11 +96,14 @@ $assert(!str_contains($script, '.innerHTML') && !str_contains($script, 'insertAd
&& str_contains($script, 'node.textContent = String(value)'), 'Announcement title and body must be plain text.');
$assert(str_contains($script, '/api/v1/announcements?page=') && !str_contains($script, '/session')
&& !str_contains($script, 'from \'./runtime.js\''), 'Announcements must not depend on a VM session.');
$assert(str_contains($script, "item.status === 'published'") && str_contains($script, 'void load(1);'),
'Reopening must revalidate published content.');
$assert(str_contains($script, "item.status !== 'published'") && str_contains($script, 'visibilitychange'),
'Visible drawers must revalidate published content without background polling when hidden.');
foreach (['读取于', '旧内容', '正在刷新', '正在读取最新公告', '正在加载更多公告'] as $retiredMessage) {
$assert(!str_contains($script, $retiredMessage), 'Retired announcement status message remains: ' . $retiredMessage);
}
$css = file_get_contents(dirname(__DIR__) . '/public/cloud/client.css');
$assert(preg_match('/\.panel-announcements-trigger\.button \{[^}]*width: 30px;[^}]*height: 30px;[^}]*background: transparent;/', $css) === 1,
'The topbar announcement trigger must match the 30px avatar without a large button background.');
$assert(preg_match('/\.panel-announcements-close\.button \{[^}]*width: 44px;[^}]*height: 44px;/', $css) === 1,
'The drawer close control must retain its 44px touch size.');
echo "User announcement shared shell, lazy drawer, plain-text contract and retired navigation checks passed.\n";
echo "User announcement shared shell, silent drawer, plain-text contract and retired navigation checks passed.\n";

Loading…
Cancel
Save