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

+1 -1
View File
@@ -18,7 +18,7 @@ Core pipeline: GitHub Webhook → Worker (verify + filter + format) → Discord
- Per-group webhook ingress: optional `POST /webhook/{groupId}` with a per-group secret in KV (`tenant:{groupId}`) — Gitea/classic-GitHub/custom webhooks are verified against the group's secret instead of the operator's global ones; only that group's routes fire. The legacy `POST /webhook` (global secrets, all routes) stays untouched
- GitHub App tenant isolation: `Group.installationId` binds a group to one GitHub App installation; events whose `payload.installation.id` differs are rejected at dispatch (hard isolation on top of the optional `owners` list). The App's Setup URL points at `GET /auth/github/install`, which renders a choice page (create `inst-{installationId}` or bind to a group the signed-in user owns, verified by role); `POST /auth/github/install/bind` performs the provisioning. `installation.created` webhook events auto-provision as a fallback (create `inst-{installationId}` or bind existing groups whose `owners` match the installing account)
- GitHub OAuth: octokit (token is stored hashed for reverse lookup)
- Admin WebUI: `/admin` config console, OAuth-session protected via `ADMIN_USER_IDS` whitelist (local-only `DEBUG_MODE=true` bypasses authentication); left sidebar navigation (Overview / Groups / Send Logs / Audit / Stats) + topbar, deep-linkable routes (`/admin` overview · `/admin/groups` · `/admin/groups/{groupId}` a group's routes, members and webhook · `/admin/logs` · `/admin/audit` · `/admin/metrics`, parsed by `app/utils/admin-path.ts`; the admin page's `validate` 404s any other path); every page is a history entry, so the browser's back button returns from a group to the list (no in-page back button); the overview dashboard (`AdminHome.vue`) aggregates delivery KPIs, a routes table and recent send logs; the stats page (`MetricsPanel.vue`) renders KPI cards plus per-platform/per-event ok/failed bar legends and a per-status breakdown, and filters by group (`?groupId=`); the route/group editors (`RouteEditor.vue` / `GroupEditor.vue`) are centered, scrollable `RcDialog` forms with an eyebrow header and sectioned bodies
- Admin WebUI: `/admin` config console, OAuth-session protected via `ADMIN_USER_IDS` whitelist (local-only `DEBUG_MODE=true` bypasses authentication); left sidebar navigation (Overview / Groups / Send Logs / Audit / Stats) + topbar, deep-linkable routes (`/admin` overview · `/admin/groups` · `/admin/groups/{groupId}` a group's routes, members and webhook · `/admin/logs` · `/admin/audit` · `/admin/metrics`, parsed by `app/utils/admin-path.ts`; the admin page's `validate` 404s any other path); every page is a history entry, so the browser's back button returns from a group to the list (no in-page back button) and leaving with an open editor or an unsaved route order asks first; the overview dashboard (`AdminHome.vue`) aggregates delivery KPIs, a routes table and recent send logs; the stats page (`MetricsPanel.vue`) renders KPI cards plus per-platform/per-event ok/failed bar legends and a per-status breakdown, and filters by group (`?groupId=`); the route/group editors (`RouteEditor.vue` / `GroupEditor.vue`) are centered, scrollable `RcDialog` forms with an eyebrow header and sectioned bodies
- Access control: every group has role-based members (`owner` / `admin` / `viewer`); super admins bypass; legacy `adminIds` are read as owners (backward compatible); owners manage members + invites; `owners` field stays super-only
- Invites: single-use 7-day links (`invite:{token}`) for joining a group as admin/viewer; `ALLOW_SELF_SIGNUP=1` gives access-less users a personal group on first login (self-service SaaS entry)
- Audit log: every admin operation (logins, group/route/member/invite changes) recorded in D1 `audit_logs`; pruned by the scheduled trigger after `AUDIT_RETENTION_DAYS` (default 90)
+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 };
+1 -1
View File
@@ -63,7 +63,7 @@ WebHooker ships with a built-in config console at `/admin` for managing routes,
For local debugging only, set `DEBUG_MODE=true` to bypass GitHub OAuth and grant complete console access. Do not set this variable in a deployed environment.
The console is served as an SPA at `/admin`; its tabs are deep-linkable via the URL path (`/admin/groups`, `/admin/logs`, `/admin/audit`), and each group's routes page has its own URL (`/admin/groups/{groupId}`). Pages are browser history entries: use the browser's (or device's) back button to return from a group to the group list. Unknown console paths return the console's 404 page. URLs outside `/admin` that do not match an endpoint return a plain `404` instead of the console.
The console is served as an SPA at `/admin`; its tabs are deep-linkable via the URL path (`/admin/groups`, `/admin/logs`, `/admin/audit`), and each group's routes page has its own URL (`/admin/groups/{groupId}`). Pages are browser history entries: use the browser's (or device's) back button to return from a group to the group list; leaving a page with an open editor or an unsaved route order asks for confirmation first. Unknown console paths return the console's 404 page. URLs outside `/admin` that do not match an endpoint return a plain `404` instead of the console.
Destructive actions — deleting routes, groups, filter conditions, fragments, targets or forge hosts, removing members, revoking invites, disabling a group's webhook — ask for confirmation in an in-app dialog (empty, never-filled rows are removed directly). The route and group editors ignore clicks on the backdrop so unsaved input is never lost; close them with Cancel, ✕ or <kbd>Esc</kbd>.
+1 -1
View File
@@ -62,7 +62,7 @@ WebHooker 在 `/admin` 提供内置配置控制台,可在浏览器中管理路
仅供本地调试:设置 `DEBUG_MODE=true` 可跳过 GitHub OAuth,并授予完整控制台权限。部署环境切勿设置此变量。
控制台以 SPA 形式在 `/admin` 提供;其标签页可通过 URL 路径直达(`/admin/groups`、`/admin/logs`、`/admin/audit`),每个分组的路由页也有独立 URL(`/admin/groups/{groupId}`)。各页面都会记入浏览器历史:从分组返回分组列表请使用浏览器(或设备)自带的返回。未知的控制台路径显示控制台的 404 页面。`/admin` 之外未匹配到端点的 URL 直接返回 `404`,而不会展示控制台。
控制台以 SPA 形式在 `/admin` 提供;其标签页可通过 URL 路径直达(`/admin/groups`、`/admin/logs`、`/admin/audit`),每个分组的路由页也有独立 URL(`/admin/groups/{groupId}`)。各页面都会记入浏览器历史:从分组返回分组列表请使用浏览器(或设备)自带的返回;若页面上有打开的编辑器或未保存的路由顺序,离开前会先确认。未知的控制台路径显示控制台的 404 页面。`/admin` 之外未匹配到端点的 URL 直接返回 `404`,而不会展示控制台。
删除类操作——删除路由、分组、过滤条件、片段、目标或来源主机,移除成员,撤销邀请,停用分组 webhook——都会先弹出应用内确认框(从未填写过的空行直接删除)。路由与分组编辑弹窗点击遮罩不会关闭,避免丢失未保存的内容;请用「取消」、✕ 或 <kbd>Esc</kbd> 关闭。