Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

fix(nav): quick-nav entries that did nothing (#8074)

Reece Brownee9128dab1d36
diff --git a/frontend/editor/src/core/hooks/useSuperSearch.ts b/frontend/editor/src/core/hooks/useSuperSearch.ts
index dcbfadc966..02957e3fc3 100644
--- a/frontend/editor/src/core/hooks/useSuperSearch.ts
+++ b/frontend/editor/src/core/hooks/useSuperSearch.ts
@@ -9,7 +9,7 @@ import {
} from "react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
-import { useLocation, useNavigate } from "react-router-dom";
+import { useNavigate } from "react-router-dom";
import { useAuth } from "@app/auth/UseSession";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
@@ -23,7 +23,6 @@ import { FileDocIcon } from "@app/components/shared/FileDocIcon";
import { getFileDocVariant } from "@app/components/shared/filePreview/getFileTypeIcon";
import { detectFileExtension } from "@app/utils/fileUtils";
import { openExternalUrl } from "@app/utils/safeNavigation";
-import { EDITOR_BASENAME } from "@app/routes/editorBasename";
import {
rankByFuzzy,
idToWords,
@@ -508,19 +507,6 @@ export function useSuperSearch(
const trimmed = query.trim();
const { stubs, loadingFiles } = useMyFilesStubs(active);
const { scopeEnabled } = useSearchScopeFilter(options);
- const { pathname } = useLocation();
-
- // Workbench-bound selections must leave the file manager through the router.
- // Tool/file selection pins its URL via raw history.pushState, which the
- // router never observes — so on /files the route keeps re-asserting the
- // "myFiles" workbench and the selection appears to do nothing. Exit to the
- // editor's home path: on processor-shipping builds "/" is a role router,
- // not the editor.
- const leaveFileManager = useCallback(() => {
- if (pathname.startsWith("/files")) {
- navigate(EDITOR_BASENAME);
- }
- }, [pathname, navigate]);
// --- Actions -----------------------------------------------------------
const openFile = useCallback(
@@ -529,14 +515,14 @@ export function useSuperSearch(
// The file already lives in storage — load it as a stub so its id and
// metadata are preserved (addFiles would persist a duplicate record).
await fileActions.addStirlingFileStubs([stub], { selectFiles: true });
+ // Leaving the library is the view changing; HomePage takes the path with it.
navActions.setWorkbench("viewer");
viewerRef.current?.setActiveFileId?.(stub.id);
- leaveFileManager();
} catch (err) {
console.error("[SuperSearch] Failed to open file:", stub.name, err);
}
},
- [fileActions, navActions, leaveFileManager],
+ [fileActions, navActions],
);
const openTool = useCallback(
@@ -560,15 +546,8 @@ export function useSuperSearch(
} else {
handleToolSelectForced(id);
}
- leaveFileManager();
},
- [
- handleToolSelect,
- handleToolSelectForced,
- toolAvailability,
- toolRegistry,
- leaveFileManager,
- ],
+ [handleToolSelect, handleToolSelectForced, toolAvailability, toolRegistry],
);
const openSettings = useCallback(
diff --git a/frontend/editor/src/core/hooks/useUrlSync.test.tsx b/frontend/editor/src/core/hooks/useUrlSync.test.tsx
index e35c7dbd44..456c75b266 100644
--- a/frontend/editor/src/core/hooks/useUrlSync.test.tsx
+++ b/frontend/editor/src/core/hooks/useUrlSync.test.tsx
@@ -1,17 +1,18 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderHook } from "@testing-library/react";
-import { useRef } from "react";
+import { useRef, type ReactNode } from "react";
+import { MemoryRouter } from "react-router-dom";
import type { ToolId } from "@app/types/toolId";
const h = vi.hoisted(() => ({
- updateToolRoute: vi.fn(),
- clearToolRoute: vi.fn(),
+ toolRoute: vi.fn(() => "/compress"),
+ editorHomeRoute: vi.fn(() => null),
}));
vi.mock("@app/utils/urlRouting", () => ({
parseToolRoute: () => ({ workbench: "fileEditor", toolId: null }),
- updateToolRoute: h.updateToolRoute,
- clearToolRoute: h.clearToolRoute,
+ toolRoute: h.toolRoute,
+ editorHomeRoute: h.editorHomeRoute,
}));
vi.mock("@app/utils/scarfTracking", () => ({ firePixel: vi.fn() }));
vi.mock("@app/contexts/AppConfigContext", () => ({
@@ -25,6 +26,11 @@ const registry = {
compress: { name: "Compress", workbench: "fileEditor" },
} as never;
+/** The hook navigates through the router, so it needs one to render under. */
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter>{children}</MemoryRouter>
+);
+
/** Drives the hook the way ToolWorkflowContext does, with a startup marker. */
function useHarness(selectedTool: ToolId | null, startupTool: ToolId | null) {
const ref = useRef<ToolId | null>(startupTool);
@@ -33,17 +39,17 @@ function useHarness(selectedTool: ToolId | null, startupTool: ToolId | null) {
}
describe("useNavigationUrlSync — startup-view selections", () => {
- beforeEach(() => h.updateToolRoute.mockClear());
+ beforeEach(() => h.toolRoute.mockClear());
// The default-startup-view preference selects a tool to change the *view*.
// Writing it to the address turned every visit to /editor into /read.
it("never writes the URL for the startup-applied tool", () => {
const { rerender } = renderHook(
({ tool }: { tool: ToolId | null }) => useHarness(tool, "read" as ToolId),
- { initialProps: { tool: null as ToolId | null } },
+ { initialProps: { tool: null as ToolId | null }, wrapper },
);
rerender({ tool: "read" as ToolId });
- expect(h.updateToolRoute).not.toHaveBeenCalled();
+ expect(h.toolRoute).not.toHaveBeenCalled();
});
// The effect re-runs whenever the registry identity changes, so a marker that
@@ -51,30 +57,38 @@ describe("useNavigationUrlSync — startup-view selections", () => {
it("survives a re-run for the same tool", () => {
const { rerender } = renderHook(
({ tool }: { tool: ToolId | null }) => useHarness(tool, "read" as ToolId),
- { initialProps: { tool: null as ToolId | null } },
+ { initialProps: { tool: null as ToolId | null }, wrapper },
);
rerender({ tool: "read" as ToolId });
rerender({ tool: "read" as ToolId });
rerender({ tool: "read" as ToolId });
- expect(h.updateToolRoute).not.toHaveBeenCalled();
+ expect(h.toolRoute).not.toHaveBeenCalled();
});
it("still writes the URL when the user picks a different tool", () => {
const { rerender } = renderHook(
({ tool }: { tool: ToolId | null }) => useHarness(tool, "read" as ToolId),
- { initialProps: { tool: null as ToolId | null } },
+ { initialProps: { tool: null as ToolId | null }, wrapper },
);
rerender({ tool: "read" as ToolId });
rerender({ tool: "compress" as ToolId });
- expect(h.updateToolRoute).toHaveBeenCalledWith("compress", registry, false);
+ expect(h.toolRoute).toHaveBeenCalledWith(
+ "compress",
+ registry,
+ expect.anything(),
+ );
});
it("writes the URL for a tool chosen without a startup marker", () => {
const { rerender } = renderHook(
({ tool }: { tool: ToolId | null }) => useHarness(tool, null),
- { initialProps: { tool: null as ToolId | null } },
+ { initialProps: { tool: null as ToolId | null }, wrapper },
);
rerender({ tool: "read" as ToolId });
- expect(h.updateToolRoute).toHaveBeenCalledWith("read", registry, false);
+ expect(h.toolRoute).toHaveBeenCalledWith(
+ "read",
+ registry,
+ expect.anything(),
+ );
});
});
diff --git a/frontend/editor/src/core/hooks/useUrlSync.ts b/frontend/editor/src/core/hooks/useUrlSync.ts
index 76fd67178a..ae56a31909 100644
--- a/frontend/editor/src/core/hooks/useUrlSync.ts
+++ b/frontend/editor/src/core/hooks/useUrlSync.ts
@@ -3,20 +3,23 @@
*/
import { useEffect, useCallback, useRef, type MutableRefObject } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
import { ToolId } from "@app/types/toolId";
import {
parseToolRoute,
- updateToolRoute,
- clearToolRoute,
+ toolRoute,
+ editorHomeRoute,
} from "@app/utils/urlRouting";
import { ToolRegistry } from "@app/data/toolsTaxonomy";
import { firePixel } from "@app/utils/scarfTracking";
-import { withBasePath } from "@app/constants/app";
-import { EDITOR_BASENAME } from "@app/routes/editorBasename";
import { useAppConfig } from "@app/contexts/AppConfigContext";
/**
* Hook to sync workbench and tool with URL using registry
+ *
+ * Both directions go through the router, reads included. State derived from the
+ * path - the file library's reconciler above all - only sees addresses the router
+ * knows, so writing one any other way moves the address past the view.
*/
export function useNavigationUrlSync(
selectedTool: ToolId | null,
@@ -32,25 +35,31 @@ export function useNavigationUrlSync(
) {
const { config } = useAppConfig();
const premiumEnabled = config?.premiumEnabled;
+ const navigate = useNavigate();
+ const { pathname, search } = useLocation();
const hasInitialized = useRef(false);
const prevSelectedTool = useRef<ToolId | null>(null);
+ // A pixel is a move, not a render.
+ const countedPath = useRef<string | null>(null);
+
+ // Held in a ref so neither pass below depends on it: a write that re-ran on
+ // every address change would answer a Back by returning to the tool it left.
+ const here = useRef({ pathname, search });
+ here.current = { pathname, search };
// Check if tool requires premium and redirect if needed
const checkPremiumAndSelect = useCallback(
(toolId: ToolId) => {
const tool = registry[toolId];
if (tool?.requiresPremium === true && premiumEnabled !== true) {
- // Premium tool accessed without premium - redirect to home
- const homePath = withBasePath(EDITOR_BASENAME);
- if (window.location.pathname !== homePath) {
- clearToolRoute(true); // Use replaceState to avoid adding to history
- window.location.href = homePath;
- }
+ // Replaced, not pushed: Back would land on an address that bounces again.
+ const target = editorHomeRoute(here.current);
+ if (target) navigate(target, { replace: true });
return;
}
handleToolSelect(toolId);
},
- [registry, premiumEnabled, handleToolSelect],
+ [registry, premiumEnabled, handleToolSelect, navigate],
);
// Initialize workbench and tool from URL on mount
@@ -62,10 +71,9 @@ export function useNavigationUrlSync(
if (hasInitialized.current) return;
// Fire pixel for initial page load
- const currentPath = window.location.pathname;
- firePixel(currentPath);
+ firePixel(window.location.pathname);
- const route = parseToolRoute(registry);
+ const route = parseToolRoute(registry, here.current);
if (route.toolId) {
// URL specifies a tool — navigate to it (URL takes precedence over startup view preference)
if (route.toolId !== selectedTool) {
@@ -76,28 +84,79 @@ export function useNavigationUrlSync(
// the startup view preference (defaultStartupView) is respected.
hasInitialized.current = true;
- }, [checkPremiumAndSelect, config, enableSync, registry, selectedTool]); // Include dependencies
+ countedPath.current = pathname;
+ }, [
+ checkPremiumAndSelect,
+ config,
+ enableSync,
+ pathname,
+ registry,
+ selectedTool,
+ ]);
- // Update URL when tool or workbench changes
+ // Address -> selection, for every move after arrival, Back and forward included.
+ // The mount pass above leaves an address carrying no tool alone so the
+ // startup-view preference survives a reload; here it means no tool.
useEffect(() => {
if (!enableSync) return;
+ if (!hasInitialized.current) return;
+ // A selection the pass below has not pushed yet is in flight, not stale:
+ // reconciling it against the address it is leaving would cancel the move.
+ if (prevSelectedTool.current !== selectedTool) return;
+
+ if (countedPath.current !== pathname) {
+ countedPath.current = pathname;
+ firePixel(window.location.pathname);
+ }
- const startupTool = startupSelectedToolRef?.current ?? null;
+ // Disagreement is the trigger, not arrival: a Back can land on the address a
+ // tool was picked from, where the path is unchanged but the selection is not.
+ const route = parseToolRoute(registry, here.current);
+ if (route.toolId === selectedTool) return;
+ if (route.toolId) {
+ checkPremiumAndSelect(route.toolId);
+ } else {
+ clearToolSelection();
+ }
+ }, [
+ pathname,
+ selectedTool,
+ clearToolSelection,
+ registry,
+ enableSync,
+ checkPremiumAndSelect,
+ ]);
- if (selectedTool) {
- // A startup-view selection is a view preference, not a navigation: writing
- // it here rewrote /editor to /read on every load. The effect re-runs
- // whenever the registry identity changes, so the marker has to survive
- // until the selection actually moves off it (cleared below).
- if (startupTool !== selectedTool) {
- updateToolRoute(selectedTool, registry, false); // Use pushState for user navigation
- }
- } else if (prevSelectedTool.current !== null) {
- // Only clear URL if we had a tool before (user navigated away)
- // Don't clear on initial load when both current and previous are null
- const homePath = withBasePath(EDITOR_BASENAME);
- if (window.location.pathname !== homePath) {
- clearToolRoute(false); // Use pushState for user navigation
+ // Selection -> address. The pass above owns what an address change means.
+ useEffect(() => {
+ if (!enableSync) return;
+ // Writing before the address has been read would push the startup view ahead
+ // of whatever the address asked for.
+ if (!hasInitialized.current) return;
+
+ const startupTool = startupSelectedToolRef?.current ?? null;
+ const previous = prevSelectedTool.current;
+
+ // Only a change of selection is a navigation: the registry's identity churns,
+ // and re-asserting the tool's address on every run would undo a Back the
+ // moment it landed.
+ if (selectedTool !== previous) {
+ if (selectedTool) {
+ // A startup-view selection is a view preference, not a navigation, or
+ // every visit to /editor becomes /read. The marker survives until the
+ // selection moves off it (cleared below).
+ if (startupTool !== selectedTool) {
+ const target = toolRoute(selectedTool, registry, here.current);
+ if (target) navigate(target); // Pushed: picking a tool is a navigation
+ }
+ } else if (previous !== null) {
+ // Only a tool's own address is this hook's to clear: the library and the
+ // reader name no tool rather than holding a stale one, and sending them
+ // home would undo the navigation that cleared the selection.
+ if (parseToolRoute(registry, here.current).toolId !== null) {
+ const target = editorHomeRoute(here.current);
+ if (target) navigate(target);
+ }
}
}
@@ -106,88 +165,12 @@ export function useNavigationUrlSync(
if (
startupSelectedToolRef &&
startupTool !== null &&
- prevSelectedTool.current === startupTool &&
+ previous === startupTool &&
selectedTool !== startupTool
) {
startupSelectedToolRef.current = null;
}
prevSelectedTool.current = selectedTool;
- }, [selectedTool, registry, enableSync, startupSelectedToolRef]);
-
- // Handle browser back/forward navigation
- useEffect(() => {
- if (!enableSync) return;
-
- const handlePopState = () => {
- const route = parseToolRoute(registry);
- if (route.toolId !== selectedTool) {
- // Fire pixel for back/forward navigation
- const currentPath = window.location.pathname;
- firePixel(currentPath);
-
- if (route.toolId) {
- checkPremiumAndSelect(route.toolId);
- } else {
- clearToolSelection();
- }
- }
- };
-
- window.addEventListener("popstate", handlePopState);
- return () => window.removeEventListener("popstate", handlePopState);
- }, [
- selectedTool,
- handleToolSelect,
- clearToolSelection,
- registry,
- enableSync,
- checkPremiumAndSelect,
- ]);
-}
-
-/**
- * Hook to programmatically navigate to tools with registry support
- */
-export function useToolNavigation(registry: ToolRegistry) {
- const navigateToTool = useCallback(
- (toolId: ToolId) => {
- updateToolRoute(toolId, registry);
-
- // Dispatch a custom event to notify other components
- window.dispatchEvent(
- new CustomEvent("toolNavigation", {
- detail: { toolId },
- }),
- );
- },
- [registry],
- );
-
- const navigateToHome = useCallback(() => {
- clearToolRoute();
-
- // Dispatch a custom event to notify other components
- window.dispatchEvent(
- new CustomEvent("toolNavigation", {
- detail: { toolId: null },
- }),
- );
- }, []);
-
- return {
- navigateToTool,
- navigateToHome,
- };
-}
-
-/**
- * Hook to get current URL route information with registry support
- */
-export function useCurrentRoute(registry: ToolRegistry) {
- const getCurrentRoute = useCallback(() => {
- return parseToolRoute(registry);
- }, [registry]);
-
- return getCurrentRoute;
+ }, [selectedTool, registry, enableSync, startupSelectedToolRef, navigate]);
}
diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsx
index e4fe7073d7..88f1d865cd 100644
--- a/frontend/editor/src/core/pages/HomePage.tsx
+++ b/frontend/editor/src/core/pages/HomePage.tsx
@@ -355,12 +355,26 @@ export default function HomePage() {
}, [toolRegistry, toolAvailability, config?.premiumEnabled, t]);
const openFromComputerRef = useRef<(() => void) | null>(null);
+ // Reading unmounts the sidebar that owns the picker, so a request made there
+ // is held until the sidebar is back to answer it.
+ const openFromComputerPending = useRef(false);
const registerOpenFromComputer = useCallback((open: (() => void) | null) => {
openFromComputerRef.current = open;
+ if (open && openFromComputerPending.current) {
+ openFromComputerPending.current = false;
+ open();
+ }
}, []);
const openFromComputer = useCallback(() => {
- openFromComputerRef.current?.();
- }, []);
+ if (openFromComputerRef.current) {
+ openFromComputerRef.current();
+ return;
+ }
+ // Opening a document from disk shows it, and reading is a view of one
+ // document, so the picker lands you on what you opened either way.
+ openFromComputerPending.current = true;
+ setReaderMode(false);
+ }, [setReaderMode]);
const [showSwipeHint, setShowSwipeHint] = useState(
() => !readSwipeHintSeen(),
diff --git a/frontend/editor/src/core/tests/stubbed/quicknav-file-library.spec.ts b/frontend/editor/src/core/tests/stubbed/quicknav-file-library.spec.ts
new file mode 100644
index 0000000000..26ecd2f898
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/quicknav-file-library.spec.ts
@@ -0,0 +1,52 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+type P = import("@playwright/test").Page;
+
+const nav = (page: P) =>
+ page.getByRole("navigation", { name: /Quick navigation/i });
+const rail = (page: P, name: RegExp) => nav(page).getByRole("button", { name });
+const folderTree = (page: P) => page.getByRole("tree", { name: /Folders/i });
+
+async function intoLibrary(page: P) {
+ await rail(page, /^File library$/i).click();
+ await expect(page).toHaveURL(/\/files/);
+ await expect(folderTree(page)).toBeVisible({ timeout: 15_000 });
+}
+
+/**
+ * Selecting a tool moves the address, and the library is the view the address
+ * decides. Writing that address outside the router left react-router on /files,
+ * so the reconciler that takes the view out of "myFiles" never ran: the tool was
+ * selected, its panel stayed hidden behind the library, and both rail entries lit.
+ */
+test.describe("a tool picked from the file library opens", () => {
+ test("the library gives way to the tool", async ({ page }) => {
+ await intoLibrary(page);
+
+ await rail(page, /^Automate$/i).click();
+
+ await expect(page).toHaveURL(/\/automate/);
+ await expect(folderTree(page)).toBeHidden();
+ await expect(rail(page, /^File library$/i)).not.toHaveAttribute(
+ "aria-current",
+ "true",
+ );
+ });
+
+ // The address and the view disagreeing is what made Back land on /editor with
+ // the library still on screen.
+ test("back returns to the library", async ({ page }) => {
+ await intoLibrary(page);
+ await rail(page, /^Automate$/i).click();
+ await expect(folderTree(page)).toBeHidden();
+
+ await page.goBack();
+
+ await expect(page).toHaveURL(/\/files/);
+ await expect(folderTree(page)).toBeVisible();
+ await expect(rail(page, /^File library$/i)).toHaveAttribute(
+ "aria-current",
+ "true",
+ );
+ });
+});
diff --git a/frontend/editor/src/core/tests/stubbed/reader-open-from-computer.spec.ts b/frontend/editor/src/core/tests/stubbed/reader-open-from-computer.spec.ts
new file mode 100644
index 0000000000..9719803292
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/reader-open-from-computer.spec.ts
@@ -0,0 +1,35 @@
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+
+type P = import("@playwright/test").Page;
+const rail = (p: P, name: RegExp) =>
+ p
+ .getByRole("navigation", { name: /Quick navigation/i })
+ .getByRole("button", { name });
+
+/**
+ * The picker lives in the file sidebar, which reading unmounts along with the
+ * rest of the wing. Quick navigation still offers it there, so the request has to
+ * outlive the unmount rather than land on nothing - and still count as the same
+ * user gesture, or the browser refuses to open the dialog.
+ */
+test("open from computer opens the picker while reading", async ({ page }) => {
+ await rail(page, /^Reader$/i).click();
+ await expect(page).toHaveURL(/\/reader/);
+ await expect(page.locator('[data-testid="file-input"]')).toHaveCount(0);
+
+ // The event only fires when the browser really opens a chooser.
+ const chooser = page.waitForEvent("filechooser", { timeout: 10_000 });
+ await page.getByTestId("files-button").click();
+ await chooser;
+
+ await page.locator('[data-testid="file-input"]').setInputFiles([SAMPLE_PDF]);
+ await expect(page.locator(".file-sidebar-file-item").first()).toBeVisible({
+ timeout: 10_000,
+ });
+});
diff --git a/frontend/editor/src/core/utils/urlRouting.ts b/frontend/editor/src/core/utils/urlRouting.ts
index f8869067c2..473efc47d4 100644
--- a/frontend/editor/src/core/utils/urlRouting.ts
+++ b/frontend/editor/src/core/utils/urlRouting.ts
@@ -10,22 +10,27 @@ import {
getToolWorkbench,
getToolUrlPath,
} from "@app/data/toolsTaxonomy";
-import { firePixel } from "@app/utils/scarfTracking";
import { URL_TO_TOOL_MAP } from "@app/utils/urlMapping";
-import { BASE_PATH, withBasePath } from "@app/constants/app";
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
/**
- * Parse the current URL to extract tool routing information
+ * An address as the router states it: app-relative, BASE_PATH already off.
+ *
+ * Everything here works in these terms rather than reading window.location. The
+ * two disagree for a tick during a history move, and an effect that navigates on
+ * the wrong one loops.
*/
-export function parseToolRoute(registry: ToolRegistry): ToolRoute {
- const fullPath = window.location.pathname;
- // Remove base path to get app-relative path
- const path =
- BASE_PATH && fullPath.startsWith(BASE_PATH)
- ? fullPath.slice(BASE_PATH.length) || "/"
- : fullPath;
- const searchParams = new URLSearchParams(window.location.search);
+export interface RouteLocation {
+ pathname: string;
+ search: string;
+}
+
+export function parseToolRoute(
+ registry: ToolRegistry,
+ location: RouteLocation,
+): ToolRoute {
+ const path = location.pathname;
+ const searchParams = new URLSearchParams(location.search);
// First, check URL mapping for multiple URL aliases
const mappedToolId = URL_TO_TOOL_MAP[path];
@@ -66,63 +71,37 @@ export function parseToolRoute(registry: ToolRegistry): ToolRoute {
}
/**
- * Update URL and fire analytics pixel
+ * Where the address should move to, or null when it already says this. The result
+ * is app-relative, which is what navigate() wants: <BrowserRouter basename> puts
+ * BASE_PATH back on, so a target carrying it already arrives doubled.
*/
-function updateUrl(
- newPath: string,
- searchParams: URLSearchParams,
- replace: boolean = false,
-): void {
- const currentPath = window.location.pathname;
+function routeTarget(path: string, from: RouteLocation): string | null {
+ const searchParams = new URLSearchParams(from.search);
+ // The path names the tool, so the query form of it never survives a move.
+ searchParams.delete("tool");
const queryString = searchParams.toString();
- const fullUrl = newPath + (queryString ? `?${queryString}` : "");
+ const search = queryString ? `?${queryString}` : "";
- // Only update URL and fire pixel if something actually changed
- if (
- currentPath !== newPath ||
- window.location.search !== (queryString ? `?${queryString}` : "")
- ) {
- if (replace) {
- window.history.replaceState(null, "", fullUrl);
- } else {
- window.history.pushState(null, "", fullUrl);
- }
- firePixel(newPath);
- }
+ if (from.pathname === path && from.search === search) return null;
+ return `${path}${search}`;
}
-/**
- * Update the URL to reflect the current tool selection
- */
-export function updateToolRoute(
+/** Where the address should move to for this tool selection. */
+export function toolRoute(
toolId: ToolId,
registry: ToolRegistry,
- replace: boolean = false,
-): void {
- const tool = registry[toolId];
- if (!tool) {
+ from: RouteLocation,
+): string | null {
+ if (!registry[toolId]) {
console.warn(`Tool ${toolId} not found in registry`);
- return;
+ return null;
}
-
- const toolPath = getToolUrlPath(toolId);
- const newPath = withBasePath(toolPath);
- const searchParams = new URLSearchParams(window.location.search);
-
- // Remove tool query parameter since we're using path-based routing
- searchParams.delete("tool");
-
- updateUrl(newPath, searchParams, replace);
+ return routeTarget(getToolUrlPath(toolId), from);
}
-/**
- * Clear tool routing and return to the editor home ("/" is the role router).
- */
-export function clearToolRoute(replace: boolean = false): void {
- const searchParams = new URLSearchParams(window.location.search);
- searchParams.delete("tool");
-
- updateUrl(withBasePath(EDITOR_BASENAME), searchParams, replace);
+/** Where the address should move to with no tool open ("/" is the role router). */
+export function editorHomeRoute(from: RouteLocation): string | null {
+ return routeTarget(EDITOR_BASENAME, from);
}
/**