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/public/cloud/announcements.js

326 lines
15 KiB
JavaScript

// 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,
foreground: false, timer: null, opener: null, scroll: null, closing: false,
};
function element(tag, className = '', value) {
const node = document.createElement(tag);
node.className = className;
if (value !== undefined) node.textContent = String(value);
return node;
}
function setMessage(message, tone = '') {
const node = byId('panel-announcements-state');
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) {
// The API supplies the publication time in the site's timezone. Do not parse
// an unzoned SQL date as UTC or substitute a browser-generated publication time.
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value) ? value : '时间未记录';
}
function renderItems() {
const list = byId('panel-announcements-list');
list.replaceChildren();
for (const item of state.items) {
const article = element('article', 'panel-announcements-item');
article.dataset.announcementId = String(item.id);
const meta = element('div', 'panel-announcements-meta');
const type = ['notice', 'maintenance', 'incident'].includes(item.type) ? item.type : 'notice';
const fallback = { notice: '通知', maintenance: '维护', incident: '故障' }[type];
meta.append(element('span', `panel-announcements-type is-${type}`, item.type_label || fallback));
const published = element('time', '', `发布于 ${dateText(item.published_at)}`);
if (dateText(item.published_at) !== '时间未记录') published.dateTime = item.published_at.replace(' ', 'T');
meta.append(published);
if (item.updated_at && item.updated_at !== item.published_at) {
meta.append(element('span', '', `更新于 ${dateText(item.updated_at)}`));
}
article.append(meta, element('h3', '', item.title || '站点公告'), element('p', 'panel-announcements-body', item.body ?? ''));
list.append(article);
}
if (!state.items.length) list.append(element('p', 'panel-announcements-empty', '暂无已发布的公告。'));
}
function renderControls() {
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');
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) && !state.closing && 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 hydrate() {
const source = byId('panel-announcements-bootstrap');
if (!source) return false;
try {
const payload = JSON.parse(source.textContent || '{}');
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 > pagination.total_pages) return false;
state.items = publishedItems(payload.items);
state.pagination = pagination;
return true;
} catch {
return false;
}
}
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) {
const timeout = setTimeout(() => controller.abort('timeout'), 15000);
try {
const response = await fetch(`/api/v1/announcements?page=${page}&per_page=10`, {
headers: { Accept: 'application/json' }, credentials: 'same-origin',
cache: 'no-store', signal: controller.signal,
});
if (response.status === 401) throw new Error('登录已过期,请重新登录后查看公告。');
if (response.status === 403) throw new Error('当前账号无法读取公告。');
let payload;
try { payload = await response.json(); }
catch { throw new Error('公告服务返回异常,请稍后重试。'); }
if (!response.ok || payload?.ret === 0) {
throw new Error(typeof payload?.detail === 'string' ? payload.detail : `公告读取失败 (${response.status})。`);
}
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 > pagination.total_pages) {
throw new Error('公告数据格式无效,请稍后重试。');
}
return payload;
} catch (error) {
if (controller.signal.reason === 'timeout') throw new Error('公告读取超时,请稍后重试。');
throw error;
} finally { clearTimeout(timeout); }
}
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;
state.foreground = source !== 'auto';
if (state.foreground) renderControls();
try {
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('');
// Only a completed read advances this timestamp; pending/failed refreshes
// keep it visible and never replace it with progress messages.
const readTime = byId('panel-announcements-read-time');
const label = `读取于 ${new Date().toLocaleTimeString('zh-CN', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}`;
if (readTime.textContent !== label) readTime.textContent = label;
if (readTime.hidden) readTime.hidden = false;
} catch (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;
state.foreground = false;
if (canRefresh()) { renderControls(); scheduleRefresh(); }
}
}
}
function historyData(changes = {}) {
return { ...(history.state && typeof history.state === 'object' ? history.state : {}), ...changes };
}
function finishClose() {
state.closing = false;
stopRequests();
document.documentElement.classList.remove('panel-announcements-open');
document.body.style.removeProperty('--panel-announcements-scroll-top');
if (state.scroll) { window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' }); state.scroll = null; }
document.querySelectorAll('[data-announcements-open]').forEach(button => button.setAttribute('aria-expanded', 'false'));
if (state.opener?.isConnected) state.opener.focus({ preventScroll: true });
state.opener = null;
if (history.state?.panelAnnouncementsScroll) history.replaceState(historyData({ panelAnnouncementsScroll: undefined }), '', location.href);
renderControls();
}
function close() {
if (state.closing) return;
state.closing = true;
stopRequests();
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
if (closed) finishClose();
else state.closing = false;
});
}
function open(opener) {
if (dialog.open) return;
state.closing = false;
state.opener = opener || document.querySelector('[data-announcements-open]');
state.scroll = { x: window.scrollX, y: window.scrollY };
document.body.style.setProperty('--panel-announcements-scroll-top', `${-state.scroll.y}px`);
document.documentElement.classList.add('panel-announcements-open');
window.VenixDrawerMotion.openDrawerWithMotion(dialog);
byId('panel-announcements-close').focus({ preventScroll: true });
document.querySelectorAll('[data-announcements-open]').forEach(button => button.setAttribute('aria-expanded', 'true'));
// Every open checks for current publications immediately. Existing content
// remains visible and this revalidation stays silent until new data arrives.
void load(1, state.pagination ? 'auto' : 'initial');
}
if (dialog) {
if (hydrate()) {
// Render the server snapshot before the first click. Opening the drawer
// only performs a silent revalidation, so the visible content is ready.
renderItems();
renderControls();
}
document.addEventListener('click', event => {
const trigger = event.target.closest('[data-announcements-open]');
if (!trigger || event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
event.preventDefault(); open(trigger);
});
byId('panel-announcements-close').addEventListener('click', close);
byId('panel-announcements-refresh').addEventListener('click', () => { void load(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;
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) close();
});
window.addEventListener('popstate', () => { if (dialog.open) close(); });
window.addEventListener('pagehide', () => {
stopRequests();
if (state.scroll) history.replaceState(historyData({ panelAnnouncementsScroll: state.scroll }), '', location.href);
});
window.addEventListener('pageshow', event => { if (event.persisted && dialog.open) close(); });
const stored = history.state?.panelAnnouncementsScroll;
if (stored && Number.isFinite(stored.x) && Number.isFinite(stored.y)) {
requestAnimationFrame(() => {
window.scrollTo({ left: stored.x, top: stored.y, behavior: 'instant' });
history.replaceState(historyData({ panelAnnouncementsScroll: undefined }), '', location.href);
});
}
const url = new URL(location.href);
if (url.searchParams.get('announcements') === '1') {
url.searchParams.delete('announcements');
history.replaceState(historyData(), '', url);
open();
}
}