feat(admin-console): improve route and filter management (#10)

* fix(nuxt): pre-bundle the CommonJS deps of the markdown stack

`debug` and `extend` are imported by micromark and unified through
@elysola/ui. Served unbundled by the dev server they have no default
export, so the console page failed with a 500 in `nuxt dev`.

* docs(deployment): list the fragments and feishu link migrations

The manual `d1 execute` fallback stopped at 0008, and AGENTS.md named
0001..0010 although 0011 already exists.

* feat(storage): persist the per-group route order

Routes used to load in id order, so the order saved from the console
was lost on the next read. Migration 0012 adds `d1_routes.position`:
saving writes each route's index within its own group (saving one group
never shifts another), and routes load by `group_id, position, id`.

A database without the column keeps working: only a "no such column" /
"has no column named" error falls back to the legacy statements, and
nothing is cached, so a later migration is picked up on the next call.

* feat(console): add in-app destructive-action confirmation

Deleting a route or a group used `window.confirm`, which blocks the page
and ignores the console theme. A promise-based `useConfirm()` now drives
one <ConfirmDialog /> built on the reka-ui AlertDialog that
@elysola/ui ships; reka-ui is pre-bundled so dev keeps a single copy and
the dialog stacks with the Rc dialogs.

A request never outlives its asker: one made after the asking component
unmounted resolves false, and one still open when it unmounts is
cancelled.

* feat(console): confirm member and webhook removal

Removing a member, revoking an invite link and disabling a group's
webhook endpoint took effect on the first click. They now ask first;
disabling the webhook explains that senders still using the secret will
be rejected, and its button is styled as destructive.

* feat(console): confirm removing filled editor rows

Filter conditions and groups, delivery targets, saved fragments and forge
hosts vanished on a single click, taking whatever had been typed with
them. Rows holding content now ask first, while empty, never-filled
rows (`isBlankNode`: default operator, no path, no values, not negated)
are still removed directly.

* fix(i18n): remove duplicate button glyphs

"New Route", "New Group" and the group cards' "Open" link render a Plus
or ArrowRight icon next to their label, so the "+" and "→" baked into
the strings appeared twice.

* style(console): redesign route cards for narrow screens

The card was one flex row whose badges, filter chips, targets and five
hand-drawn icon buttons squeezed the route name on small screens. It is
now a grid driven by a container query: name and actions share the top
line, the filter summary (clamped to two lines) and targets follow, and
the tags wrap below; from 40rem the tags move up beside the title.

Targets of the same platform collapse into one tag with a count, long
ids truncate instead of widening the page, and the actions use lucide
icons with accessible labels.

* feat(console): reorder a group's routes by drag or keyboard

The per-card up/down arrows saved after every single step, so moving a
route five places took five writes. A Reorder mode on the group page now
swaps each card's switch for a drag handle: pointer drags (mouse and
touch) slide the neighbours out of the way and auto-scroll near the
viewport edges, Arrow Up/Down on a focused handle moves a card by one
and is announced to screen readers, and nothing is written until Save
order. Cancel or Escape (unless a dialog or list owns it) drops the
draft.

The cards move into a new RouteList component that owns the drag state.

* style(members): align member cards and invite actions

* style(group-editor): size forge and log target controls

Keep source hosts, platform selectors and remove actions aligned without stretching short controls across the dialog. Wrap component roots explicitly so their internal markup cannot break the grid.

* style(route-editor): group options and delivery target fields

Give each target labeled fields and a compact platform header, widen the filter workspace, and align fragment controls. Scroll failed validation into view when the footer is far from the affected section.

* feat(filters): add bilingual suggestions and value validation

Catalog forge events, actions, payload paths and known values with searchable English and Chinese descriptions. Match-value validation mirrors the server and only rejects inputs that cannot match.

* feat(filters): add searchable creatable value inputs

Build a theme-aligned combobox on the shared reka-ui primitives. Rank stored keys before bilingual descriptions, allow validated custom values, and preserve unconfirmed multi-value drafts instead of silently committing them.

* feat(filter-editor): integrate searchable condition inputs

Replace chip-only values with context-aware bilingual inputs and a compact condition grid. Preserve drafts across tree changes, block saves and tests until drafts are resolved, and keep keyword filters free of hidden operators.

* feat(filters): split pasted values without breaking regexes

Accept multiple values separated by commas or lines while retaining commas inside wrapped expressions and raw regex patterns. Pasting replaces the selected range and keeps rejected values as an explicit draft.

* fix(filters): adapt suggestions to the selected operator

Offer literal prefixes and suffixes for substring operators, escaped anchored patterns for regex, and numeric suggestions only for comparisons. Suggestion syntax must mean what the selected matcher actually reads.

* fix(filters): preserve regex meaning when changing operators

Swap wrapped and raw regex sources only when both compile identically after saving. Leave literal, glob, multiline and Unicode-sensitive comparisons unchanged rather than inventing non-equivalent conversions.

* a11y(filter-editor): label type and operator controls

Associate each fixed select with a stable per-condition label while keeping the compact visual layout unchanged.

* fix(editors): ignore accidental backdrop dismissal

Do not discard unsaved route or group edits when the user clicks outside the dialog. Preserve Escape, Cancel and explicit close, including popovers and confirmation dialogs stacked above the editor.

* feat(dispatch)!: scope stop and fallback to each group

A match in one group must not suppress delivery in another group. Track regular matches and stopped scopes independently, and document the routing-table boundary.

BREAKING CHANGE: stop and fallback no longer apply globally across
groups. Put mutually exclusive routes in the same group and define
fallback routes in each group that needs its own catch-all.

