Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(settings): confirm before discarding group edits (#20527)

boojack9aafd7e5d59c
diff --git a/frontend/src/react/app/RootLayout.tsx b/frontend/src/react/app/RootLayout.tsx
index 77dd2c175c..2a7d89d78c 100644
--- a/frontend/src/react/app/RootLayout.tsx
+++ b/frontend/src/react/app/RootLayout.tsx
@@ -1,3 +1,4 @@
+import { useRef } from "react";
import type { Location } from "react-router-dom";
import { matchRoutes, Outlet, useBlocker } from "react-router-dom";
import { AuthGate } from "@/react/app/AuthGate";
@@ -31,18 +32,27 @@ function snapshotLocation(location: Location): ReactRoute {
// `next(false)`. The guards run `window.confirm` synchronously and remember a
// pending target themselves, so a blocked navigation simply stays put.
function LeaveGuardBlocker() {
- useBlocker(({ currentLocation, nextLocation }) => {
- if (
- currentLocation.pathname === nextLocation.pathname &&
- currentLocation.search === nextLocation.search
- ) {
- return false;
+ const blockerRef = useRef<ReturnType<typeof useBlocker> | null>(null);
+ const blocker = useBlocker(
+ ({ currentLocation, historyAction, nextLocation }) => {
+ if (
+ currentLocation.pathname === nextLocation.pathname &&
+ currentLocation.search === nextLocation.search
+ ) {
+ return false;
+ }
+ return runBeforeEachGuards(
+ snapshotLocation(nextLocation),
+ snapshotLocation(currentLocation),
+ {
+ historyAction,
+ reset: () => blockerRef.current?.reset?.(),
+ retry: () => blockerRef.current?.proceed?.(),
+ }
+ );
}
- return runBeforeEachGuards(
- snapshotLocation(nextLocation),
- snapshotLocation(currentLocation)
- );
- });
+ );
+ blockerRef.current = blocker;
return null;
}
diff --git a/frontend/src/react/pages/settings/GroupsPage.test.tsx b/frontend/src/react/pages/settings/GroupsPage.test.tsx
new file mode 100644
index 0000000000..b0c9ae71cf
--- /dev/null
+++ b/frontend/src/react/pages/settings/GroupsPage.test.tsx
@@ -0,0 +1,546 @@
+import type {
+ ButtonHTMLAttributes,
+ InputHTMLAttributes,
+ ReactNode,
+} from "react";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { nativeChange } from "@/react/test-utils/nativeChange";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+type CapturedBeforeEachGuard = (
+ to: { fullPath: string },
+ from: { fullPath: string },
+ next: (target?: boolean) => void,
+ options?: {
+ historyAction?: "POP" | "PUSH" | "REPLACE";
+ reset?: () => void;
+ retry?: () => void;
+ }
+) => void;
+
+const mocks = vi.hoisted(() => ({
+ beforeEachGuard: undefined as CapturedBeforeEachGuard | undefined,
+ routerPush: vi.fn(),
+ routerReplace: vi.fn(),
+}));
+
+vi.mock("@/react/components/ComponentPermissionGuard", () => ({
+ ComponentPermissionGuard: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+}));
+
+vi.mock("@/react/components/FeatureBadge", () => ({
+ FeatureBadge: ({
+ fallback,
+ }: {
+ clickable?: boolean;
+ fallback?: ReactNode;
+ feature?: unknown;
+ }) => createElement("span", {}, fallback),
+}));
+
+vi.mock("@/react/components/HighlightLabelText", () => ({
+ HighlightLabelText: ({ text }: { text: string }) =>
+ createElement("span", {}, text),
+}));
+
+vi.mock("@/react/components/UserCell", () => ({
+ UserCell: ({ user }: { user?: { email?: string } }) =>
+ createElement("span", {}, user?.email ?? ""),
+}));
+
+vi.mock("@/react/components/UserSelect", () => ({
+ UserSelect: ({
+ disabled,
+ onChange,
+ value,
+ }: {
+ disabled?: boolean;
+ onChange: (value: string) => void;
+ value: string;
+ }) =>
+ createElement("input", {
+ "data-testid": "user-select",
+ disabled,
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
+ onChange(e.target.value),
+ value,
+ }),
+}));
+
+vi.mock("@/react/components/ui/alert", () => ({
+ Alert: ({
+ children,
+ description,
+ }: {
+ children?: ReactNode;
+ description?: ReactNode;
+ }) => createElement("div", {}, description, children),
+}));
+
+vi.mock("@/react/components/ui/alert-dialog", () => ({
+ AlertDialog: ({
+ children,
+ open,
+ }: {
+ children: ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ open: boolean;
+ }) =>
+ open
+ ? createElement("div", { "data-testid": "alert-dialog" }, children)
+ : null,
+ AlertDialogContent: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ AlertDialogFooter: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ AlertDialogTitle: ({ children }: { children: ReactNode }) =>
+ createElement("h3", {}, children),
+}));
+
+vi.mock("@/react/components/ui/badge", () => ({
+ Badge: ({ children }: { children?: ReactNode }) =>
+ createElement("span", {}, children),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ disabled,
+ onClick,
+ variant: _variant,
+ size: _size,
+ }: ButtonHTMLAttributes<HTMLButtonElement> & {
+ size?: string;
+ variant?: string;
+ }) => createElement("button", { disabled, onClick }, children),
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: (props: InputHTMLAttributes<HTMLInputElement>) =>
+ createElement("input", props),
+}));
+
+vi.mock("@/react/components/ui/search-input", () => ({
+ SearchInput: (props: InputHTMLAttributes<HTMLInputElement>) =>
+ createElement("input", props),
+}));
+
+vi.mock("@/react/components/ui/select", () => ({
+ Select: ({
+ children,
+ disabled,
+ }: {
+ children: ReactNode;
+ disabled?: boolean;
+ onValueChange?: (value: string | null) => void;
+ value?: string | number;
+ }) => createElement("div", { "aria-disabled": disabled }, children),
+ SelectContent: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SelectItem: ({ children }: { children: ReactNode; value: unknown }) =>
+ createElement("div", {}, children),
+ SelectTrigger: ({ children }: { children: ReactNode }) =>
+ createElement("button", { type: "button" }, children),
+ SelectValue: ({ children }: { children?: ReactNode }) =>
+ createElement("span", {}, typeof children === "function" ? null : children),
+}));
+
+vi.mock("@/react/components/ui/sheet", () => ({
+ Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>
+ open ? createElement("div", { "data-testid": "sheet" }, children) : null,
+ SheetBody: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetContent: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetFooter: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetHeader: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetTitle: ({ children }: { children: ReactNode }) =>
+ createElement("h2", {}, children),
+}));
+
+vi.mock("@/react/components/ui/table", () => ({
+ Table: ({ children }: { children: ReactNode }) =>
+ createElement("table", {}, children),
+ TableBody: ({ children }: { children: ReactNode }) =>
+ createElement("tbody", {}, children),
+ TableCell: ({ children }: { children?: ReactNode }) =>
+ createElement("td", {}, children),
+ TableHead: ({ children }: { children?: ReactNode }) =>
+ createElement("th", {}, children),
+ TableHeader: ({ children }: { children: ReactNode }) =>
+ createElement("thead", {}, children),
+ TableRow: ({ children }: { children?: ReactNode }) =>
+ createElement("tr", {}, children),
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactNode }) =>
+ createElement("span", {}, children),
+}));
+
+vi.mock("@/react/hooks/useAppState", () => ({
+ useCurrentUser: () => ({
+ email: "[email protected]",
+ name: "users/[email protected]",
+ }),
+}));
+
+vi.mock("@/react/hooks/usePagedData", () => ({
+ PagedTableFooter: () => null,
+ usePagedData: () => ({
+ dataList: [],
+ hasMore: false,
+ isFetchingMore: false,
+ isLoading: false,
+ loadMore: vi.fn(),
+ onPageSizeChange: vi.fn(),
+ pageSize: 10,
+ pageSizeOptions: [10],
+ removeCache: vi.fn(),
+ updateCache: vi.fn(),
+ }),
+}));
+
+vi.mock("@/react/router", () => ({
+ SETTING_ROUTE_WORKSPACE_GENERAL: "workspace-general",
+ router: {
+ afterEach: () => vi.fn(),
+ beforeEach: (guard: CapturedBeforeEachGuard) => {
+ mocks.beforeEachGuard = guard;
+ return vi.fn();
+ },
+ currentRoute: { value: { query: {} } },
+ push: mocks.routerPush,
+ replace: mocks.routerReplace,
+ resolve: () => ({ href: "/settings/general" }),
+ },
+}));
+
+vi.mock("@/react/router/handles", () => ({
+ SETTING_ROUTE_WORKSPACE_GENERAL: "workspace-general",
+}));
+
+vi.mock("@/react/stores/app", () => {
+ const storeState = {
+ batchGetOrFetchUsers: vi.fn(async () => []),
+ createGroup: vi.fn(),
+ deleteGroup: vi.fn(),
+ fetchGroup: vi.fn(),
+ getOrFetchUserByIdentifier: vi.fn(),
+ getWorkspaceProfile: () => ({ domains: ["example.com"] }),
+ hasInstanceFeature: () => true,
+ isSaaSMode: () => true,
+ listGroups: vi.fn(async () => ({ groups: [], nextPageToken: "" })),
+ updateGroup: vi.fn(),
+ };
+ const useAppStore = (selector?: (state: typeof storeState) => unknown) =>
+ selector ? selector(storeState) : storeState;
+ useAppStore.getState = () => storeState;
+ return { useAppStore };
+});
+
+vi.mock("@/store", () => ({
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("@/store/modules/v1/common", () => ({
+ extractUserEmail: (name: string) => name.replace(/^users\//, ""),
+ groupNamePrefix: "groups/",
+}));
+
+vi.mock("@/types", () => ({
+ UNKNOWN_USER_NAME: "users/unknown",
+}));
+
+vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({
+ PlanFeature: {
+ FEATURE_DIRECTORY_SYNC: 1,
+ FEATURE_USER_GROUPS: 2,
+ },
+}));
+
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: () => true,
+ isValidEmail: (email: string) => email.includes("@"),
+}));
+
+vi.mock("./shared/AADSyncSheet", () => ({
+ AADSyncSheet: () => null,
+}));
+
+vi.mock("@bufbuild/protobuf", () => ({
+ create: (_schema: unknown, init?: Record<string, unknown>) => ({ ...init }),
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { GroupsPage } from "./GroupsPage";
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.beforeEachGuard = undefined;
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ document.body.removeChild(container);
+});
+
+async function renderPage(): Promise<void> {
+ await act(async () => {
+ root.render(createElement(GroupsPage));
+ await Promise.resolve();
+ });
+}
+
+describe("GroupsPage create group sheet", () => {
+ it("asks for explicit confirmation before closing with unsaved changes", async () => {
+ await renderPage();
+
+ const createButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.create"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ createButton.click();
+ });
+
+ const titleInput = container.querySelector(
+ "input[maxlength='200']"
+ ) as HTMLInputElement;
+ await act(async () => {
+ nativeChange(titleInput, "Developers");
+ await Promise.resolve();
+ });
+
+ const cancelButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.cancel"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ cancelButton.click();
+ });
+
+ expect(container.querySelector("[data-testid='sheet']")).not.toBeNull();
+ expect(
+ container.querySelector("[data-testid='alert-dialog']")
+ ).not.toBeNull();
+ expect(container.textContent).toContain("common.leave-without-saving");
+
+ const discardButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.discard-changes"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ discardButton.click();
+ });
+
+ expect(container.querySelector("[data-testid='sheet']")).toBeNull();
+ });
+
+ it("closes without a discard dialog after creating a modified group", async () => {
+ await renderPage();
+
+ const createButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.create"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ createButton.click();
+ });
+
+ const sheet = container.querySelector(
+ "[data-testid='sheet']"
+ ) as HTMLDivElement;
+ const emailInput = sheet.querySelector(
+ "input:not([data-testid='user-select']):not([maxlength])"
+ ) as HTMLInputElement;
+ const titleInput = sheet.querySelector(
+ "input[maxlength='200']"
+ ) as HTMLInputElement;
+ await act(async () => {
+ nativeChange(emailInput, "developers");
+ nativeChange(titleInput, "Developers");
+ await Promise.resolve();
+ });
+
+ const submitButton = [...container.querySelectorAll("button")]
+ .filter((button) => button.textContent === "common.create")
+ .at(-1) as HTMLButtonElement;
+ await act(async () => {
+ submitButton.click();
+ await Promise.resolve();
+ });
+
+ expect(container.querySelector("[data-testid='alert-dialog']")).toBeNull();
+ expect(container.querySelector("[data-testid='sheet']")).toBeNull();
+ });
+
+ it("replays blocked push navigation as push after discarding changes", async () => {
+ await renderPage();
+
+ const createButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.create"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ createButton.click();
+ });
+
+ const titleInput = container.querySelector(
+ "input[maxlength='200']"
+ ) as HTMLInputElement;
+ await act(async () => {
+ nativeChange(titleInput, "Developers");
+ await Promise.resolve();
+ });
+
+ let blocked = false;
+ await act(async () => {
+ mocks.beforeEachGuard?.(
+ { fullPath: "/settings/users" },
+ { fullPath: "/settings/groups" },
+ (target?: boolean) => {
+ blocked = target === false;
+ },
+ { historyAction: "PUSH" }
+ );
+ await Promise.resolve();
+ });
+
+ expect(blocked).toBe(true);
+ expect(
+ container.querySelector("[data-testid='alert-dialog']")
+ ).not.toBeNull();
+
+ const discardButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.discard-changes"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ discardButton.click();
+ await Promise.resolve();
+ });
+
+ expect(mocks.routerPush).toHaveBeenCalledWith("/settings/users");
+ expect(mocks.routerReplace).not.toHaveBeenCalled();
+ });
+
+ it("resets blocked route navigation after canceling the discard dialog", async () => {
+ await renderPage();
+
+ const createButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.create"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ createButton.click();
+ });
+
+ const titleInput = container.querySelector(
+ "input[maxlength='200']"
+ ) as HTMLInputElement;
+ await act(async () => {
+ nativeChange(titleInput, "Developers");
+ await Promise.resolve();
+ });
+
+ const reset = vi.fn();
+ let blocked = false;
+ await act(async () => {
+ mocks.beforeEachGuard?.(
+ { fullPath: "/settings/users" },
+ { fullPath: "/settings/groups" },
+ (target?: boolean) => {
+ blocked = target === false;
+ },
+ { historyAction: "PUSH", reset }
+ );
+ await Promise.resolve();
+ });
+
+ expect(blocked).toBe(true);
+ expect(
+ container.querySelector("[data-testid='alert-dialog']")
+ ).not.toBeNull();
+
+ const alertDialog = container.querySelector(
+ "[data-testid='alert-dialog']"
+ ) as HTMLDivElement;
+ const cancelButton = [...alertDialog.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.cancel"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ cancelButton.click();
+ await Promise.resolve();
+ });
+
+ expect(reset).toHaveBeenCalledTimes(1);
+ expect(container.querySelector("[data-testid='sheet']")).not.toBeNull();
+ expect(container.querySelector("[data-testid='alert-dialog']")).toBeNull();
+ expect(mocks.routerPush).not.toHaveBeenCalled();
+ expect(mocks.routerReplace).not.toHaveBeenCalled();
+ });
+
+ it("retries blocked pop navigation after discarding changes", async () => {
+ await renderPage();
+
+ const createButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.create"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ createButton.click();
+ });
+
+ const titleInput = container.querySelector(
+ "input[maxlength='200']"
+ ) as HTMLInputElement;
+ await act(async () => {
+ nativeChange(titleInput, "Developers");
+ await Promise.resolve();
+ });
+
+ const retry = vi.fn();
+ let blocked = false;
+ await act(async () => {
+ mocks.beforeEachGuard?.(
+ { fullPath: "/settings/users" },
+ { fullPath: "/settings/groups" },
+ (target?: boolean) => {
+ blocked = target === false;
+ },
+ { historyAction: "POP", retry }
+ );
+ await Promise.resolve();
+ });
+
+ expect(blocked).toBe(true);
+ expect(
+ container.querySelector("[data-testid='alert-dialog']")
+ ).not.toBeNull();
+
+ const discardButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.discard-changes"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ discardButton.click();
+ await Promise.resolve();
+ });
+
+ expect(retry).toHaveBeenCalledTimes(1);
+ expect(mocks.routerPush).not.toHaveBeenCalled();
+ expect(mocks.routerReplace).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/react/pages/settings/GroupsPage.tsx b/frontend/src/react/pages/settings/GroupsPage.tsx
index 0f14ba54f3..cff516fed3 100644
--- a/frontend/src/react/pages/settings/GroupsPage.tsx
+++ b/frontend/src/react/pages/settings/GroupsPage.tsx
@@ -16,6 +16,12 @@ import { HighlightLabelText } from "@/react/components/HighlightLabelText";
import { UserCell } from "@/react/components/UserCell";
import { UserSelect } from "@/react/components/UserSelect";
import { Alert } from "@/react/components/ui/alert";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogFooter,
+ AlertDialogTitle,
+} from "@/react/components/ui/alert-dialog";
import { Badge } from "@/react/components/ui/badge";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
@@ -47,6 +53,7 @@ import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { cn } from "@/react/lib/utils";
+import type { NavigationHistoryAction } from "@/react/router";
import { router } from "@/react/router";
import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
@@ -445,8 +452,21 @@ interface CreateGroupSheetProps {
onRemoved: (group: Group) => void;
}
+type PendingLeaveTarget = {
+ fullPath: string;
+ historyAction: NavigationHistoryAction;
+ reset?: () => void;
+ retry?: () => void;
+};
+
function CreateGroupSheet(props: CreateGroupSheetProps) {
const { open, group, onClose } = props;
+ const { t } = useTranslation();
+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+ const [pendingLeaveConfirm, setPendingLeaveConfirm] = useState(false);
+ const [pendingLeaveTarget, setPendingLeaveTarget] =
+ useState<PendingLeaveTarget | null>(null);
+ const bypassLeaveGuardRef = useRef(false);
// Freeze the entity while open=false so the inner form stays visually
// stable during the Sheet's close animation.
const openEntityRef = useRef(group);
@@ -454,27 +474,148 @@ function CreateGroupSheet(props: CreateGroupSheetProps) {
openEntityRef.current = group;
}
const stableGroup = openEntityRef.current;
+
+ const clearPendingLeave = useCallback(() => {
+ setPendingLeaveConfirm(false);
+ setPendingLeaveTarget(null);
+ }, []);
+
+ const stayOnCurrentPage = useCallback(() => {
+ const target = pendingLeaveTarget;
+ clearPendingLeave();
+ target?.reset?.();
+ }, [clearPendingLeave, pendingLeaveTarget]);
+
+ const closeWithoutConfirm = useCallback(() => {
+ setHasUnsavedChanges(false);
+ clearPendingLeave();
+ onClose();
+ }, [clearPendingLeave, onClose]);
+
+ const requestClose = useCallback(() => {
+ if (hasUnsavedChanges) {
+ setPendingLeaveConfirm(true);
+ return;
+ }
+ closeWithoutConfirm();
+ }, [closeWithoutConfirm, hasUnsavedChanges]);
+
+ const discardChanges = useCallback(() => {
+ const target = pendingLeaveTarget;
+ closeWithoutConfirm();
+ if (target) {
+ if (target.historyAction === "POP" && target.retry) {
+ target.retry();
+ return;
+ }
+ bypassLeaveGuardRef.current = true;
+ const navigate =
+ target.historyAction === "REPLACE" ? router.replace : router.push;
+ void navigate(target.fullPath);
+ }
+ }, [closeWithoutConfirm, pendingLeaveTarget]);
+
+ useEffect(() => {
+ if (!open) {
+ setHasUnsavedChanges(false);
+ clearPendingLeave();
+ }
+ }, [clearPendingLeave, open]);
+
+ useEffect(() => {
+ if (!open || !hasUnsavedChanges) return;
+
+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {
+ e.preventDefault();
+ e.returnValue = "";
+ };
+ window.addEventListener("beforeunload", handleBeforeUnload);
+
+ const removeGuard = router.beforeEach((to, _from, next, options) => {
+ if (bypassLeaveGuardRef.current) {
+ bypassLeaveGuardRef.current = false;
+ next();
+ return;
+ }
+ setPendingLeaveTarget({
+ fullPath: to.fullPath,
+ historyAction: options?.historyAction ?? "PUSH",
+ reset: options?.reset,
+ retry: options?.retry,
+ });
+ setPendingLeaveConfirm(true);
+ next(false);
+ });
+
+ return () => {
+ window.removeEventListener("beforeunload", handleBeforeUnload);
+ removeGuard();
+ };
+ }, [hasUnsavedChanges, open]);
+
return (
- <Sheet open={open} onOpenChange={(next) => !next && onClose()}>
- <SheetContent width="standard">
- <GroupForm
- key={stableGroup?.name ?? "new"}
- group={stableGroup}
- onClose={props.onClose}
- onUpdated={props.onUpdated}
- onRemoved={props.onRemoved}
- />
- </SheetContent>
- </Sheet>
+ <>
+ <Sheet open={open} onOpenChange={(next) => !next && requestClose()}>
+ <SheetContent width="standard">
+ <GroupForm
+ key={stableGroup?.name ?? "new"}
+ group={stableGroup}
+ onClose={requestClose}
+ onCloseWithoutConfirm={closeWithoutConfirm}
+ onDirtyChange={setHasUnsavedChanges}
+ onUpdated={props.onUpdated}
+ onRemoved={props.onRemoved}
+ />
+ </SheetContent>
+ </Sheet>
+ <AlertDialog
+ open={pendingLeaveConfirm}
+ onOpenChange={(
+ nextOpen: boolean,
+ eventDetails?: { reason?: string; cancel?: () => void }
+ ) => {
+ if (
+ !nextOpen &&
+ (eventDetails?.reason === "escape-key" ||
+ eventDetails?.reason === "outside-press")
+ ) {
+ eventDetails.cancel?.();
+ return;
+ }
+ if (!nextOpen) {
+ stayOnCurrentPage();
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>
+ {t("common.leave-without-saving")}
+ </AlertDialogTitle>
+ <AlertDialogFooter>
+ <Button variant="outline" onClick={stayOnCurrentPage}>
+ {t("common.cancel")}
+ </Button>
+ <Button variant="destructive" onClick={discardChanges}>
+ {t("common.discard-changes")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
);
}
function GroupForm({
group,
onClose,
+ onCloseWithoutConfirm,
+ onDirtyChange,
onUpdated,
onRemoved,
-}: Omit<CreateGroupSheetProps, "open">) {
+}: Omit<CreateGroupSheetProps, "open"> & {
+ onCloseWithoutConfirm: () => void;
+ onDirtyChange: (dirty: boolean) => void;
+}) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
const isSaaSMode = useAppStore((s) => s.isSaaSMode());
@@ -575,6 +716,33 @@ function GroupForm({
return false;
}, [isEditMode, group, title, description, members]);
+ const hasUnsavedChanges = useMemo(() => {
+ if (isEditMode) return hasChanged;
+ if (email !== initialEmail) return true;
+ if (selectedDomain !== initialSelectedDomain) return true;
+ if (title !== initialTitle) return true;
+ if (description !== initialDescription) return true;
+ if (!isEqual(members, initialMembers)) return true;
+ return false;
+ }, [
+ description,
+ email,
+ hasChanged,
+ initialDescription,
+ initialEmail,
+ initialMembers,
+ initialSelectedDomain,
+ initialTitle,
+ isEditMode,
+ members,
+ selectedDomain,
+ title,
+ ]);
+
+ useEffect(() => {
+ onDirtyChange(hasUnsavedChanges);
+ }, [hasUnsavedChanges, onDirtyChange]);
+
const allowConfirm = !errorMessage && hasChanged;
const handleAddMember = () => {
@@ -671,7 +839,7 @@ function GroupForm({
title: t("common.created"),
});
}
- onClose();
+ onCloseWithoutConfirm();
} catch {
// error shown by store
} finally {
@@ -690,7 +858,7 @@ function GroupForm({
style: "SUCCESS",
title: t("common.deleted"),
});
- onClose();
+ onCloseWithoutConfirm();
} catch {
// error shown by store
} finally {
diff --git a/frontend/src/react/router/index.ts b/frontend/src/react/router/index.ts
index d6da390a34..bddf0ee3d1 100644
--- a/frontend/src/react/router/index.ts
+++ b/frontend/src/react/router/index.ts
@@ -253,10 +253,17 @@ export function isSqlEditorRouteName(name: string | undefined): boolean {
// vue-router `next()` callback: no-arg / `RouteTarget` proceeds, `false`
// cancels.
type GuardNext = (target?: boolean | RouteTarget) => void;
+export type NavigationHistoryAction = "POP" | "PUSH" | "REPLACE";
+export type BeforeEachGuardOptions = {
+ historyAction?: NavigationHistoryAction;
+ reset?: () => void;
+ retry?: () => void;
+};
type BeforeEachGuard = (
to: ReactRoute,
from: ReactRoute,
- next: GuardNext
+ next: GuardNext,
+ options?: BeforeEachGuardOptions
) => void;
const beforeEachGuards = new Set<BeforeEachGuard>();
@@ -266,12 +273,21 @@ const beforeEachGuards = new Set<BeforeEachGuard>();
// root consults this from a single `useBlocker`, reproducing vue-router's
// global guard semantics. Guards that redirect (`next(target)`) are treated as
// "proceed" here — the existing leave guards only ever proceed or cancel.
-export function runBeforeEachGuards(to: ReactRoute, from: ReactRoute): boolean {
+export function runBeforeEachGuards(
+ to: ReactRoute,
+ from: ReactRoute,
+ options?: BeforeEachGuardOptions
+): boolean {
for (const guard of beforeEachGuards) {
let blocked = false;
- guard(to, from, (target) => {
- if (target === false) blocked = true;
- });
+ guard(
+ to,
+ from,
+ (target) => {
+ if (target === false) blocked = true;
+ },
+ options
+ );
if (blocked) return true;
}
return false;