feat(console): confirm leaving unsaved page work

Guard route changes when an editor or changed order draft is open. Cancel superseded questions and restore the shown history entry when repeated Back or Forward navigation is refused; only completed navigation resets page work.
This commit is contained in:
翅膀 committed 2026-10-17 12:03:27 +08:00
1 parent 535bfa98ce
commit 1c4639b07d
7 files changed
+104 -6

No files matched your search

+9 -2
View File
@@ -4,7 +4,9 @@
<AlertDialogOverlay class="confirm-overlay" />
<AlertDialogContent class="confirm-dialog">
<div class="confirm-body">
<span class="confirm-icon" aria-hidden="true"><Trash2 :size="18" /></span>
<span class="confirm-icon" aria-hidden="true"
><component :is="KIND_ICONS[shown?.kind ?? 'delete']" :size="18"
/></span>
<div class="min-w-0 space-y-1.5">
<AlertDialogTitle class="confirm-title">{{ shown?.title }}</AlertDialogTitle>
<AlertDialogDescription v-if="shown?.description" class="confirm-description">
@@ -26,7 +28,7 @@
</template>
<script setup lang="ts">
import { Trash2 } from "lucide-vue-next";
import { Trash2, TriangleAlert } from "lucide-vue-next";
import {
AlertDialogCancel,
AlertDialogContent,
@@ -41,6 +43,11 @@ import type { ConfirmOptions } from "~/composables/useConfirm";
const { t } = useI18n();
const { pending: request, settle, attachHost } = useConfirm();
const KIND_ICONS = {
delete: Trash2,
leave: TriangleAlert,
} satisfies Record<NonNullable<ConfirmOptions["kind"]>, typeof Trash2>;
// Keep the last request on screen while the close animation plays.
const shown = ref<ConfirmOptions | null>(null);
watch(
+84 -1
View File
@@ -413,7 +413,7 @@ import AdminHome from "~/components/AdminHome.vue";
const { t, toggle } = useI18n();
const { push } = useToasts();
const { confirm } = useConfirm();
const { confirm, settle: dismissConfirm } = useConfirm();
const route = useRoute();
const router = useRouter();
@@ -594,6 +594,89 @@ function onMobileNavClick(event: MouseEvent): void {
if (tab?.getAttribute("aria-selected") === "true" && routeGroupId.value) switchView("groups");
}
/** Work on the current page that leaving it would throw away. */
function hasUnsavedWork(): boolean {
return editorOpen.value || groupEditorOpen.value || (reordering.value && orderChanged.value);
}
/** Counts navigations reaching the guards; a newer one supersedes the question. */
let navigationAttempt = 0;
/** Ask before a navigation throws work away; the page resets once it happened. */
async function confirmLeave(): Promise<boolean> {
if (!hasUnsavedWork()) return true;
const attempt = navigationAttempt;
const leave = await confirm({
title: t("confirm.leaveUnsaved"),
description: t("confirm.leaveUnsavedDesc"),
confirmText: t("confirm.leave"),
kind: "leave",
});
// Superseded while asking: let the router cancel this navigation itself.
// Refusing it would read as "stay" and step the browser history back again,
// on top of the newer navigation that already moved it.
if (attempt !== navigationAttempt) return true;
// Staying after Back/Forward: the browser has already moved. The router
// steps back its own move; earlier, superseded moves are undone after it.
if (!leave && historyPosition() !== shownPosition) {
window.addEventListener("popstate", restoreShownEntry, { once: true });
}
return leave;
}
/** vue-router's position (in `history.state`) of the current history entry. */
function historyPosition(): number | null {
const position = (window.history.state as { position?: unknown } | null)?.position;
return typeof position === "number" ? position : null;
}
/** History position of the page on screen, as of the last completed navigation. */
let shownPosition = typeof window === "undefined" ? null : historyPosition();
const stopTrackingPosition = router.afterEach((_to, _from, failure) => {
if (!failure) shownPosition = historyPosition();
});
onBeforeUnmount(stopTrackingPosition);
/** Move the browser back to the entry on screen without starting a navigation. */
function restoreShownEntry(): void {
const position = historyPosition();
if (position !== null && shownPosition !== null && position !== shownPosition) {
router.options.history.go(shownPosition - position, false);
}
}
// A newer navigation supersedes one still waiting for an answer: that
// question (like any other confirmation of this page) is cancelled first.
function supersedePending(): void {
navigationAttempt++;
dismissConfirm(false);
}
onBeforeRouteUpdate((to, from) => {
supersedePending();
return to.path === from.path || confirmLeave();
});
onBeforeRouteLeave(() => {
supersedePending();
return confirmLeave();
});
/** Bumped by every page change: work begun on one page must not act on the next. */
let pageVisit = 0;
// Only a navigation that actually happened resets the page it left: its
// editors, a reorder draft and any confirmation still open.
watch(
() => route.path,
() => {
pageVisit++;
dismissConfirm(false);
editorOpen.value = false;
groupEditorOpen.value = false;
cancelReorder();
},
);
async function refreshOverview(): Promise<void> {
refreshKey.value++;
await Promise.all([loadGroups(), loadLogs(50, logFilterGroup.value || undefined), loadMetrics()]);
+2
View File
@@ -5,6 +5,8 @@ export interface ConfirmOptions {
description?: string;
/** Label of the destructive button (defaults to "Delete"). */
confirmText?: string;
/** What the action does, shown as the dialog icon (defaults to "delete"). */
kind?: "delete" | "leave";
}
interface ConfirmRequest extends ConfirmOptions {
+6
View File
@@ -443,6 +443,9 @@ const en: Dict = {
"confirm.disableWebhook": "Disable this group's webhook endpoint?",
"confirm.disableWebhookDetail": "The secret is deleted; senders still using it will be rejected.",
"confirm.removeForgeSource": 'Remove host "{name}"?',
"confirm.leaveUnsaved": "Leave this page?",
"confirm.leaveUnsavedDesc": "Your unsaved changes will be lost.",
"confirm.leave": "Leave",
};
const zh: Dict = {
@@ -877,6 +880,9 @@ const zh: Dict = {
"confirm.disableWebhook": "确定停用该分组的 webhook 入口吗?",
"confirm.disableWebhookDetail": "secret 将被删除,仍在使用它的发送方会被拒绝。",
"confirm.removeForgeSource": "确定删除来源主机“{name}”吗?",
"confirm.leaveUnsaved": "确定离开此页面吗?",
"confirm.leaveUnsavedDesc": "尚未保存的修改将会丢失。",
"confirm.leave": "离开",
};
const messages: Record<Locale, Dict> = { en, zh };