From 3479a2a362becdad151b3294a12262b1c0555840 Mon Sep 17 00:00:00 2001 From: codex Date: Sat, 31 Oct 2026 18:54:11 +0800 Subject: [PATCH] feat(admin): add searchable cloud image catalog --- web/public/cloud/admin-catalog-filter.js | 70 +++++++++++++++++++ web/public/cloud/admin-catalog-runtime.js | 23 ++++-- web/public/cloud/admin.css | 14 ++++ .../views/venix/admin/cloud/templates.tpl | 6 ++ web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/AdminCatalogFilterBehaviorTest.mjs | 43 ++++++++++++ 6 files changed, 153 insertions(+), 5 deletions(-) create mode 100644 web/public/cloud/admin-catalog-filter.js create mode 100644 web/tests/AdminCatalogFilterBehaviorTest.mjs diff --git a/web/public/cloud/admin-catalog-filter.js b/web/public/cloud/admin-catalog-filter.js new file mode 100644 index 00000000..0caeb60c --- /dev/null +++ b/web/public/cloud/admin-catalog-filter.js @@ -0,0 +1,70 @@ +const runningStates = new Set(['preparing', 'validating', 'distributing', 'importing', + 'syncing', 'pending', 'deleting', 'retiring', 'fetching', 'uploading']); +const attentionStates = new Set(['degraded', 'error', 'failed', 'source_failed', + 'source_unknown', 'unknown', 'delete_failed', 'delete_unknown', 'delete_attention', + 'uncertain', 'missing', 'stale']); + +function matches(entry, query, status) { + const replicas = Array.isArray(entry.replicas) ? entry.replicas : []; + const states = [entry.state, entry.artifact?.state, + ...replicas.filter(replica => replica.host_eligible === true).map(replica => replica.state)] + .filter(Boolean).map(value => String(value).toLowerCase()); + const running = states.some(value => runningStates.has(value)); + const attention = states.some(value => attentionStates.has(value)) + || Boolean(entry.cleanup_reason || entry.artifact?.error_code) + || replicas.some(replica => replica.host_record_present === false + || replica.repair_reason === 'content_divergent'); + if (status === 'running' && !running) return false; + if (status === 'attention' && !attention) return false; + const searchable = [entry.name, entry.id, entry.catalog_key, entry.os_family, + entry.os_version, entry.version_label, + ...replicas.flatMap(replica => [replica.host_name, replica.host_region])] + .filter(Boolean).join(' ').normalize('NFKC').toLowerCase(); + return searchable.includes(query.normalize('NFKC').toLowerCase()); +} + +/** Filter a complete catalog without changing entries or their action policy. */ +export function mountAdminCatalogFilter({ form, count, onChange, + locationImpl = globalThis.location, historyImpl = globalThis.history } = {}) { + const query = form.elements.namedItem('catalog_q'); + const status = form.elements.namedItem('catalog_status'); + function restore() { + const params = new URLSearchParams(locationImpl?.search || ''); + query.value = (params.get('catalog_q') || '').slice(0, 80); + const value = params.get('catalog_status'); + status.value = ['running', 'attention'].includes(value) ? value : 'all'; + } + function changed(event) { + event?.preventDefault(); + if (locationImpl?.href && historyImpl?.replaceState) { + const url = new URL(locationImpl.href); + for (const [key, value] of [['catalog_q', query.value.trim()], + ['catalog_status', status.value === 'all' ? '' : status.value]]) { + if (value) url.searchParams.set(key, value); else url.searchParams.delete(key); + } + historyImpl.replaceState(historyImpl.state, '', url); + } + onChange(); + } + function reset(event) { + query.value = ''; status.value = 'all'; changed(event); + } + restore(); + form.addEventListener('input', changed); + form.addEventListener('change', changed); + form.addEventListener('submit', changed); + form.addEventListener('reset', reset); + return Object.freeze({ + apply(entries) { + const filtered = entries.filter(entry => matches(entry, query.value.trim(), status.value)); + count.textContent = `显示 ${filtered.length} / ${entries.length} 条记录`; + return filtered; + }, + destroy() { + form.removeEventListener('input', changed); + form.removeEventListener('change', changed); + form.removeEventListener('submit', changed); + form.removeEventListener('reset', reset); + }, + }); +} diff --git a/web/public/cloud/admin-catalog-runtime.js b/web/public/cloud/admin-catalog-runtime.js index 89df6f20..9253bdcf 100644 --- a/web/public/cloud/admin-catalog-runtime.js +++ b/web/public/cloud/admin-catalog-runtime.js @@ -20,6 +20,8 @@ const requestRuntime = window.VenixAdminRequestRuntime.create({ taskReceiptValidator: taskUrl, }); let templateUploadController = null; +let catalogFilter = null; +let catalogEntries = []; const confirmDanger = options => window.VenixAdminDangerDialog.confirm(options); const REMOTE_IMPORT_STORAGE_KEY = 'virt-cloud:template-remote:v1'; // Permission state is rendered by the server on the page. API endpoints keep @@ -579,6 +581,14 @@ function rescueTemplateCard(entry) { function renderRescueTemplates(list, entries) { for (const entry of entries) list.append(rescueTemplateCard(entry)); } +function renderCatalog() { + const list = byId('catalog-list'); list.replaceChildren(); + const entries = catalogFilter ? catalogFilter.apply(catalogEntries) : catalogEntries; + if (!entries.length) list.append(element('p', 'text-muted py-3', + catalogEntries.length ? '没有符合筛选条件的镜像,请调整或清空条件。' : '暂无镜像。')); + else if (isRescueCatalog()) renderRescueTemplates(list, entries); + else renderCloudTemplates(list, entries); +} async function loadCatalog() { const rescue = isRescueCatalog(); const epoch = ++state.epoch; @@ -587,9 +597,8 @@ async function loadCatalog() { try { const payload = await api(catalogPath()); if (epoch !== state.epoch) return; const entries = collection(payload, 'templates'); - if (!entries.length) list.append(element('p', 'text-muted', '暂无模版。')); - else if (rescue) renderRescueTemplates(list, entries); - else renderCloudTemplates(list, entries); + catalogEntries = entries; + renderCatalog(); if (rescue) { const available = entries.filter(entry => ['active', 'degraded'].includes(String(entry.state || ''))).length; notice(`已加载 ${entries.length} 个救援 ISO:${available} 个可挂载,${entries.length - available} 个正在处理或需核查。`); @@ -692,12 +701,18 @@ async function importRescue(event) { } async function initialize(expectedKind) { if (!root || root.dataset.cloudAdmin !== expectedKind) return; - window.addEventListener('pagehide', () => { + window.addEventListener('pagehide', event => { + if (!event.persisted) catalogFilter?.destroy(); templateUploadController?.destroy(); for (const observer of state.taskObservers) observer.stop('pagehide'); state.taskObservers.clear(); }); try { + if (expectedKind === 'templates' && byId('catalog-filter')) { + const { mountAdminCatalogFilter } = await import(versionedModuleUrl('./admin-catalog-filter.js')); + catalogFilter = mountAdminCatalogFilter({ form: byId('catalog-filter'), + count: byId('catalog-filter-count'), onChange: renderCatalog }); + } const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin) throw new Error('需要管理员权限。'); diff --git a/web/public/cloud/admin.css b/web/public/cloud/admin.css index 7536ed5c..dc65f992 100644 --- a/web/public/cloud/admin.css +++ b/web/public/cloud/admin.css @@ -394,6 +394,20 @@ gap: 18px; } +.cloud-catalog-filter { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(140px, 190px) auto; + align-items: end; + gap: 12px; + margin: 20px 0; +} +.cloud-catalog-filter label { min-width: 0; } +.cloud-catalog-filter > [role="status"] { grid-column: 1 / -1; } +@media (max-width: 575.98px) { + .cloud-catalog-filter { grid-template-columns: minmax(0, 1fr) auto; } + .cloud-catalog-filter label:first-child { grid-column: 1 / -1; } +} + .cloud-template-family { min-width: 0; overflow: hidden; diff --git a/web/resources/views/venix/admin/cloud/templates.tpl b/web/resources/views/venix/admin/cloud/templates.tpl index 7290270d..d97e5f01 100644 --- a/web/resources/views/venix/admin/cloud/templates.tpl +++ b/web/resources/views/venix/admin/cloud/templates.tpl @@ -88,6 +88,12 @@ +

