diff --git a/apps/web/components/shell/command-palette.tsx b/apps/web/components/shell/command-palette.tsx index 9b4be975..c69c1547 100644 --- a/apps/web/components/shell/command-palette.tsx +++ b/apps/web/components/shell/command-palette.tsx @@ -10,6 +10,7 @@ import { Kbd } from "@/components/ui/kbd"; import { AgentStatusBadge } from "@/components/ui/status-badge"; import { NAV_GROUPS } from "@/components/shell/nav"; import { useAllAgents } from "@/lib/queries"; +import { confirmNavigation } from "@/lib/navigation-guard"; import { useTheme } from "@/lib/theme"; import { cn } from "@/lib/utils"; @@ -79,7 +80,12 @@ export function CommandPaletteProvider({ children }: { children: React.ReactNode }, [open]); const commands = React.useMemo(() => { - const go = (href: string) => () => router.push(href); + // Through the unsaved-changes guard, so a dirty form asks before it is left. + const go = (href: string) => () => { + void confirmNavigation(href).then((ok) => { + if (ok) router.push(href); + }); + }; const actions: Command[] = [ { id: "act-work", group: "Actions", label: "Start work", keywords: "run execute task new", icon: Play, run: go("/work") }, { id: "act-agent", group: "Actions", label: "New agent", keywords: "create add", icon: Plus, run: go("/agents/new") }, diff --git a/apps/web/lib/navigation-guard.test.ts b/apps/web/lib/navigation-guard.test.ts new file mode 100644 index 00000000..50c6295b --- /dev/null +++ b/apps/web/lib/navigation-guard.test.ts @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { confirmNavigation, isSamePage, setNavigationGuard } from "./navigation-guard.ts"; + +const FORM = "https://orbit.test/skills/new"; + +test("without a guard navigation is allowed", async () => { + assert.equal(await confirmNavigation("/agents", FORM), true); +}); + +test("a guard decides navigation to another page", async () => { + let asked = 0; + const remove = setNavigationGuard(async () => { + asked += 1; + return false; + }); + assert.equal(await confirmNavigation("/agents", FORM), false); + assert.equal(asked, 1); + remove(); + assert.equal(await confirmNavigation("/agents", FORM), true); +}); + +test("navigation within the page never asks", async () => { + const remove = setNavigationGuard(async () => false); + assert.equal(await confirmNavigation("/skills/new#access", FORM), true); + assert.equal(await confirmNavigation("/skills/new?step=2", FORM), true); + remove(); +}); + +test("removing an old guard keeps the newer one", async () => { + const removeOld = setNavigationGuard(async () => true); + const removeNew = setNavigationGuard(async () => false); + removeOld(); + assert.equal(await confirmNavigation("/agents", FORM), false); + removeNew(); +}); + +test("isSamePage compares origin and path only", () => { + assert.equal(isSamePage("/skills/new#x", FORM), true); + assert.equal(isSamePage("/skills", FORM), false); + assert.equal(isSamePage("https://evil.test/skills/new", FORM), false); +}); diff --git a/apps/web/lib/navigation-guard.ts b/apps/web/lib/navigation-guard.ts new file mode 100644 index 00000000..01225c8c --- /dev/null +++ b/apps/web/lib/navigation-guard.ts @@ -0,0 +1,39 @@ +/** + * One place that decides whether in-app navigation may leave the current page. + * + * A form with unsaved changes registers a guard (see `use-unsaved-changes.ts`); code that + * navigates with `router.push` outside a link (the command palette) asks + * `confirmNavigation` first, so it gets the same "Leave without saving?" prompt as a link. + */ + +export type NavigationGuard = () => Promise; + +let active: NavigationGuard | null = null; + +/** Register the page's guard; the returned function removes it (and only it). */ +export function setNavigationGuard(guard: NavigationGuard): () => void { + active = guard; + return () => { + if (active === guard) active = null; + }; +} + +/** + * Resolve to true when navigation to `target` may go ahead. A target on the current page + * (a section hash, a query change) never asks: nothing on the page is lost. + */ +export async function confirmNavigation(target: string, current: string = currentHref()): Promise { + if (!active || isSamePage(target, current)) return true; + return active(); +} + +/** True when `target` stays on the page `current` shows (same origin and path). */ +export function isSamePage(target: string, current: string): boolean { + const from = new URL(current); + const to = new URL(target, from); + return to.origin === from.origin && to.pathname === from.pathname; +} + +function currentHref() { + return typeof window === "undefined" ? "http://localhost/" : window.location.href; +} diff --git a/apps/web/lib/use-unsaved-changes.ts b/apps/web/lib/use-unsaved-changes.ts index 2d319ad9..6a7aac8d 100644 --- a/apps/web/lib/use-unsaved-changes.ts +++ b/apps/web/lib/use-unsaved-changes.ts @@ -1,16 +1,22 @@ "use client"; -import { useEffect, useRef } from "react"; +import { useCallback, useEffect, useRef } from "react"; import { useRouter } from "next/navigation"; import { useConfirm } from "@/components/ui/confirm"; +import { isSamePage, setNavigationGuard } from "@/lib/navigation-guard"; /** * Protects a long form from being lost by accident. * - * While `dirty`, closing or reloading the tab asks the browser to confirm, and a click - * on a link that leaves the page asks in-app first. Saving navigates in code - * (`router.push`), which is not intercepted, so a successful save never prompts. + * While `dirty`: + * - closing or reloading the tab asks the browser to confirm; + * - a click on a link that leaves the page asks in-app first; + * - browser Back and Forward to another page ask in-app first; + * - code that navigates through `confirmNavigation` (the command palette) asks the same. + * + * Saving navigates in code (`router.push`) without `confirmNavigation`, so a successful + * save never prompts. * * Pass the form's state as `value`; it is compared with what the form started with. */ @@ -23,6 +29,18 @@ export function useUnsavedChanges(value: unknown, options: { enabled?: boolean } const dirtyRef = useRef(dirty); dirtyRef.current = dirty; + const askToLeave = useCallback(async () => { + const leave = await confirm({ + title: "Leave without saving?", + description: "Your changes on this page have not been saved and will be lost.", + confirmLabel: "Leave page", + cancelLabel: "Keep editing", + destructive: true, + }); + if (leave) dirtyRef.current = false; + return leave; + }, [confirm]); + useEffect(() => { if (!dirty) return; const onBeforeUnload = (event: BeforeUnloadEvent) => { @@ -31,8 +49,12 @@ export function useUnsavedChanges(value: unknown, options: { enabled?: boolean } event.returnValue = ""; }; window.addEventListener("beforeunload", onBeforeUnload); - return () => window.removeEventListener("beforeunload", onBeforeUnload); - }, [dirty]); + const removeGuard = setNavigationGuard(() => (dirtyRef.current ? askToLeave() : Promise.resolve(true))); + return () => { + window.removeEventListener("beforeunload", onBeforeUnload); + removeGuard(); + }; + }, [dirty, askToLeave]); useEffect(() => { const onClick = (event: MouseEvent) => { @@ -44,25 +66,45 @@ export function useUnsavedChanges(value: unknown, options: { enabled?: boolean } const url = new URL(anchor.href, window.location.href); if (url.origin !== window.location.origin) return; // Same page (a section hash, a query change): nothing is lost. - if (url.pathname === window.location.pathname) return; + if (isSamePage(url.href, window.location.href)) return; event.preventDefault(); event.stopPropagation(); - void confirm({ - title: "Leave without saving?", - description: "Your changes on this page have not been saved and will be lost.", - confirmLabel: "Leave page", - cancelLabel: "Keep editing", - destructive: true, - }).then((leave) => { - if (!leave) return; - dirtyRef.current = false; - router.push(`${url.pathname}${url.search}${url.hash}`); + void askToLeave().then((leave) => { + if (leave) router.push(`${url.pathname}${url.search}${url.hash}`); }); }; // Capture phase: before Next's own link handler starts the navigation. document.addEventListener("click", onClick, true); return () => document.removeEventListener("click", onClick, true); - }, [confirm, router]); + }, [askToLeave, router]); + + useEffect(() => { + // The entry this form lives on, to put back when the user keeps editing. Section + // hashes change on this page, so it is refreshed whenever history stays here. + let page = { href: window.location.href, state: window.history.state as unknown }; + const onPopState = (event: PopStateEvent) => { + if (isSamePage(window.location.href, page.href)) { + page = { href: window.location.href, state: event.state }; + return; + } + if (!dirtyRef.current) return; + // Back or Forward has already moved the URL. Stop Next's router from rendering the + // other page (this capture listener on window runs before its own), then ask. + event.stopImmediatePropagation(); + const target = event.state as unknown; + void askToLeave().then((leave) => { + if (leave) { + // Let the router render the page the browser moved to. + window.dispatchEvent(new PopStateEvent("popstate", { state: target })); + } else { + // Put this page back on top of history; the draft never unmounted. + window.history.pushState(page.state, "", page.href); + } + }); + }; + window.addEventListener("popstate", onPopState, true); + return () => window.removeEventListener("popstate", onPopState, true); + }, [askToLeave]); return dirty; } diff --git a/changelog.d/439.fixed.md b/changelog.d/439.fixed.md new file mode 100644 index 00000000..81861e4c --- /dev/null +++ b/changelog.d/439.fixed.md @@ -0,0 +1,3 @@ +- A form with unsaved changes now also asks "Leave without saving?" on browser Back and + Forward and when a command-palette entry leaves the page; before, only links and closing + the tab asked and the draft was lost (#439). diff --git a/docs/development/ui-test-plan.md b/docs/development/ui-test-plan.md index 53ee1117..91074821 100644 --- a/docs/development/ui-test-plan.md +++ b/docs/development/ui-test-plan.md @@ -335,6 +335,11 @@ licence messages instead. - Destructive actions (archive, delete, revoke, cancel) ask in an in-app dialog that names the object; none use the browser’s native confirm. - Deleting/archiving an agent preserves execution history by default. +- Unsaved changes (#439): on `/skills/new` and `/agent-teams/new`, type a name, then press + browser Back, press Forward after going back to the form, and pick a page in the command + palette (Ctrl/Cmd+K). Each opens "Leave without saving?"; **Keep editing** stays on the form + with the draft and the URL intact, **Leave page** goes to the chosen page. A clean form + navigates without a prompt, and saving never prompts. ## What to record