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/instances.js

668 lines
26 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { toast } from './toast.js?v=2026100206';
// The first twenty instances are rendered by PHP. This lightweight module only
// handles local filtering, pagination and batched live-state refreshes.
const byId = id => document.getElementById(id);
const POLL_INTERVAL = 15000;
const MAX_POLL_INTERVAL = 120000;
const state = {
vms: [],
stats: { total: 0, running: 0, stopped: 0 },
pagination: {
page: 1, per_page: 20, total: 0, total_pages: 1,
page_count: 0, has_previous: false, has_next: false, from: 0, to: 0,
},
user: {},
loading: false,
metadataLoading: false,
statusLoading: false,
liveStatsReady: false,
pageActive: true,
pollTimer: null,
pollFailures: 0,
};
function showError(message = '') {
const target = byId('cloud-page-error');
if (!target) return;
target.textContent = message;
target.hidden = !message;
}
async function api(path) {
const response = await fetch(path, {
method: 'GET', headers: { Accept: 'application/json' },
credentials: 'same-origin', cache: 'no-store',
});
let payload;
try { payload = await response.json(); }
catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); }
if (response.status === 401) {
location.assign('/auth/login');
throw new Error('登录已过期。');
}
if (!response.ok || payload?.ret === 0) {
const detail = Array.isArray(payload?.detail)
? payload.detail.map(item => item.msg || '输入错误').join(';') : payload?.detail;
throw new Error(String(detail || payload?.message || payload?.msg || payload?.error
|| `请求失败 (${response.status})`));
}
return payload;
}
function makeElement(tag, className = '', content) {
const element = document.createElement(tag);
if (className) element.className = className;
if (content !== undefined) element.textContent = String(content);
return element;
}
function firstText(...values) {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim() !== '') {
return String(value).trim();
}
}
return '';
}
function normalizeVm(vm) {
const source = vm && typeof vm === 'object' ? vm : {};
const fresh = source.state_fresh === true || source.fresh === true
|| source.fresh === 1 || source.fresh === '1' || source.fresh === 'true';
return {
...source,
uuid: String(source.uuid || source.id || ''),
api_id: String(source.api_id || source.id || source.uuid || ''),
vcpu: source.vcpu ?? source.cpu_cores,
memory_mib: source.memory_mib ?? source.ram_mib,
public_ip_cidr: source.public_ip_cidr || source.public_ip || '',
state_fresh: fresh,
state_observed_at: source.state_observed_at ?? source.last_success_at ?? null,
state_sync_status: String(source.state_sync_status ?? source.sync_status
?? (fresh ? 'fresh' : 'pending')).toLowerCase(),
state_label_hint: firstText(source.state_label_hint),
};
}
function stateCategory(value) {
const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, '');
if (normalized === 'running' || normalized === 'blocked') return 'running';
if (['shutoff', 'stopped', 'crashed'].includes(normalized)) return 'stopped';
return 'other';
}
function stateLabel(value) {
const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, '');
const labels = {
running: '运行中', blocked: '运行中', shutoff: '已关机', stopped: '已关机',
shutdown: '关机中', crashed: '已崩溃', paused: '已暂停', pmsuspended: '已挂起',
nostate: '等待宿主机同步', unknown: '等待宿主机同步',
};
return labels[normalized] || '等待宿主机同步';
}
function runtimeStateReady(vm) {
return hasKnownState(vm)
&& (String(vm?.state_sync_status || '').toLowerCase() === ''
|| String(vm?.state_sync_status || '').toLowerCase() === 'fresh');
}
function hasKnownState(vm) {
const state = String(vm?.state || '').toLowerCase();
const sync = String(vm?.state_sync_status || '').toLowerCase();
if (['pending', 'never'].includes(sync)) return false;
return state !== '' && state !== 'unknown' && state !== 'nostate'
&& !['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync);
}
function stateCategoryForVm(vm) {
const sync = String(vm?.state_sync_status || '').toLowerCase();
if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) {
return 'other';
}
if (!hasKnownState(vm)) return 'other';
return stateCategory(vm?.state);
}
function stateDisplay(vm) {
const sync = String(vm?.state_sync_status || '').toLowerCase();
if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) {
return { label: '暂时无法同步', category: 'other', note: '', noteClass: 'offline' };
}
if (!hasKnownState(vm)) {
const hint = firstText(vm?.state_label_hint,
['creating', 'provisioning', 'deploying'].includes(String(vm?.instance_status || ''))
? '部署中' : '等待宿主机同步');
return { label: hint, category: 'other', note: '', noteClass: '' };
}
const category = stateCategory(vm.state);
return {
label: stateLabel(vm.state),
category,
note: runtimeStateReady(vm) ? '' : '状态同步中',
noteClass: runtimeStateReady(vm) ? '' : 'stale',
};
}
function vmRegion(vm) {
return firstText(vm.region, vm.location, '未设置');
}
function vmIp(vm) {
return firstText(vm.public_ip_cidr, vm.public_ip).split('/')[0] || '未获取';
}
function vmSystemInfo(vm) {
if (vm.os_source === 'iso') return { label: '安装镜像', value: firstText(vm.install_iso, '未识别') };
if (vm.os_source === 'cloud_template') return { label: '系统镜像', value: firstText(vm.os_name, '未识别') };
return { label: '系统', value: firstText(vm.os_name, vm.install_iso, '未识别') };
}
function diskLabel(vm) {
if (Array.isArray(vm.disks) && vm.disks.length) {
const size = vm.disks.reduce((total, disk) => {
const capacity = Number(disk?.capacity_gib ?? disk?.size_gib ?? 0);
return total + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0);
}, 0);
if (size > 0) return `${Math.round(size * 100) / 100} GiB`;
}
const size = Number(vm.disk_gib);
return Number.isFinite(size) && size > 0 ? `${size} GiB` : '—';
}
function normalizeStats(value, vms = []) {
const source = value && typeof value === 'object' ? value : {};
const pageRunning = vms.filter(vm => stateCategoryForVm(vm) === 'running').length;
const pageStopped = vms.filter(vm => stateCategoryForVm(vm) === 'stopped').length;
const number = (candidate, fallback) => {
const parsed = Number(candidate);
return Number.isFinite(parsed) && parsed >= 0 ? Math.trunc(parsed) : fallback;
};
return {
total: number(source.total, vms.length),
running: number(source.running, pageRunning),
stopped: number(source.stopped, pageStopped),
};
}
function normalizePagination(value, fallbackPage = 1, fallbackTotal = 0) {
const source = value && typeof value === 'object' ? value : {};
const page = Math.max(1, Math.trunc(Number(source.page) || fallbackPage));
const totalPages = Math.max(1, Math.trunc(Number(source.total_pages) || 1));
const total = Math.max(0, Math.trunc(Number(source.total) || fallbackTotal));
return {
page,
per_page: Math.max(1, Math.trunc(Number(source.per_page) || 20)),
total,
page_count: Math.max(0, Math.trunc(Number(source.page_count) || 0)),
total_pages: totalPages,
has_previous: source.has_previous === true || page > 1,
has_next: source.has_next === true || page < totalPages,
from: Math.max(0, Math.trunc(Number(source.from) || 0)),
to: Math.max(0, Math.trunc(Number(source.to) || 0)),
};
}
function renderStats() {
if (byId('stat-total')) byId('stat-total').textContent = String(state.stats.total);
// The PHP bootstrap and the cache-only status endpoint already provide the
// last known counts. Render them immediately, including while a host is
// being re-synchronised; a stale row is explicitly marked in its status
// cell and must not make the whole summary look like it is still loading.
const liveValue = value => String(value);
if (byId('stat-running')) byId('stat-running').textContent = liveValue(state.stats.running);
if (byId('stat-stopped')) byId('stat-stopped').textContent = liveValue(state.stats.stopped);
}
async function copyText(value) {
if (navigator.clipboard?.writeText) {
try { await navigator.clipboard.writeText(value); return; } catch {}
}
const area = document.createElement('textarea');
area.value = value;
area.style.position = 'fixed';
area.style.opacity = '0';
document.body.append(area);
area.select();
try {
if (!document.execCommand('copy')) throw new Error('浏览器无法复制,请手动选择文本。');
} finally { area.value = ''; area.remove(); }
}
function copyIconButton(value, label) {
const button = makeElement('button', 'vm-copy-icon');
button.type = 'button';
button.dataset.copyValue = value;
button.dataset.copyLabel = label;
button.title = `复制${label}`;
button.setAttribute('aria-label', `复制${label}`);
const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
icon.setAttribute('viewBox', '0 0 24 24');
icon.setAttribute('aria-hidden', 'true');
const back = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
for (const [name, valuePart] of Object.entries({ x: '8', y: '8', width: '12', height: '12', rx: '2' })) {
back.setAttribute(name, valuePart);
}
const front = document.createElementNS('http://www.w3.org/2000/svg', 'path');
front.setAttribute('d', 'M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2');
icon.append(back, front);
button.append(icon);
return button;
}
function makeCell(row, label) {
const cell = document.createElement('td');
cell.dataset.label = label;
row.append(cell);
return cell;
}
function matchingVms() {
const query = (byId('search-input')?.value || '').trim().toLocaleLowerCase();
const filter = byId('state-filter')?.value || 'all';
return state.vms.filter(vm => {
const textMatches = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.public_ip,
vm.region, vm.location, vm.os_name, vm.install_iso]
.some(value => String(value || '').toLocaleLowerCase().includes(query));
const statusMatches = filter === 'all' || stateCategoryForVm(vm) === filter;
return textMatches && statusMatches;
});
}
function renderCount(filteredCount = state.vms.length) {
const target = byId('inventory-count');
if (!target) return;
const filtering = Boolean((byId('search-input')?.value || '').trim())
|| (byId('state-filter')?.value || 'all') !== 'all';
target.textContent = filtering
? `匹配 ${filteredCount} 台 · 当前页 ${state.vms.length} 台 · 共 ${state.pagination.total} 台`
: `当前页 ${state.vms.length} 台 · 共 ${state.pagination.total} 台`;
}
function renderVms(connectionError = false) {
const filtered = matchingVms();
renderCount(filtered.length);
const tbody = byId('vm-table-body');
const empty = byId('empty-state');
if (!tbody || !empty) return;
tbody.replaceChildren();
empty.hidden = filtered.length !== 0;
if (!filtered.length) {
if (connectionError) {
byId('empty-title').textContent = '无法加载实例';
byId('empty-description').textContent = '请稍后重试,或联系管理员检查服务状态。';
} else if (state.vms.length) {
byId('empty-title').textContent = '没有匹配的实例';
byId('empty-description').textContent = '尝试更换搜索词或状态筛选。';
} else {
byId('empty-title').textContent = '还没有实例';
byId('empty-description').textContent = '点击右上角“部署实例”开始。';
}
return;
}
const fragment = document.createDocumentFragment();
for (const vm of filtered) {
const row = document.createElement('tr');
row.dataset.vmId = vm.api_id;
row.dataset.vmUuid = vm.uuid;
const identity = makeElement('div', 'vm-identity');
identity.append(makeElement('div', 'vm-icon', '▣'));
const identityText = document.createElement('div');
const name = makeElement('a', 'vm-name-link', vm.name || '未命名实例');
name.href = `/user/cloud/instances/${encodeURIComponent(vm.api_id)}`;
name.dataset.vmUuid = vm.uuid;
name.setAttribute('aria-label', `管理实例 ${vm.name || vm.uuid}`);
const uuidRow = makeElement('span', 'vm-uuid-row');
const uuid = makeElement('span', 'vm-id', vm.uuid || 'UUID 未知');
if (vm.uuid) uuid.title = vm.uuid;
uuidRow.append(uuid);
if (vm.uuid) uuidRow.append(copyIconButton(vm.uuid, 'UUID'));
identityText.append(name, uuidRow);
identity.append(identityText);
makeCell(row, '实例').append(identity);
const display = stateDisplay(vm);
const status = makeElement('span', `state-pill ${display.category} vm-state-pill`, display.label);
const statusCell = makeCell(row, '状态');
statusCell.append(status);
if (display.note) {
statusCell.append(makeElement('small', `vm-state-sync ${display.noteClass}`, display.note));
}
makeCell(row, '地区').append(makeElement('span', 'vm-metadata', vmRegion(vm)));
const system = vmSystemInfo(vm);
makeCell(row, system.label).append(makeElement('span', 'vm-metadata', system.value));
const ip = vmIp(vm);
const ipRow = makeElement('span', 'vm-ip-copy-row');
ipRow.append(makeElement('span', 'vm-metadata vm-ip', ip));
if (ip !== '未获取') ipRow.append(copyIconButton(ip, '公网 IP'));
makeCell(row, '已配置公网 IP').append(ipRow);
const spec = makeElement('div', 'vm-spec');
spec.append(makeElement('strong', '', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`),
makeElement('small', '', '计算资源'));
makeCell(row, '规格').append(spec);
makeCell(row, '磁盘').append(makeElement('span', 'vm-spec', diskLabel(vm)));
fragment.append(row);
}
tbody.append(fragment);
}
function renderPagination() {
const navigation = byId('instances-pagination');
if (!navigation) return;
const { page, total_pages: totalPages, total, has_previous: previous, has_next: next } = state.pagination;
navigation.hidden = total === 0;
const busy = state.loading || state.metadataLoading || state.statusLoading;
navigation.setAttribute('aria-busy', String(busy));
if (byId('instances-page-label')) {
byId('instances-page-label').textContent = `第 ${page} / ${totalPages} 页 · 共 ${total} 台`;
}
if (byId('instances-previous')) {
byId('instances-previous').disabled = busy || !previous;
}
if (byId('instances-next')) {
byId('instances-next').disabled = busy || !next;
}
if (byId('refresh-button')) {
byId('refresh-button').disabled = busy;
byId('refresh-button').setAttribute('aria-busy', String(busy));
}
}
function updatePageUrl(page) {
const url = new URL(location.href);
if (page > 1) url.searchParams.set('page', String(page));
else url.searchParams.delete('page');
history.replaceState(history.state, '', `${url.pathname}${url.search}${url.hash}`);
}
function stopPolling() {
if (state.pollTimer !== null) window.clearTimeout(state.pollTimer);
state.pollTimer = null;
}
function nextPollDelay() {
if (!state.pollFailures) return POLL_INTERVAL;
return Math.min(MAX_POLL_INTERVAL, POLL_INTERVAL * (2 ** Math.min(state.pollFailures, 3)));
}
function schedulePolling(delay = nextPollDelay()) {
stopPolling();
if (!state.pageActive || document.hidden || !state.vms.length) return;
state.pollTimer = window.setTimeout(() => {
state.pollTimer = null;
void refreshStatuses(true);
}, delay);
}
function statusItems(payload) {
if (Array.isArray(payload?.vms)) return payload.vms;
if (Array.isArray(payload?.statuses)) return payload.statuses;
if (Array.isArray(payload?.items)) return payload.items;
if (payload?.statuses && typeof payload.statuses === 'object') {
return Object.entries(payload.statuses).map(([id, value]) => (
value && typeof value === 'object' ? { id, ...value } : { id, state: value }
));
}
return [];
}
function vmMatchesUpdate(vm, update) {
const candidates = [update?.api_id, update?.id, update?.uuid].map(value => String(value || ''));
return candidates.includes(vm.api_id) || candidates.includes(vm.uuid);
}
const VM_METADATA_FIELDS = Object.freeze([
'region', 'location', 'os_source', 'os_name', 'install_iso',
'public_ip_cidr', 'public_ip', 'login_name', 'vcpu', 'cpu_cores', 'memory_mib',
'ram_mib', 'disks', 'disk_gib', 'engine_metadata_version',
]);
function needsVmMetadata(vm) {
if (Number(vm?.engine_metadata_version) >= 1) return false;
const source = firstText(vm?.os_source);
if (!source) return true;
if (source === 'cloud_template') {
return !firstText(vm.public_ip_cidr, vm.public_ip)
|| !firstText(vm.os_name) || !firstText(vm.login_name);
}
if (source === 'iso') return !firstText(vm.install_iso);
return true;
}
function metadataItems(payload) {
if (Array.isArray(payload?.vms)) return payload.vms;
if (Array.isArray(payload?.items)) return payload.items;
return [];
}
function applyMetadata(payload) {
for (const update of metadataItems(payload)) {
if (!update || typeof update !== 'object') continue;
const vm = state.vms.find(item => vmMatchesUpdate(item, update));
if (!vm) continue;
const updateUuid = String(update.uuid || '').toLowerCase();
if (!updateUuid || updateUuid !== String(vm.uuid || '').toLowerCase()) continue;
for (const field of VM_METADATA_FIELDS) {
if (Object.prototype.hasOwnProperty.call(update, field)) vm[field] = update[field];
}
Object.assign(vm, normalizeVm(vm));
}
renderVms();
}
/** Fetch host-derived static fields only once for the currently visible page. */
async function refreshMetadata() {
if (!state.pageActive || state.metadataLoading || !state.vms.length) return;
const ids = state.vms.filter(needsVmMetadata).map(vm => vm.api_id).filter(Boolean);
if (!ids.length) return;
state.metadataLoading = true;
renderPagination();
try {
const payload = await api(`/api/v1/vms/metadata?ids=${encodeURIComponent(ids.join(','))}`);
applyMetadata(payload);
} catch {
// Keep the database-backed first paint usable. The independent status
// request below still runs, and a manual page refresh can retry metadata.
} finally {
state.metadataLoading = false;
renderPagination();
}
}
function applyStatuses(payload) {
const updates = statusItems(payload);
let statusFilterChanged = false;
let displayNameChanged = false;
for (const update of updates) {
const vm = state.vms.find(item => vmMatchesUpdate(item, update));
if (!vm) continue;
const candidateState = firstText(update.state, update.status);
const normalizedState = candidateState.toLowerCase().replace(/[_\s-]+/g, '');
const hasState = candidateState !== '' && normalizedState !== 'unknown'
&& normalizedState !== 'nostate';
const previousCategory = stateCategoryForVm(vm);
const previousName = String(vm.name || '');
const liveState = update?.live_state_available === true;
const nextState = hasState ? candidateState : vm.state;
const nextSync = firstText(update.state_sync_status, update.sync_status,
liveState ? 'fresh' : vm.state_sync_status || 'pending').toLowerCase();
const nextFresh = update.state_fresh === true || update.fresh === true
|| update.fresh === 1 || update.fresh === '1' || liveState;
Object.assign(vm, update, {
state: nextState,
state_fresh: nextFresh,
state_sync_status: nextSync,
state_observed_at: update.state_observed_at ?? update.last_success_at
?? (liveState ? Math.floor(Date.now() / 1000) : vm.state_observed_at),
state_label_hint: Object.prototype.hasOwnProperty.call(update, 'state_label_hint')
? firstText(update.state_label_hint) : vm.state_label_hint,
});
if (String(vm.name || '') !== previousName) displayNameChanged = true;
const nextCategory = stateCategoryForVm(vm);
if (previousCategory !== nextCategory) {
if (previousCategory === 'running') state.stats.running = Math.max(0, state.stats.running - 1);
if (previousCategory === 'stopped') state.stats.stopped = Math.max(0, state.stats.stopped - 1);
if (nextCategory === 'running') state.stats.running += 1;
if (nextCategory === 'stopped') state.stats.stopped += 1;
statusFilterChanged = true;
}
const row = Array.from(document.querySelectorAll('#vm-table-body tr[data-vm-id]'))
.find(item => item.dataset.vmId === vm.api_id || item.dataset.vmUuid === vm.uuid);
const pill = row?.querySelector('.vm-state-pill');
if (pill) {
const display = stateDisplay(vm);
pill.className = `state-pill ${display.category} vm-state-pill`;
pill.textContent = display.label;
const statusCell = pill.parentElement;
let note = statusCell?.querySelector('.vm-state-sync');
if (display.note) {
if (!note) {
note = makeElement('small', 'vm-state-sync');
statusCell?.append(note);
}
note.className = `vm-state-sync ${display.noteClass}`;
note.textContent = display.note;
} else if (note) {
note.remove();
}
}
}
if (payload?.stats && typeof payload.stats === 'object') {
state.stats = normalizeStats(payload.stats, state.vms);
}
state.liveStatsReady = state.vms.length === 0 || state.vms.every(runtimeStateReady);
renderStats();
if (displayNameChanged
|| (statusFilterChanged && (byId('state-filter')?.value || 'all') !== 'all')) {
renderVms();
}
}
async function refreshStatuses(scheduleNext = true) {
if (!state.pageActive || state.statusLoading || document.hidden || !state.vms.length) {
if (scheduleNext) schedulePolling();
return;
}
const ids = state.vms.map(vm => vm.api_id).filter(Boolean);
if (!ids.length) return;
state.statusLoading = true;
renderPagination();
try {
const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids.join(','))}`);
applyStatuses(payload);
state.pollFailures = 0;
showError();
} catch (error) {
state.pollFailures += 1;
if (state.pollFailures >= 2) {
showError(`${error?.message || '实例实时状态更新失败。'} 页面将自动重试。`);
}
} finally {
state.statusLoading = false;
renderPagination();
if (scheduleNext) schedulePolling();
}
}
async function loadPage(page = state.pagination.page, updateUrl = true) {
if (state.loading || state.metadataLoading) return;
const requestedPage = Math.max(1, Math.trunc(Number(page) || 1));
state.loading = true;
state.liveStatsReady = false;
stopPolling();
renderPagination();
let pageLoaded = false;
try {
const payload = await api(`/api/v1/vms/page?page=${encodeURIComponent(requestedPage)}`);
state.vms = (Array.isArray(payload?.vms) ? payload.vms : []).map(normalizeVm);
state.pagination = normalizePagination(payload?.pagination, requestedPage, state.vms.length);
state.stats = normalizeStats(payload?.stats, state.vms);
state.liveStatsReady = state.vms.length === 0 || state.vms.every(runtimeStateReady);
state.pollFailures = 0;
renderStats();
renderVms();
renderPagination();
if (updateUrl) updatePageUrl(state.pagination.page);
showError();
pageLoaded = true;
} catch (error) {
showError(error?.message || '实例加载失败,请稍后重试。');
if (!state.vms.length) renderVms(true);
} finally {
state.loading = false;
renderPagination();
}
if (pageLoaded) {
await Promise.all([refreshMetadata(), refreshStatuses(true)]);
}
}
function hydrate() {
const source = byId('instances-bootstrap');
if (!source) return false;
try {
const payload = JSON.parse(source.textContent || '{}');
if (!Array.isArray(payload?.vms)) return false;
state.vms = payload.vms.map(normalizeVm);
state.pagination = normalizePagination(payload.pagination, 1, state.vms.length);
state.stats = normalizeStats(payload.stats, state.vms);
state.liveStatsReady = state.vms.length === 0 || state.vms.every(runtimeStateReady);
state.user = payload.user && typeof payload.user === 'object' ? payload.user : {};
renderStats();
renderPagination();
renderCount(state.vms.length);
updatePageUrl(state.pagination.page);
return true;
} catch { return false; }
}
function bindEvents() {
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
byId('refresh-button')?.addEventListener('click', () => { void loadPage(state.pagination.page, false); });
byId('search-input')?.addEventListener('input', renderVms);
byId('state-filter')?.addEventListener('change', renderVms);
byId('instances-previous')?.addEventListener('click', () => {
if (!state.loading && !state.statusLoading && state.pagination.has_previous) {
void loadPage(state.pagination.page - 1);
}
});
byId('instances-next')?.addEventListener('click', () => {
if (!state.loading && !state.statusLoading && state.pagination.has_next) {
void loadPage(state.pagination.page + 1);
}
});
byId('vm-table-body')?.addEventListener('click', event => {
const button = event.target.closest?.('[data-copy-value]');
if (!button) return;
void copyText(button.dataset.copyValue || '')
.then(() => toast(`${button.dataset.copyLabel || '内容'}已复制。`, 'success'))
.catch(error => toast(error?.message || '复制失败。', 'error'));
});
window.addEventListener('pagehide', () => {
state.pageActive = false;
stopPolling();
});
window.addEventListener('pageshow', event => {
state.pageActive = true;
if (event.persisted) void refreshStatuses(true);
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) stopPolling();
else void refreshStatuses(true);
});
}
export async function initialize() {
const hydrated = hydrate();
bindEvents();
if (!hydrated) await loadPage(1, false);
else {
await Promise.all([refreshMetadata(), refreshStatuses(true)]);
}
}