diff --git a/web/public/cloud/announcements.js b/web/public/cloud/announcements.js index a5f0976b..c425552a 100644 --- a/web/public/cloud/announcements.js +++ b/web/public/cloud/announcements.js @@ -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(); }); diff --git a/web/public/cloud/client.css b/web/public/cloud/client.css index c93442f8..92cad63a 100644 --- a/web/public/cloud/client.css +++ b/web/public/cloud/client.css @@ -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; } diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index b02c06f5..99cc86f8 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -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'} diff --git a/web/resources/views/venix/user/announcement_drawer.tpl b/web/resources/views/venix/user/announcement_drawer.tpl index cac7c99a..bbae562f 100644 --- a/web/resources/views/venix/user/announcement_drawer.tpl +++ b/web/resources/views/venix/user/announcement_drawer.tpl @@ -3,7 +3,7 @@

公告与维护信息

按发布时间查看站点通知、维护安排与故障说明。

-

打开后读取最新公告。

+

diff --git a/web/tests/AnnouncementDrawerBehaviorTest.mjs b/web/tests/AnnouncementDrawerBehaviorTest.mjs new file mode 100644 index 00000000..281bcb08 --- /dev/null +++ b/web/tests/AnnouncementDrawerBehaviorTest.mjs @@ -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: '', body: '\n第二行' }); + await test.respond(page([unsafe])); + assert.equal(articles(test).length, 1); assert.match(test.nodes.list.textContent, /