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 @@
按发布时间查看站点通知、维护安排与故障说明。