* fix(dispatch): honor stop on a matching fallback route

Once a fallback matches with stop enabled, skip later routes of the same group without affecting other groups. Cover multiple fallback routes in the group-isolation regression test.

* style(console): pin theme and language controls to the right

Separate utility controls from page actions so narrow screens retain a readable title column and right-aligned actions below. Wrap long headings without letting them push controls out of view.

* style(groups): place creation beside the aligned group count

Keep the new-group action inside the group list at every width and align the label and count on one baseline with a consistent type scale.

* style(groups): align card footers and keep role badges intact

Give long names two lines, show the current role in its own non-wrapping row, and anchor every card footer to the grid-row bottom regardless of optional source metadata.

* style(logs): prevent filter labels and metadata overflow

Keep filter labels on one line and allow long channel, thread and repository identifiers to wrap instead of widening the page.

* style(console): scale the sidebar and hide mobile tab tracks

Narrow the sidebar proportionally while retaining enough room for both locales. Keep mobile navigation swipeable without a visible horizontal scrollbar.

* feat(console): give each group its own routes URL

Resolve the selected group from /admin/groups/{groupId}, validate console paths, and use browser history for back navigation. Keep Groups active and let an active mobile-tab tap return to the list. Scope pending route loads to their group and retain the count beside long headings.

* 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.

* feat(console): confirm sign-out from desktop and mobile

Expose sign-out in the mobile topbar when the sidebar is hidden. Both entry points use the in-app confirmation before navigating to the server logout endpoint.

* fix(console): keep topbar tools clear of very narrow headings

Below 360px, place the full-width heading beneath the breadcrumb and utility row so the three top-right buttons cannot overlap it.

* feat(console): prioritize group titles over actions

Place New Route after Reorder in the group bar. Measure available space and remove the reorder label first, then the creation label, before truncating the group title; remeasure on resize, locale and font changes.

* fix(editors): focus the dialog without selecting its name field

Cancel the non-bubbling FocusScope mount event in the capture phase and focus the dialog itself. Keep keyboard navigation working without highlighting the name or opening the touch keyboard automatically.

* perf(console): preserve one instance across admin navigation

Use a fixed page key instead of remounting the whole console for each URL. Refresh each view when shown and isolate overview metrics and logs so page filters cannot leak into the dashboard.

* fix(console-data): discard superseded load responses

Only the latest request may update a list, its error or loading state. Invalidate pending group loads after a save so an older response cannot restore stale configuration during persistent-console navigation.

* fix(routes): serialize writes and reject unloaded route lists

Whole-list saves must start from loaded data and wait for other route writes. Lock switches and actions during saves, recheck deletion after confirmation, and rebuild saved ordering from the newest route objects.

* fix(editors): scope async results and fragment writes to sessions

A completed save or dry run must not close or overwrite a newer editor. Keep fragment state scoped by group, reject writes until the real list is ready, and retain in-flight fragment locks across navigation.

* fix(groups): serialize edits and isolate group detail panels

Prevent overlapping whole-list writes, avoid duplicate ids after rename, and discard delete confirmations prepared on a page that has since been left. Key member and webhook panels by group so local state cannot cross tenants.

* fix(console): omit the empty action row outside overview

Render the refresh-action container only where it has content so narrow layouts do not reserve a blank row after creation controls move into their page bars.

* perf(metrics): send all seven queries in one D1 batch

Avoid seven sequential network round trips and read totals, breakdowns and recent failures in one consistent transaction. Reuse the failed-send statement and row mapping while retaining group scoping.

* fix(admin-api): bypass browser cache locks for live requests

Use no-store on both client requests and admin responses. Personalized live data must not be reused, and one stalled same-URL cache entry must not block later log requests behind the browser cache lock.

* docs(routes): Clarify fallback hints and document group-scoped stop and fallback upgrade behavior
This commit is contained in:
翅膀喵 authored and GitHub committed 2026-10-17 21:13:20 +08:00
1 parent 29b15f4933
commit dbf162bf74
55 files changed
+5778 -985

No files matched your search

