feat: 托管应用操作中显示加载状态并自动刷新

This commit is contained in:
2026-11-06 15:52:29 +08:00
parent 38cf1ff3ed
commit f0313d4306
3 changed files with 163 additions and 40 deletions
+9
View File
@@ -92,6 +92,15 @@
"exited": "Exited", "exited": "Exited",
"missing": "Missing" "missing": "Missing"
}, },
"busy": {
"deploy": "Deploying",
"update": "Updating",
"start": "Starting",
"stop": "Stopping",
"restart": "Restarting",
"rollback": "Rolling back",
"delete": "Deleting"
},
"serviceRole": { "serviceRole": {
"web": "Web Entry", "web": "Web Entry",
"worker": "Background Service", "worker": "Background Service",
+9
View File
@@ -92,6 +92,15 @@
"exited": "已退出", "exited": "已退出",
"missing": "未创建" "missing": "未创建"
}, },
"busy": {
"deploy": "部署中",
"update": "更新中",
"start": "启动中",
"stop": "停止中",
"restart": "重启中",
"rollback": "回滚中",
"delete": "删除中"
},
"serviceRole": { "serviceRole": {
"web": "Web 入口", "web": "Web 入口",
"worker": "后台服务", "worker": "后台服务",
+145 -40
View File
@@ -16,7 +16,7 @@
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4h12M2 8h12M2 12h12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg> <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4h12M2 8h12M2 12h12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
</template> </template>
</n-button> </n-button>
<n-button @click="loadApps">{{ t("common.refresh") }}</n-button> <n-button @click="loadApps()">{{ t("common.refresh") }}</n-button>
<n-button :loading="downloadingExample" @click="saveExample">{{ t("hosting.downloadExample") }}</n-button> <n-button :loading="downloadingExample" @click="saveExample">{{ t("hosting.downloadExample") }}</n-button>
<permission-button :permission="APPS_CREATE" type="primary" @click="openDeploy()">{{ t("hosting.deploy") }}</permission-button> <permission-button :permission="APPS_CREATE" type="primary" @click="openDeploy()">{{ t("hosting.deploy") }}</permission-button>
</div> </div>
@@ -36,7 +36,10 @@
</div> </div>
<div class="hosting-card-body"> <div class="hosting-card-body">
<div class="hosting-card-meta"> <div class="hosting-card-meta">
<n-tag :type="statusType(app.status)" size="small">{{ statusLabel(app.status) }}</n-tag> <n-tag :type="busyKind(app) ? 'info' : statusType(app.status)" size="small">
<span v-if="busyKind(app)" class="hosting-busy"><i class="hosting-spinner" aria-hidden="true" />{{ busyLabel(busyKind(app)) }}</span>
<template v-else>{{ statusLabel(app.status) }}</template>
</n-tag>
</div> </div>
<div class="hosting-address" @click.stop> <div class="hosting-address" @click.stop>
<span>{{ app.url }}</span> <span>{{ app.url }}</span>
@@ -55,10 +58,11 @@
<n-icon :component="Shield20Regular" :size="16" /> <n-icon :component="Shield20Regular" :size="16" />
<span>{{ t("hosting.manage") }}</span> <span>{{ t("hosting.manage") }}</span>
</button> </button>
<button v-if="authStore.has(APPS_OPERATE)" type="button" class="hosting-action" :class="app.desired_state === 'running' ? 'is-stop' : 'is-start'" @click="togglePower(app)"> <button v-if="authStore.has(APPS_OPERATE)" type="button" class="hosting-action" :class="powerTone(app)" :disabled="!!busyKind(app)" @click="togglePower(app)">
<svg v-if="app.desired_state === 'running'" viewBox="0 0 16 16" width="15" height="15" aria-hidden="true"><rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2" fill="none" stroke="currentColor" stroke-width="1.6"/></svg> <i v-if="busyKind(app)" class="hosting-spinner" aria-hidden="true" />
<svg v-else-if="app.desired_state === 'running'" viewBox="0 0 16 16" width="15" height="15" aria-hidden="true"><rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>
<svg v-else viewBox="0 0 16 16" width="15" height="15" aria-hidden="true"><path d="M5.2 3.6 12.2 8 5.2 12.4Z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></svg> <svg v-else viewBox="0 0 16 16" width="15" height="15" aria-hidden="true"><path d="M5.2 3.6 12.2 8 5.2 12.4Z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></svg>
<span>{{ app.desired_state === "running" ? t("hosting.stop") : t("hosting.start") }}</span> <span>{{ powerLabel(app) }}</span>
</button> </button>
<n-dropdown trigger="click" placement="bottom-end" :options="moreOptions(app)" @select="(key: string) => handleMore(app, key)"> <n-dropdown trigger="click" placement="bottom-end" :options="moreOptions(app)" @select="(key: string) => handleMore(app, key)">
<button type="button" class="hosting-action hosting-action-more" :title="t('common.moreActions')" :aria-label="t('common.moreActions')"> <button type="button" class="hosting-action hosting-action-more" :title="t('common.moreActions')" :aria-label="t('common.moreActions')">
@@ -250,6 +254,7 @@ import {
uploadAppPackage, uploadAppPackage,
type AppDetail, type AppDetail,
type AppJob, type AppJob,
type AppJobSubmit,
type AppPackagePreview, type AppPackagePreview,
type AppServiceState, type AppServiceState,
type HostedApp type HostedApp
@@ -280,6 +285,11 @@ const deleteData = ref(false);
const viewMode = ref<"card" | "list">(localStorage.getItem("metrix.hosting.view") === "list" ? "list" : "card"); const viewMode = ref<"card" | "list">(localStorage.getItem("metrix.hosting.view") === "list" ? "list" : "card");
const brandUrls = ref<Record<string, string>>({}); const brandUrls = ref<Record<string, string>>({});
let brandTicket = 0; let brandTicket = 0;
let brandKey = "";
const pendingOps = ref<Record<number, string>>({});
let listTicket = 0;
let refreshTimer = 0;
let unmounted = false;
const pagination = reactive({ page: 1, pageSize: 20, itemCount: 0, pageSizes: [20, 50, 100], showSizePicker: true }); const pagination = reactive({ page: 1, pageSize: 20, itemCount: 0, pageSizes: [20, 50, 100], showSizePicker: true });
const settings = reactive({ const settings = reactive({
name: "", name: "",
@@ -338,7 +348,12 @@ const columns = computed<DataTableColumns<HostedApp>>(() => [
title: t("hosting.field.status"), title: t("hosting.field.status"),
key: "status", key: "status",
width: 110, width: 110,
render: (row) => h(NTag, { type: statusType(row.status), size: "small" }, () => statusLabel(row.status)) render: (row) => {
const kind = busyKind(row);
return kind
? h(NTag, { type: "info", size: "small" }, () => h("span", { class: "hosting-busy" }, [h("i", { class: "hosting-spinner", "aria-hidden": "true" }), busyLabel(kind)]))
: h(NTag, { type: statusType(row.status), size: "small" }, () => statusLabel(row.status));
}
}, },
{ title: t("hosting.field.version"), key: "version", width: 140, render: (row) => row.version || "-" }, { title: t("hosting.field.version"), key: "version", width: 140, render: (row) => row.version || "-" },
{ title: t("field.updatedAt"), key: "updated_at", width: 170, render: (row) => formatDateTime(row.updated_at) }, { title: t("field.updatedAt"), key: "updated_at", width: 170, render: (row) => formatDateTime(row.updated_at) },
@@ -364,10 +379,11 @@ const columns = computed<DataTableColumns<HostedApp>>(() => [
circle: true, circle: true,
quaternary: true, quaternary: true,
size: "small", size: "small",
title: row.desired_state === "running" ? t("hosting.stop") : t("hosting.start"), disabled: !!busyKind(row),
onClick: () => (row.desired_state === "running" ? confirmAction(row, "stop") : void runOperation(row, "start")) title: powerLabel(row),
onClick: () => togglePower(row)
}, },
() => (row.desired_state === "running" ? stopMark() : playMark()) () => (busyKind(row) ? h("i", { class: "hosting-spinner", "aria-hidden": "true" }) : row.desired_state === "running" ? stopMark() : playMark())
) )
: null, : null,
h( h(
@@ -391,20 +407,58 @@ onMounted(async () => {
await Promise.all([loadApps(), loadRoles()]); await Promise.all([loadApps(), loadRoles()]);
}); });
async function loadApps() { async function loadApps(quiet = false) {
loading.value = true; const ticket = ++listTicket;
if (!quiet) loading.value = true;
let ok = false;
try { try {
const result = await listApps({ keyword: keyword.value, page: pagination.page, page_size: pagination.pageSize }); const result = await listApps({ keyword: keyword.value, page: pagination.page, page_size: pagination.pageSize });
if (ticket !== listTicket) return;
apps.value = result.items; apps.value = result.items;
pagination.itemCount = result.total; pagination.itemCount = result.total;
void loadBrands(result.items); const key = result.items.map((app) => `${app.id}:${app.version}:${app.has_icon}:${app.has_cover}`).join("|");
if (!quiet || key !== brandKey) {
brandKey = key;
void loadBrands(result.items);
}
ok = true;
} catch (error) { } catch (error) {
showError(message, error); if (ticket === listTicket) showError(message, error);
} finally { } finally {
loading.value = false; if (ticket === listTicket) {
loading.value = false;
if (ok) scheduleRefresh();
}
} }
} }
function scheduleRefresh() {
window.clearTimeout(refreshTimer);
if (unmounted || !apps.value.some((app) => busyKind(app))) return;
refreshTimer = window.setTimeout(() => void loadApps(true), 1500);
}
function busyKind(app: HostedApp) {
return pendingOps.value[app.id] || app.active_job_kind || "";
}
function busyLabel(kind: string) {
const known = ["deploy", "update", "start", "stop", "restart", "rollback", "delete"];
return known.includes(kind) ? t(`hosting.busy.${kind}`) : t("hosting.status.deploying");
}
function powerTone(app: HostedApp) {
const kind = busyKind(app);
if (kind) return kind === "stop" || kind === "delete" ? "is-stop" : "is-start";
return app.desired_state === "running" ? "is-stop" : "is-start";
}
function powerLabel(app: HostedApp) {
const kind = busyKind(app);
if (kind) return busyLabel(kind);
return app.desired_state === "running" ? t("hosting.stop") : t("hosting.start");
}
async function loadRoles() { async function loadRoles() {
try { try {
roles.value = await listAppRoles(); roles.value = await listAppRoles();
@@ -479,6 +533,7 @@ async function submitDeploy() {
admin_role_ids: preview.value.manifest.admin_auth === "metrix" ? deployAdminRoles.value : [], admin_role_ids: preview.value.manifest.admin_auth === "metrix" ? deployAdminRoles.value : [],
user_role_ids: preview.value.manifest.user_auth === "metrix" ? deployUserRoles.value : [] user_role_ids: preview.value.manifest.user_auth === "metrix" ? deployUserRoles.value : []
}); });
void loadApps(true);
await pollJob(submitted.job_id); await pollJob(submitted.job_id);
} catch (error) { } catch (error) {
showError(message, error); showError(message, error);
@@ -546,12 +601,34 @@ async function saveSettings() {
} }
} }
async function runOperation(app: HostedApp, action: "start" | "stop" | "restart") { function runOperation(app: HostedApp, action: "start" | "stop" | "restart") {
return trackJob(app, action, () => operateApp(app.id, action));
}
async function trackJob(app: HostedApp, kind: string, submit: () => Promise<AppJobSubmit>) {
if (pendingOps.value[app.id]) return;
pendingOps.value = { ...pendingOps.value, [app.id]: kind };
try { try {
const submitted = await operateApp(app.id, action); const submitted = await submit();
await pollJob(submitted.job_id); void loadApps(true);
const job = await waitJob(submitted.job_id);
if (job.status === "success") message.success(t("hosting.jobSuccess"));
else if (job.status === "failed") message.error(job.error_code ? t(job.error_code as never, job.error_params) : t("hosting.jobFailed"));
} catch (error) { } catch (error) {
showError(message, error); showError(message, error);
} finally {
await loadApps(true);
const next = { ...pendingOps.value };
delete next[app.id];
pendingOps.value = next;
}
}
async function waitJob(jobId: string) {
for (;;) {
const job = await getAppJob(jobId);
if (job.status === "success" || job.status === "failed" || unmounted) return job;
await new Promise((resolve) => window.setTimeout(resolve, 1000));
} }
} }
@@ -565,14 +642,10 @@ function confirmDelete(app: HostedApp) {
}); });
} }
async function removeApp(app: HostedApp) { function removeApp(app: HostedApp) {
try { const withData = deleteData.value;
const submitted = await deleteApp(app.id, deleteData.value); showDetail.value = false;
showDetail.value = false; return trackJob(app, "delete", () => deleteApp(app.id, withData));
await pollJob(submitted.job_id);
} catch (error) {
showError(message, error);
}
} }
function handleMore(app: HostedApp, key: string) { function handleMore(app: HostedApp, key: string) {
@@ -598,25 +671,21 @@ function confirmAction(app: HostedApp, action: "stop" | "restart" | "rollback")
}); });
} }
async function runRollback(app: HostedApp) { function runRollback(app: HostedApp) {
try { return trackJob(app, "rollback", () => rollbackApp(app.id));
const submitted = await rollbackApp(app.id);
await pollJob(submitted.job_id);
} catch (error) {
showError(message, error);
}
} }
function moreOptions(app: HostedApp) { function moreOptions(app: HostedApp) {
const busy = !!busyKind(app);
return [ return [
{ label: t("hosting.details"), key: "details" }, { label: t("hosting.details"), key: "details" },
authStore.has(APPS_OPERATE) ? { label: t("hosting.restart"), key: "restart" } : null, authStore.has(APPS_OPERATE) ? { label: t("hosting.restart"), key: "restart", disabled: busy } : null,
authStore.has(APPS_UPDATE) ? { label: t("hosting.updateVersion"), key: "update" } : null, authStore.has(APPS_UPDATE) ? { label: t("hosting.updateVersion"), key: "update", disabled: busy } : null,
authStore.has(APPS_UPDATE) && app.has_previous ? { label: t("hosting.rollback"), key: "rollback" } : null, authStore.has(APPS_UPDATE) && app.has_previous ? { label: t("hosting.rollback"), key: "rollback", disabled: busy } : null,
{ label: t("hosting.logs"), key: "logs" }, { label: t("hosting.logs"), key: "logs" },
authStore.has(APPS_UPDATE) ? { label: t("hosting.settings"), key: "settings" } : null, authStore.has(APPS_UPDATE) ? { label: t("hosting.settings"), key: "settings" } : null,
authStore.has(APPS_DELETE) ? { label: t("common.delete"), key: "delete" } : null authStore.has(APPS_DELETE) ? { label: t("common.delete"), key: "delete", disabled: busy } : null
].filter(Boolean) as { label: string; key: string }[]; ].filter(Boolean) as { label: string; key: string; disabled?: boolean }[];
} }
function parseEnv(value: string): Record<string, string> { function parseEnv(value: string): Record<string, string> {
@@ -643,6 +712,7 @@ function openAdmin(app: HostedApp) {
} }
function togglePower(app: HostedApp) { function togglePower(app: HostedApp) {
if (busyKind(app)) return;
if (app.desired_state === "running") confirmAction(app, "stop"); if (app.desired_state === "running") confirmAction(app, "stop");
else void runOperation(app, "start"); else void runOperation(app, "start");
} }
@@ -688,6 +758,8 @@ function stopMark() {
} }
onUnmounted(() => { onUnmounted(() => {
unmounted = true;
window.clearTimeout(refreshTimer);
for (const url of Object.values(brandUrls.value)) URL.revokeObjectURL(url); for (const url of Object.values(brandUrls.value)) URL.revokeObjectURL(url);
}); });
@@ -885,15 +957,19 @@ function stepStatus(status: string): StepsProps["status"] {
flex: 0 0 auto; flex: 0 0 auto;
} }
.hosting-action:hover { .hosting-action:not(:disabled):hover {
color: var(--primary-color); color: var(--primary-color);
background: color-mix(in srgb, currentColor 8%, transparent); background: color-mix(in srgb, currentColor 8%, transparent);
} }
.hosting-action:active { .hosting-action:not(:disabled):active {
background: color-mix(in srgb, currentColor 14%, transparent); background: color-mix(in srgb, currentColor 14%, transparent);
} }
.hosting-action:disabled {
cursor: progress;
}
.hosting-action:focus-visible { .hosting-action:focus-visible {
outline: 2px solid var(--primary-focus); outline: 2px solid var(--primary-focus);
outline-offset: -2px; outline-offset: -2px;
@@ -907,7 +983,7 @@ function stepStatus(status: string): StepsProps["status"] {
color: var(--danger-color); color: var(--danger-color);
} }
.hosting-action.is-stop:hover { .hosting-action.is-stop:not(:disabled):hover {
color: var(--danger-strong); color: var(--danger-strong);
} }
@@ -934,6 +1010,35 @@ function stepStatus(status: string): StepsProps["status"] {
color: var(--danger-color); color: var(--danger-color);
} }
.hosting-page :deep(.hosting-busy) {
display: inline-flex;
align-items: center;
gap: 5px;
}
.hosting-page :deep(.hosting-spinner) {
display: inline-block;
flex: 0 0 auto;
width: 12px;
height: 12px;
box-sizing: border-box;
border: 1.6px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: hosting-spin 0.8s linear infinite;
}
.hosting-card-actions .hosting-spinner {
width: 14px;
height: 14px;
}
@keyframes hosting-spin {
to {
transform: rotate(360deg);
}
}
.hosting-deploy-modal { .hosting-deploy-modal {
width: min(760px, 92vw); width: min(760px, 92vw);
} }