支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10,以及 Ubuntu 20.04 至 26.04 的 x86_64 cloud-init 镜像。

“补齐副本”和“同步元数据”只会在服务器端确认可安全执行时显示;内容校验分歧与效果未知任务必须先人工核查,页面不会自动覆盖。

diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index bb051686..fd4d959f 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='2026103127' scope='global'} +{assign var=venix_asset_version value='2026103128' scope='global'} diff --git a/web/tests/AdminCatalogFilterBehaviorTest.mjs b/web/tests/AdminCatalogFilterBehaviorTest.mjs new file mode 100644 index 00000000..799aec34 --- /dev/null +++ b/web/tests/AdminCatalogFilterBehaviorTest.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { mountAdminCatalogFilter } from '../public/cloud/admin-catalog-filter.js'; + +const query = { value: '' }; const status = { value: '' }; const count = {}; +const handlers = {}; +const form = { elements: { namedItem: key => key === 'catalog_q' ? query : status }, + addEventListener(name, handler) { handlers[name] = handler; }, + removeEventListener(name) { delete handlers[name]; } }; +const location = new URL('https://panel.test/admin/cloud-templates?catalog_q=debian&catalog_status=attention&other=keep'); +let changes = 0; +const filter = mountAdminCatalogFilter({ form, count, onChange() { changes += 1; }, + locationImpl: location, historyImpl: { state: {}, replaceState(state, title, url) { location.href = url.href; } } }); +const ready = Object.freeze({ id: '1', name: 'Debian 13', state: 'active', + artifact: { state: 'ready' }, replicas: [{ host_eligible: true, exact: true, state: 'ready' }] }); +const missing = Object.freeze({ id: '2', name: 'Debian 12', state: 'active', + replicas: [{ host_name: 'HKG-A', host_region: 'HongKong', host_eligible: true, state: 'missing', repair_action: 'import' }] }); +const running = Object.freeze({ id: '3', name: 'Ubuntu 24.04', state: 'distributing', + replicas: [{ host_eligible: true, state: 'pending' }] }); +const rescue = Object.freeze({ id: '4', name: 'SystemRescue 12', state: 'retiring', + replicas: [{ host_eligible: true, state: 'delete_unknown' }], artifact: { state: 'delete_attention' } }); +const entries = [ready, missing, running, rescue]; +assert.deepEqual(filter.apply(entries), [missing]); +assert.equal(count.textContent, '显示 1 / 4 条记录'); +assert.equal(missing.replicas[0].repair_action, 'import', 'Filtering must not rewrite action eligibility.'); +query.value = ''; status.value = 'running'; handlers.change({ preventDefault() {} }); +assert.deepEqual(filter.apply(entries), [running, rescue]); +assert.equal(location.searchParams.get('catalog_status'), 'running'); +assert.equal(location.searchParams.get('other'), 'keep'); +status.value = 'all'; query.value = 'hkg-a'; handlers.input(); +assert.deepEqual(filter.apply(entries), [missing]); +query.value = 'UBUNTU'; +assert.deepEqual(filter.apply(entries), [running], 'Unicode-normalized search failed.'); +status.value = 'attention'; query.value = 'systemrescue'; +assert.deepEqual(filter.apply(entries), [rescue], 'Retirement cleanup debt was hidden from the abnormal filter.'); +assert.deepEqual(filter.apply([...entries, { name: 'SystemRescue 13', state: 'source_unknown' }]).length, 2, + 'Refreshing catalog data discarded the current filters.'); +handlers.reset({ preventDefault() {} }); +assert.deepEqual(filter.apply(entries), entries); +assert.equal(location.searchParams.has('catalog_q'), false); +assert.equal(location.searchParams.has('catalog_status'), false); +assert.ok(changes >= 3); +filter.destroy(); assert.equal(Object.keys(handlers).length, 0); +console.log('Cloud and rescue catalog search, state filtering and URL persistence passed.');