+4
View File
@@ -15,6 +15,10 @@ export function useAuthState() {
export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(path, {
credentials: "same-origin",
// Live data, never from the browser cache. This also keeps requests out of
// its per-URL cache lock: otherwise one request that never answers makes
// every later request for the same URL wait up to 20 s behind it.
cache: "no-store",
...init,
// JSON in/out: h3's readBody only parses JSON bodies when the request
// declares application/json, and the browser defaults string bodies to
+8 -3
View File
@@ -5,8 +5,12 @@ export function useAuditApi() {
const entries = ref<AuditEntry[]>([]);
const loading = ref(false);
const error = ref("");
// Bumped by every load, so only the latest request may land (an older one,
// e.g. from the page the user just left, must not overwrite newer data).
let request = 0;
async function load(limit = 50, groupId?: string): Promise<void> {
const mine = ++request;
loading.value = true;
error.value = "";
needLogin.value = false;
@@ -14,11 +18,12 @@ export function useAuditApi() {
let url = `/admin/api/audit?limit=${limit}`;
if (groupId) url += `&groupId=${encodeURIComponent(groupId)}`;
const data = await apiFetch<{ audit?: AuditEntry[] }>(url);
entries.value = data.audit ?? [];
if (mine === request) entries.value = data.audit ?? [];
} catch (err) {
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
if (mine === request && !needLogin.value)
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
if (mine === request) loading.value = false;
}
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Keeps an editor dialog open when the user clicks outside it, so a stray click
* on the backdrop never throws away unsaved input. RcDialog exposes no hook for
* reka's `interactOutside`, so this watches pointer-downs while the dialog is
* open: a press outside the dialog (and outside any popover or dialog stacked
* above it) marks the close request it triggers as one to ignore. Escape, the
* close button and Cancel keep closing the dialog.
*/
export function useBackdropGuard(isOpen: () => boolean, dialogSelector: string) {
let pressedOutside = false;
function onPointerDown(event: PointerEvent): void {
const target = event.target as Element | null;
pressedOutside = !target?.closest?.(
`${dialogSelector}, [data-dismissable-layer], [data-reka-popper-content-wrapper]`,
);
}
function onKeyDown(): void {
pressedOutside = false;
}
function listen(on: boolean): void {
if (typeof document === "undefined") return;
if (on) {
document.addEventListener("pointerdown", onPointerDown, true);
document.addEventListener("keydown", onKeyDown, true);
return;
}
document.removeEventListener("pointerdown", onPointerDown, true);
document.removeEventListener("keydown", onKeyDown, true);
pressedOutside = false;
}
watch(isOpen, listen, { immediate: true });
onBeforeUnmount(() => listen(false));
/** Whether the pending close request came from a press outside the dialog. */
function isBackdropClose(): boolean {
const outside = pressedOutside;
pressedOutside = false;
return outside;
}
return { isBackdropClose };
}
+65
View File
@@ -0,0 +1,65 @@
export interface ConfirmOptions {
/** The question, shown as the dialog title. */
title: string;
/** Optional consequence text under the title. */
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" | "signOut";
}
interface ConfirmRequest extends ConfirmOptions {
resolve: (confirmed: boolean) => void;
}
/**
* Promise-based destructive-action confirmation shared by the whole console.
* <ConfirmDialog /> (mounted once by ConsolePage) renders the pending request;
* `confirm()` resolves true on confirm and false on cancel / Escape.
*/
export function useConfirm() {
const pending = useState<ConfirmRequest | null>("wh-confirm", () => null);
const hosts = useState<number>("wh-confirm-hosts", () => 0);
// The component that asks; a request it makes after unmounting is refused,
// and one still on screen when it unmounts is cancelled.
const owner = getCurrentInstance();
let asked: ConfirmRequest | null = null;
if (owner) {
onBeforeUnmount(() => {
// Only our own request: another component's newer one stays open.
if (asked && toRaw(pending.value) === asked) settle(false);
asked = null;
});
}
function confirm(options: ConfirmOptions): Promise<boolean> {
// Nobody can answer, or the asker is gone (the console was left while the
// request was being prepared): never resume a stale destructive action.
if (!hosts.value || owner?.isUnmounted) return Promise.resolve(false);
// A newer request supersedes (and cancels) one still on screen.
pending.value?.resolve(false);
return new Promise((resolve) => {
asked = { ...options, resolve };
pending.value = asked;
});
}
function settle(confirmed: boolean): void {
const request = pending.value;
if (!request) return;
pending.value = null;
request.resolve(confirmed);
}
/** Register the dialog that renders requests; the returned detach cancels any pending one. */
function attachHost(): () => void {
hosts.value++;
return () => {
hosts.value--;
settle(false);
};
}
return { pending, confirm, settle, attachHost };
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Opens an editor dialog without jumping into its first field. reka-ui's
* FocusScope focuses and *selects* the first input on open, which highlights
* the name as if about to overwrite it and pops up the keyboard on touch
* screens. Its mount auto-focus is announced with a non-bubbling, cancelable
* event — RcDialog exposes no `openAutoFocus` hook — so it is caught here in
* the capture phase and focus goes to the dialog itself instead: Escape and
* Tab keep working, the fields stay untouched until the user picks one.
*/
export function useDialogFocus(isOpen: () => boolean, dialogSelector: string) {
function onMountAutoFocus(event: Event): void {
const dialog = event.target;
if (!(dialog instanceof HTMLElement) || !dialog.matches(dialogSelector)) return;
event.preventDefault();
dialog.focus({ preventScroll: true });
}
function listen(on: boolean): void {
if (typeof document === "undefined") return;
if (on) document.addEventListener("focusScope.autoFocusOnMount", onMountAutoFocus, true);
else document.removeEventListener("focusScope.autoFocusOnMount", onMountAutoFocus, true);
}
watch(isOpen, listen, { immediate: true });
onBeforeUnmount(() => listen(false));
}
+79 -4
View File
@@ -1,11 +1,22 @@
import { toRaw } from "vue";
import type { ComputedRef, InjectionKey } from "vue";
import type { Filter, FilterNode, FilterOp, FilterType } from "~/types";
/** Exact event names the edited route filters on (see `scopeEvents`). */
export const FILTER_SCOPE_EVENTS: InjectionKey<ComputedRef<string[]>> = Symbol("filter-scope");
export interface LeafForm {
type: FilterType;
path: string;
op: FilterOp;
values: string[];
exclude: boolean;
/**
* Text typed into the values input but not added yet (editor-only, never
* saved). It lives on the leaf so it follows the condition when the input
* remounts (a NOT unwrapped, the root wrapped by an inserted fragment).
*/
draft: string;
}
export type NodeKind = "leaf" | "all" | "any" | "not";
@@ -17,8 +28,22 @@ export interface NodeForm {
child: NodeForm | null;
}
const nodeKeys = new WeakMap<object, number>();
let lastNodeKey = 0;
/** Stable render key of a node form (list indexes shift when siblings are removed). */
export function nodeKey(nf: NodeForm): number {
const raw = toRaw(nf);
let key = nodeKeys.get(raw);
if (key === undefined) {
key = ++lastNodeKey;
nodeKeys.set(raw, key);
}
return key;
}
export function blankLeafForm(): LeafForm {
return { type: "event", path: "", op: "eq", values: [], exclude: false };
return { type: "event", path: "", op: "eq", values: [], exclude: false, draft: "" };
}
export function blankNode(kind: NodeKind): NodeForm {
@@ -42,6 +67,7 @@ function leafToForm(f: Filter): LeafForm {
op: f.op ?? "eq",
values: matchToValues(f.match),
exclude: !!f.exclude,
draft: "",
};
}
@@ -60,12 +86,14 @@ export function nodeToForm(node: FilterNode): NodeForm {
export function formToLeaf(lf: LeafForm): Filter | null {
const values = lf.values.map((v) => v.trim()).filter((v) => v.length > 0);
if (lf.op !== "exists" && values.length === 0) return null;
// Keyword filters ignore the operator on the server, so never store one.
const op: FilterOp = lf.type === "keyword" ? "eq" : lf.op;
if (op !== "exists" && values.length === 0) return null;
if (lf.type === "field" && lf.path.trim().length === 0) return null;
const filter: Filter = { type: lf.type };
if (lf.type === "field") filter.path = lf.path.trim();
if (lf.op !== "eq") filter.op = lf.op;
if (lf.op !== "exists") filter.match = values.length === 1 ? values[0] : values;
if (op !== "eq") filter.op = op;
if (op !== "exists") filter.match = values.length === 1 ? values[0] : values;
if (lf.exclude) filter.exclude = true;
return filter;
}
@@ -116,6 +144,53 @@ export function nodeFormToRouteFilters(nf: NodeForm): { filters: Filter[]; ast?:
return { filters: [], ast: ast ?? undefined };
}
/**
* Exact event names a route positively filters on (negated conditions,
* `not` groups, globs and regexes are skipped) — the context the filter
* editor uses to rank action and field suggestions.
*/
export function scopeEvents(nf: NodeForm): string[] {
const out = new Set<string>();
const walk = (n: NodeForm): void => {
if (n.kind === "leaf") {
const { type, op, exclude, values } = n.leaf;
if (type !== "event" || exclude || (op !== "eq" && op !== "in")) return;
for (const v of values) {
const value = v.trim();
if (/^[a-z0-9_]+$/i.test(value)) out.add(value.toLowerCase());
}
return;
}
if (n.kind === "all" || n.kind === "any") n.children.forEach(walk);
};
walk(nf);
return [...out];
}
/**
* Whether a node holds nothing worth confirming before it is removed: an
* untouched condition (default operator, no path, no values, not negated) or
* groups made only of those. A changed operator counts as content, since
* e.g. `exists` is a complete condition without values.
*/
export function isBlankNode(nf: NodeForm): boolean {
if (nf.kind === "leaf") {
const { draft, exclude, op, path, values } = nf.leaf;
return (
!exclude && op === "eq" && !path.trim() && values.every((v) => !v.trim()) && !draft.trim()
);
}
if (nf.kind === "all" || nf.kind === "any") return nf.children.every(isBlankNode);
return !nf.child || isBlankNode(nf.child);
}
/** Whether a condition of the tree still holds typed text that was not added. */
export function hasPendingDraft(nf: NodeForm): boolean {
if (nf.kind === "leaf") return !!nf.leaf.draft.trim();
if (nf.kind === "all" || nf.kind === "any") return nf.children.some(hasPendingDraft);
return !!nf.child && hasPendingDraft(nf.child);
}
export function collectEvents(node: FilterNode): string[] {
const out: string[] = [];
const walk = (n: FilterNode): void => {
+48 -7
View File
@@ -4,9 +4,37 @@ export function useFragmentsApi() {
const { needLogin } = useAuthState();
const fragments = ref<NamedFragment[]>([]);
const loading = ref(false);
const saving = ref(false);
const error = ref("");
/** Group whose fragments are shown; responses for any other group are dropped. */
const shownGroupId = ref<string | null>(null);
/** Group whose fragments were last loaded (or saved) successfully. */
const loadedGroupId = ref<string | null>(null);
// Bumped by every load/save, so only the latest request may land.
let request = 0;
/**
* Whether a write may start for `groupId`: the shown list is that group's
* real fragments and nothing is loading or saving. Saving replaces a group's
* whole fragment list, so each write must build on the previous one.
*/
function readyFor(groupId: string): boolean {
return (
shownGroupId.value === groupId &&
loadedGroupId.value === groupId &&
!error.value &&
!loading.value &&
!saving.value
);
}
async function load(groupId: string): Promise<void> {
const mine = ++request;
if (shownGroupId.value !== groupId) {
fragments.value = [];
loadedGroupId.value = null;
}
shownGroupId.value = groupId;
loading.value = true;
error.value = "";
needLogin.value = false;
@@ -14,21 +42,34 @@ export function useFragmentsApi() {
const data = await apiFetch<{ fragments?: NamedFragment[] }>(
`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`,
);
if (mine !== request) return;
fragments.value = data.fragments ?? [];
loadedGroupId.value = groupId;
} catch (err) {
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
if (mine === request && !needLogin.value)
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
if (mine === request) loading.value = false;
}
}
async function save(groupId: string, next: NamedFragment[]): Promise<void> {
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`, {
method: "PUT",
body: JSON.stringify({ fragments: next }),
});
saving.value = true;
try {
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`, {
method: "PUT",
body: JSON.stringify({ fragments: next }),
});
} finally {
saving.value = false;
}
if (shownGroupId.value !== groupId) return;
request++;
loading.value = false;
error.value = "";
fragments.value = next;
loadedGroupId.value = groupId;
}
return { fragments, loading, needLogin, error, load, save };
return { fragments, loading, needLogin, error, readyFor, load, save };
}
+47 -7
View File
@@ -5,30 +5,70 @@ export function useGroupRoutesApi() {
const routes = ref<Route[]>([]);
const loading = ref(false);
const error = ref("");
/** Group whose routes are shown; responses for any other group are dropped. */
const groupId = ref<string | null>(null);
/** Group whose routes were last loaded (or saved) successfully. */
const loadedId = ref<string | null>(null);
// Bumped by every load/clear, so only the latest request may land.
let request = 0;
async function load(groupId: string): Promise<void> {
/**
* The shown routes are the group's real routes. Saving replaces a group's
* whole route list, so a write is only safe from here — never from the
* empty list of a load still running or one that failed.
*/
const ready = computed(() => !!groupId.value && loadedId.value === groupId.value && !error.value);
async function load(id: string): Promise<void> {
const mine = ++request;
if (groupId.value !== id) {
routes.value = [];
loadedId.value = null;
}
groupId.value = id;
loading.value = true;
error.value = "";
needLogin.value = false;
try {
const data = await apiFetch<{ routes?: Route[] }>(
`/admin/api/groups/${encodeURIComponent(groupId)}/routes`,
`/admin/api/groups/${encodeURIComponent(id)}/routes`,
);
if (mine !== request) return;
routes.value = data.routes ?? [];
loadedId.value = id;
} catch (err) {
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
if (mine === request && !needLogin.value)
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
if (mine === request) loading.value = false;
}
}
async function save(groupId: string, next: Route[]): Promise<void> {
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/routes`, {
/** Forget the shown group (its page was left); late responses are ignored. */
function clear(): void {
request++;
groupId.value = null;
loadedId.value = null;
routes.value = [];
loading.value = false;
error.value = "";
}
async function save(id: string, next: Route[]): Promise<void> {
await apiFetch(`/admin/api/groups/${encodeURIComponent(id)}/routes`, {
method: "PUT",
body: JSON.stringify({ routes: next }),
});
// The page may have moved on to another group while the request ran.
if (groupId.value !== id) return;
// What was just written is the newest state: a load of this group that
// started earlier may return the old routes, so it must not land.
request++;
loading.value = false;
error.value = "";
routes.value = next;
loadedId.value = id;
}
return { routes, loading, needLogin, error, load, save };
return { routes, loading, needLogin, error, groupId, ready, load, clear, save };
}
+14 -2
View File
@@ -8,6 +8,11 @@ export function useGroupsApi() {
const roles = ref<Record<string, GroupRole>>({});
const loading = ref(false);
const error = ref("");
/** A load has succeeded: an id missing from `groups` really is unknown. */
const loaded = ref(false);
// Bumped by every load and save, so only the latest request may land: a
// load that started before a save must not bring back the old groups.
let request = 0;
function roleOf(groupId: string): GroupRole | undefined {
return isSuper.value ? "owner" : roles.value[groupId];
@@ -24,6 +29,7 @@ export function useGroupsApi() {
}
async function load(): Promise<void> {
const mine = ++request;
loading.value = true;
error.value = "";
needLogin.value = false;
@@ -33,13 +39,16 @@ export function useGroupsApi() {
isSuper?: boolean;
roles?: Record<string, GroupRole>;
}>("/admin/api/groups");
if (mine !== request) return;
groups.value = data.groups ?? [];
isSuper.value = data.isSuper ?? false;
roles.value = data.roles ?? {};
loaded.value = true;
} catch (err) {
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
if (mine === request && !needLogin.value)
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
if (mine === request) loading.value = false;
}
}
@@ -48,6 +57,8 @@ export function useGroupsApi() {
method: "PUT",
body: JSON.stringify({ groups: next }),
});
request++;
loading.value = false;
groups.value = next;
}
@@ -67,6 +78,7 @@ export function useGroupsApi() {
canEditGroup,
canEditRoutes,
loading,
loaded,
needLogin,
error,
load,
+124 -14
View File
@@ -6,8 +6,8 @@ type Dict = Record<string, string>;
const en: Dict = {
"app.tagline": "CONFIG CONSOLE",
"app.newRoute": "+ New Route",
"app.newGroup": "+ New Group",
"app.newRoute": "New Route",
"app.newGroup": "New Group",
"app.signOut": "Sign out",
"app.langToggle": "中文",
"login.title": "Config Console",
@@ -84,7 +84,6 @@ const en: Dict = {
"role.owner": "Owner",
"role.admin": "Admin",
"role.viewer": "Viewer",
"role.badge": "You: {role}",
"roles.owner": "Owner",
"roles.admin": "Admin",
"roles.viewer": "Viewer",
@@ -136,12 +135,24 @@ const en: Dict = {
"groups.admins": "ADMINS",
"groups.owners": "OWNERS",
"groups.members": "MEMBERS",
"groups.myRole": "MY ROLE",
"groups.any": "any",
"groups.open": "Open →",
"group.back": "Groups",
"groups.open": "Open",
"groups.delete": "Delete group",
"group.notFound": "This group does not exist, or you have no access to it",
"group.allGroups": "All groups",
"group.routeCount": "{count} routes",
"group.routesIn": "Routes in {name}",
"routes.emptyGroup": "No routes in this group yet.",
"routes.createFirst": "Create your first route",
"routes.reorder": "Reorder",
"routes.reorderHint": "Drag routes by their handle to change the evaluation order, then save.",
"routes.reorderKeyboardHint": "Press Arrow Up or Arrow Down to move this route.",
"routes.reorderSave": "Save order",
"routes.reorderCancel": "Cancel",
"routes.dragHandle": "Reorder {name}",
"routes.moved": "{name} moved to position {n}",
"routes.delete": "Delete route",
"route.untitled": "(untitled)",
"route.noFilters": "no filters",
"route.channel": "CHANNEL",
@@ -211,9 +222,11 @@ const en: Dict = {
"routeEditor.idHint": "Unique, use a-z / 0-9 / dashes",
"routeEditor.enabled": "Route enabled",
"routeEditor.fallback": "Fallback route",
"routeEditor.fallbackHint": "Only fires when no other route matched; filters still apply",
"routeEditor.fallbackHint":
"Only fires when no regular (non-fallback) route in this group matched; its filters still apply",
"routeEditor.stop": "Stop on match",
"routeEditor.stopHint": "When matched, no further routes are evaluated for this event",
"routeEditor.stopHint":
"When matched, later routes in this group are not evaluated for this event",
"routeEditor.filters": "Filters",
"routeEditor.filtersNote": "(all must match · AND)",
"routeEditor.matchPlaceholder": "match value (* ? wildcards, /regex/)",
@@ -253,7 +266,16 @@ const en: Dict = {
"routeEditor.addGroup": "Add group",
"routeEditor.addNot": "Add not",
"routeEditor.remove": "Remove",
"routeEditor.removeCondition": "Delete condition",
"routeEditor.removeGroup": "Delete condition group",
"routeEditor.removeTarget": "Remove target",
"routeEditor.path": "Field path",
"routeEditor.values": "Values",
"routeEditor.notHint": "Negate this condition",
"routeEditor.errDraft": "Add (press Enter) or clear the filter value still being typed",
"routeEditor.errInvalidValue": 'Invalid value "{value}": {reason}',
"routeEditor.op": "Operator",
"routeEditor.filterType": "Filter type",
"routeEditor.pathPlaceholder": "payload.path",
"routeEditor.valuesPlaceholder": "Type a value and press Enter",
"routeEditor.testMatch": "Test match",
@@ -263,6 +285,7 @@ const en: Dict = {
"routeEditor.testMatched": "Matches",
"routeEditor.testNotMatched": "Does not match",
"routeEditor.testInvalidJson": "Invalid JSON",
"routeEditor.testEventInvalid": "Fix or clear the event type first",
"routeEditor.fragments": "Fragments",
"routeEditor.fragmentsPresets": "Presets",
"routeEditor.fragmentsEmpty": "No fragments yet",
@@ -271,9 +294,23 @@ const en: Dict = {
"routeEditor.fragmentsSave": "Save as fragment",
"routeEditor.fragmentsNamePlaceholder": "Fragment name",
"routeEditor.fragmentsNameRequired": "Fragment name is required",
"routeEditor.fragmentsNotReady": "The group's fragments are still loading; try again in a moment",
"routeEditor.errPath": "Field filters need a path",
"routeEditor.errValues": "Add at least one value",
"routeEditor.errGroupEmpty": "Group needs at least one condition",
"combo.empty": "No matches",
"combo.typeToAdd": "Type a value to add it",
"combo.useValue": "Use “{value}”",
"combo.remove": "Remove {value}",
"combo.pending": 'Not added yet: press Enter to add "{value}"',
"valid.tooLong": "Patterns longer than 200 characters never match",
"valid.regex": "Invalid regular expression",
"valid.number": "Comparison operators need a number",
"valid.event": "Event names use letters, digits and _ (or * ? wildcards, /regex/)",
"valid.eventName": "Event names use letters, digits and _",
"valid.branch": "Branch names cannot contain spaces or ~ ^ : \\ [",
"valid.branchLiteral":
"This operator compares text as-is: branch names never contain * ? [ ~ ^ : \\ or spaces",
"fragmentPreset.prBot": "PR by a bot",
"fragmentPreset.dependabot": "Dependabot PR",
"fragmentPreset.releasePublished": "Release published",
@@ -329,6 +366,7 @@ const en: Dict = {
"groupEditor.forgeSourcesHost": "git.example.com",
"groupEditor.forgeSourcesName": "Optional display name",
"groupEditor.forgeSourcesAdd": "+ Add host",
"groupEditor.forgeSourcesRemove": "Remove host",
"groupEditor.forgeSourcesHint":
"Events whose repository host matches an entry are labeled in the message footer with its display name (or the host when none is set) — e.g. git1.example.com and git2.example.com for two Gitea instances. GitHub events match github.com.",
"groupEditor.errForgeSourceHost": "Every forge host must be a valid hostname",
@@ -384,6 +422,8 @@ const en: Dict = {
"audit.allGroups": "All groups",
"audit.refresh": "⟳ Refresh",
"toast.routesSaved": "Routes saved",
"toast.groupsBusy": "Another group change is still saving; try again in a moment",
"toast.routesNotReady": "The routes are still loading or saving; try again in a moment",
"toast.routeDeleted": "Route deleted",
"toast.groupSaved": "Groups saved",
"toast.groupDeleted": "Group deleted",
@@ -391,15 +431,31 @@ const en: Dict = {
"toast.groupIdExists": "Group ID already exists",
"toast.saveFailed": "Save failed: {msg}",
"toast.deleteFailed": "Delete failed: {msg}",
"toast.orderSaved": "Route order saved",
"confirm.deleteRoute": 'Delete route "{name}"?',
"confirm.deleteGroup": 'Delete group "{name}"?',
"confirm.deleteGroupWarn": " {n} route(s) reference it and will lose their group.",
"confirm.cancel": "Cancel",
"confirm.delete": "Delete",
"confirm.removeCondition": "Delete this condition?",
"confirm.removeFilterGroup": "Delete this condition group and everything in it?",
"confirm.removeTarget": "Remove target {n}?",
"confirm.deleteFragment": 'Delete fragment "{name}"?',
"confirm.removeMember": 'Remove member "{name}"?',
"confirm.revokeInvite": "Revoke this invite link?",
"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",
"confirm.signOut": "Sign out of the console?",
};
const zh: Dict = {
"app.tagline": "配置控制台",
"app.newRoute": "+ 新建路由",
"app.newGroup": "+ 新建分组",
"app.newRoute": "新建路由",
"app.newGroup": "新建分组",
"app.signOut": "退出登录",
"app.langToggle": "EN",
"login.title": "配置控制台",
@@ -476,7 +532,6 @@ const zh: Dict = {
"role.owner": "拥有者",
"role.admin": "管理员",
"role.viewer": "只读",
"role.badge": "我的角色:{role}",
"roles.owner": "拥有者",
"roles.admin": "管理员",
"roles.viewer": "只读",
@@ -526,12 +581,24 @@ const zh: Dict = {
"groups.admins": "管理员",
"groups.owners": "来源",
"groups.members": "成员",
"groups.myRole": "我的角色",
"groups.any": "任意",
"groups.open": "进入 →",
"group.back": "返回分组",
"groups.open": "进入",
"groups.delete": "删除分组",
"group.notFound": "分组不存在,或你没有访问权限",
"group.allGroups": "全部分组",
"group.routeCount": "{count} 条路由",
"group.routesIn": "{name} 的路由",
"routes.emptyGroup": "该分组还没有路由。",
"routes.createFirst": "创建第一个路由",
"routes.reorder": "调整顺序",
"routes.reorderHint": "拖动手柄调整路由的评估顺序,完成后保存。",
"routes.reorderKeyboardHint": "按上下方向键移动该路由。",
"routes.reorderSave": "保存顺序",
"routes.reorderCancel": "取消",
"routes.dragHandle": "调整“{name}”的顺序",
"routes.moved": "“{name}”已移到第 {n} 位",
"routes.delete": "删除路由",
"route.untitled": "(未命名)",
"route.noFilters": "无过滤器",
"route.channel": "频道",
@@ -601,9 +668,10 @@ const zh: Dict = {
"routeEditor.idHint": "唯一,使用 a-z / 0-9 / 短横线",
"routeEditor.enabled": "启用路由",
"routeEditor.fallback": "兜底路由",
"routeEditor.fallbackHint": "仅当没有其它路由匹配该事件时才发送,其过滤器仍会生效",
"routeEditor.fallbackHint":
"仅当本分组没有普通(非兜底)路由匹配该事件时才发送,其过滤器仍会生效",
"routeEditor.stop": "匹配后停止",
"routeEditor.stopHint": "该路由匹配后,不再评估后续路由",
"routeEditor.stopHint": "该路由匹配后,不再评估本分组的后续路由",
"routeEditor.filters": "过滤器",
"routeEditor.filtersNote": "(全部匹配 · AND)",
"routeEditor.matchPlaceholder": "匹配值(支持 * ? 通配符、/正则/)",
@@ -642,7 +710,16 @@ const zh: Dict = {
"routeEditor.addGroup": "添加分组",
"routeEditor.addNot": "添加非",
"routeEditor.remove": "删除",
"routeEditor.removeCondition": "删除条件",
"routeEditor.removeGroup": "删除条件组",
"routeEditor.removeTarget": "删除目标",
"routeEditor.path": "字段路径",
"routeEditor.values": "匹配值",
"routeEditor.notHint": "对该条件取反",
"routeEditor.errDraft": "请先确认(回车)或清除尚未添加的过滤值",
"routeEditor.errInvalidValue": "无效的值“{value}”:{reason}",
"routeEditor.op": "操作符",
"routeEditor.filterType": "过滤类型",
"routeEditor.pathPlaceholder": "payload.path",
"routeEditor.valuesPlaceholder": "输入值后回车",
"routeEditor.testMatch": "测试匹配",
@@ -652,6 +729,7 @@ const zh: Dict = {
"routeEditor.testMatched": "匹配",
"routeEditor.testNotMatched": "不匹配",
"routeEditor.testInvalidJson": "无效的 JSON",
"routeEditor.testEventInvalid": "请先修正或清空事件类型",
"routeEditor.fragments": "过滤器片段",
"routeEditor.fragmentsPresets": "预设",
"routeEditor.fragmentsEmpty": "暂无片段",
@@ -660,9 +738,22 @@ const zh: Dict = {
"routeEditor.fragmentsSave": "存为片段",
"routeEditor.fragmentsNamePlaceholder": "片段名称",
"routeEditor.fragmentsNameRequired": "请填写片段名称",
"routeEditor.fragmentsNotReady": "分组的片段仍在加载,请稍后再试",
"routeEditor.errPath": "字段过滤需要路径",
"routeEditor.errValues": "至少需要一个值",
"routeEditor.errGroupEmpty": "分组至少需要一个条件",
"combo.empty": "无匹配项",
"combo.typeToAdd": "输入内容后即可添加",
"combo.useValue": "使用“{value}”",
"combo.remove": "移除 {value}",
"combo.pending": "尚未添加:按回车添加“{value}”",
"valid.tooLong": "超过 200 个字符的模式永远不会匹配",
"valid.regex": "无效的正则表达式",
"valid.number": "比较运算需要数字",
"valid.event": "事件名只能包含字母、数字和 _(也可用 * ? 通配符或 /正则/)",
"valid.eventName": "事件名只能包含字母、数字和 _",
"valid.branch": "分支名不能包含空格或 ~ ^ : \\ [",
"valid.branchLiteral": "该运算符按字面比较:分支名不会包含 * ? [ ~ ^ : \\ 或空格",
"fragmentPreset.prBot": "机器人提交的 PR",
"fragmentPreset.dependabot": "Dependabot PR",
"fragmentPreset.releasePublished": "发布 Release",
@@ -717,6 +808,7 @@ const zh: Dict = {
"groupEditor.forgeSourcesHost": "git.example.com",
"groupEditor.forgeSourcesName": "可选显示名称",
"groupEditor.forgeSourcesAdd": "+ 添加主机",
"groupEditor.forgeSourcesRemove": "删除主机",
"groupEditor.forgeSourcesHint":
"仓库主机与条目匹配的事件,会在消息底部用该条目的显示名称标注(未填名称则用主机名)——例如两个 Gitea 实例可分别填 git1.example.com 和 git2.example.com。GitHub 事件匹配 github.com。",
"groupEditor.errForgeSourceHost": "每个来源主机必须是有效的主机名",
@@ -772,6 +864,8 @@ const zh: Dict = {
"audit.allGroups": "全部分组",
"audit.refresh": "⟳ 刷新",
"toast.routesSaved": "路由已保存",
"toast.groupsBusy": "另一项分组修改仍在保存,请稍后再试",
"toast.routesNotReady": "路由仍在加载或保存中,请稍后再试",
"toast.routeDeleted": "路由已删除",
"toast.groupSaved": "分组已保存",
"toast.groupDeleted": "分组已删除",
@@ -779,9 +873,25 @@ const zh: Dict = {
"toast.groupIdExists": "分组 ID 已存在",
"toast.saveFailed": "保存失败:{msg}",
"toast.deleteFailed": "删除失败:{msg}",
"toast.orderSaved": "路由顺序已保存",
"confirm.deleteRoute": "确定删除路由“{name}”吗?",
"confirm.deleteGroup": "确定删除分组“{name}”吗?",
"confirm.deleteGroupWarn": " 有 {n} 条路由引用它,将失去所属分组。",
"confirm.cancel": "取消",
"confirm.delete": "删除",
"confirm.removeCondition": "确定删除该条件吗?",
"confirm.removeFilterGroup": "确定删除该条件组及其中的全部条件吗?",
"confirm.removeTarget": "确定删除第 {n} 个目标吗?",
"confirm.deleteFragment": "确定删除片段“{name}”吗?",
"confirm.removeMember": "确定移除成员“{name}”吗?",
"confirm.revokeInvite": "确定撤销该邀请链接吗?",
"confirm.disableWebhook": "确定停用该分组的 webhook 入口吗?",
"confirm.disableWebhookDetail": "secret 将被删除,仍在使用它的发送方会被拒绝。",
"confirm.removeForgeSource": "确定删除来源主机“{name}”吗?",
"confirm.leaveUnsaved": "确定离开此页面吗?",
"confirm.leaveUnsavedDesc": "尚未保存的修改将会丢失。",
"confirm.leave": "离开",
"confirm.signOut": "确定退出登录吗?",
};
const messages: Record<Locale, Dict> = { en, zh };
+8 -3
View File
@@ -5,8 +5,12 @@ export function useSendLogs() {
const logs = ref<SendRecord[]>([]);
const loading = ref(false);
const error = ref("");
// Bumped by every load, so only the latest request may land (an older one,
// e.g. from the page the user just left, must not overwrite newer data).
let request = 0;
async function load(limit = 50, groupId?: string): Promise<void> {
const mine = ++request;
loading.value = true;
error.value = "";
needLogin.value = false;
@@ -14,11 +18,12 @@ export function useSendLogs() {
let url = `/admin/api/logs?limit=${limit}`;
if (groupId) url += `&groupId=${encodeURIComponent(groupId)}`;
const data = await apiFetch<{ logs?: SendRecord[] }>(url);
logs.value = data.logs ?? [];
if (mine === request) logs.value = data.logs ?? [];
} catch (err) {
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
if (mine === request && !needLogin.value)
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
if (mine === request) loading.value = false;
}
}
+8 -3
View File
@@ -5,19 +5,24 @@ export function useMetrics() {
const metrics = ref<DeliveryMetrics | null>(null);
const loading = ref(false);
const error = ref("");
// Bumped by every load, so only the latest request may land: Overview
// (all groups) and Stats (maybe one group) share this state.
let request = 0;
async function load(groupId?: string): Promise<void> {
const mine = ++request;
loading.value = true;
error.value = "";
needLogin.value = false;
try {
const qs = groupId ? `?groupId=${encodeURIComponent(groupId)}` : "";
const data = await apiFetch<{ metrics?: DeliveryMetrics }>(`/admin/api/metrics${qs}`);
metrics.value = data.metrics ?? null;
if (mine === request) metrics.value = data.metrics ?? null;
} catch (err) {
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
if (mine === request && !needLogin.value)
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
if (mine === request) loading.value = false;
}
}