Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ export default function NetworkApplicationsPage() {
queryParams({
del: ["networkStatus", "country", "page"],
scroll: false,
shallow: true,
});
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { buildUrl, fetcher } from "@dub/utils";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import useSWR from "swr";
import { useDebouncedCallback } from "use-debounce";
import { CampaignEvent, EventStatus } from "./campaign-events";
import { campaignEventsColumns } from "./campaign-events-columns";

Expand All @@ -33,12 +32,6 @@ export function CampaignEventsModal({
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");

const debounced = useDebouncedCallback((value) => {
setDebouncedSearch(value);
// Reset pagination to page 1 when search changes
setPagination((prev) => ({ ...prev, pageIndex: 1 }));
}, 500);

const {
data: events,
error,
Expand Down Expand Up @@ -121,9 +114,11 @@ export function CampaignEventsModal({
<div className="flex-shrink-0 border-b border-neutral-200 px-4 py-3">
<SearchBox
value={search}
onChange={(value) => {
setSearch(value);
debounced(value);
onChange={setSearch}
onChangeDebounced={(value) => {
setDebouncedSearch(value);
// Reset pagination to page 1 when search changes
setPagination((prev) => ({ ...prev, pageIndex: 1 }));
}}
placeholder="Search by partner name or email..."
loading={isLoading && debouncedSearch.length > 0}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,16 +102,7 @@ export function CustomDomains() {
<div className="grid gap-5">
<div className="flex flex-wrap justify-between gap-6">
<div className="w-full sm:w-auto">
<SearchBoxPersisted
loading={loading}
onChangeDebounced={(t) => {
if (t) {
queryParams({ set: { search: t }, del: "page" });
} else {
queryParams({ del: "search" });
}
}}
/>
<SearchBoxPersisted loading={loading} />
</div>
<div className="flex w-full flex-wrap items-center gap-3 sm:w-auto">
<ToggleGroup
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { FolderCard } from "@/ui/folders/folder-card";
import { FolderCardPlaceholder } from "@/ui/folders/folder-card-placeholder";
import { useAddFolderModal } from "@/ui/modals/add-folder-modal";
import { SearchBoxPersisted } from "@/ui/shared/search-box";
import { PaginationControls, usePagination, useRouterStuff } from "@dub/ui";
import { PaginationControls, usePagination } from "@dub/ui";
import { useSearchParams } from "next/navigation";

const allLinkFolder: Folder = {
Expand All @@ -21,7 +21,6 @@ const allLinkFolder: Folder = {

export const FoldersPageClient = () => {
const searchParams = useSearchParams();
const { queryParams } = useRouterStuff();

const { folders, isValidating } = useFolders({
includeParams: ["search", "page"],
Expand All @@ -44,16 +43,7 @@ export const FoldersPageClient = () => {
<div className="grid gap-4">
<div className="flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto">
<div className="w-full md:w-56 lg:w-64">
<SearchBoxPersisted
loading={isValidating}
onChangeDebounced={(t) => {
if (t) {
queryParams({ set: { search: t }, del: "page" });
} else {
queryParams({ del: "search" });
}
}}
/>
<SearchBoxPersisted loading={isValidating} />
</div>
</div>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const TagsListContext = createContext<{
});

export default function WorkspaceTagsClient() {
const { searchParams, queryParams } = useRouterStuff();
const { searchParams } = useRouterStuff();

const { AddEditTagModal, AddTagButton } = useAddEditTagModal();

Expand All @@ -50,16 +50,7 @@ export default function WorkspaceTagsClient() {
<div className="grid grid-cols-1 gap-4 pb-10">
<AddEditTagModal />
<div className="flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto">
<SearchBoxPersisted
loading={loading}
onChangeDebounced={(t) => {
if (t) {
queryParams({ set: { search: t }, del: "page" });
} else {
queryParams({ del: "search" });
}
}}
/>
<SearchBoxPersisted loading={loading} />
</div>

{!loading && tags?.length === 0 ? (
Expand Down
114 changes: 114 additions & 0 deletions apps/web/tests/ui/use-router-stuff.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// @vitest-environment happy-dom
import { createElement } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

// Mock fns shared with the next/navigation mock factory (hoisted above imports).
const mocks = vi.hoisted(() => ({
push: vi.fn(),
replace: vi.fn(),
searchParams: new URLSearchParams(),
}));

vi.mock("next/navigation", () => ({
useRouter: () => ({ push: mocks.push, replace: mocks.replace }),
usePathname: () => "/test",
useSearchParams: () => mocks.searchParams,
}));

// `useRouterStuff` imports `AppRouterInstance` (type only) from this module; mock
// it defensively in case the transpiler emits a runtime import for it.
vi.mock("next/dist/shared/lib/app-router-context.shared-runtime", () => ({}));

// Import the hook directly from source (not the @dub/ui barrel) to keep the test
// light and avoid pulling the whole UI library into the test environment.
import { useRouterStuff } from "../../../../packages/ui/src/hooks/use-router-stuff";

/** Render the hook once and return its API (no effects involved here). */
function renderQueryParams() {
let api: ReturnType<typeof useRouterStuff> | undefined;
function Probe() {
api = useRouterStuff();
return null;
}
const container = document.createElement("div");
document.body.appendChild(container);
flushSync(() => createRoot(container).render(createElement(Probe)));
if (!api) throw new Error("hook did not render");
return api;
Comment on lines +29 to +39

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Unmount the React root to keep tests isolated.

renderQueryParams creates and mounts a root but never unmounts/removes it. Over multiple tests, this leaks mounted trees and can cause cross-test interference once the hook grows effects.

Suggested fix
 function renderQueryParams() {
   let api: ReturnType<typeof useRouterStuff> | undefined;
   function Probe() {
     api = useRouterStuff();
     return null;
   }
   const container = document.createElement("div");
   document.body.appendChild(container);
-  flushSync(() => createRoot(container).render(createElement(Probe)));
+  const root = createRoot(container);
+  flushSync(() => root.render(createElement(Probe)));
   if (!api) throw new Error("hook did not render");
-  return api;
+  return {
+    ...api,
+    cleanup: () => {
+      root.unmount();
+      container.remove();
+    },
+  };
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/tests/ui/use-router-stuff.test.ts` around lines 29 - 39, The
renderQueryParams helper mounts a React root via createRoot but never cleans it
up, which can leak mounted trees across tests. Update renderQueryParams to keep
a reference to the root returned by createRoot, and make sure it is unmounted
and the container is removed after use; use the Probe component and
useRouterStuff hook as the key places to locate the setup. If needed, wrap the
helper’s mounting logic so cleanup runs reliably even when assertions fail.

}

describe("useRouterStuff queryParams — shallow routing", () => {
let replaceState: ReturnType<typeof vi.spyOn>;
let pushState: ReturnType<typeof vi.spyOn>;

beforeEach(() => {
mocks.push.mockClear();
mocks.replace.mockClear();
mocks.searchParams = new URLSearchParams();
replaceState = vi.spyOn(window.history, "replaceState");
pushState = vi.spyOn(window.history, "pushState");
});

afterEach(() => {
vi.restoreAllMocks();
});

// This is the invariant the search-perf fix depends on: a `shallow` write must
// update the URL via the History API and must NOT trigger a router navigation
// (which would re-render Server Components — a wasted RSC round-trip for our
// client-fetched, SWR-keyed tables). SearchBoxPersisted relies on this.
it("shallow + replace writes the URL via history.replaceState, never the router", () => {
const { queryParams } = renderQueryParams();

queryParams({
set: { search: "foo" },
del: "page",
shallow: true,
replace: true,
});

expect(replaceState).toHaveBeenCalledWith({}, "", "/test?search=foo");
expect(pushState).not.toHaveBeenCalled();
expect(mocks.replace).not.toHaveBeenCalled();
expect(mocks.push).not.toHaveBeenCalled();
});

it("shallow without replace uses history.pushState (mirrors router.push)", () => {
const { queryParams } = renderQueryParams();

queryParams({ set: { search: "foo" }, shallow: true });

expect(pushState).toHaveBeenCalledWith({}, "", "/test?search=foo");
expect(mocks.push).not.toHaveBeenCalled();
expect(mocks.replace).not.toHaveBeenCalled();
});

it("non-shallow falls back to a router navigation (the RSC round-trip we avoid for search)", () => {
const { queryParams } = renderQueryParams();

queryParams({ set: { search: "foo" } });

expect(mocks.push).toHaveBeenCalledWith("/test?search=foo", {
scroll: false,
});
expect(replaceState).not.toHaveBeenCalled();
expect(pushState).not.toHaveBeenCalled();
});

it("no-ops when the resulting URL is unchanged (no router nav, no history write)", () => {
mocks.searchParams = new URLSearchParams("search=foo");
const { queryParams } = renderQueryParams();

// `del` a param that isn't present → identical URL. This is the pagination
// case: after a search clears `page`, a pagination sync re-issues del:page,
// which must not fire a (same-URL) navigation / RSC round-trip.
queryParams({ del: "page" });

expect(mocks.push).not.toHaveBeenCalled();
expect(mocks.replace).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
expect(pushState).not.toHaveBeenCalled();
});
});
28 changes: 18 additions & 10 deletions apps/web/ui/shared/search-box.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,19 @@ export const SearchBox = forwardRef(
onChange(e.target.value);
debounced(e.target.value);
}}
onKeyDown={(e) => {
// Commit the search immediately on Enter rather than waiting out the
// debounce. isComposing guards against firing mid-IME-composition.
if (e.key === "Enter" && !e.nativeEvent.isComposing) {
debounced.flush();
}
}}
autoCapitalize="none"
/>
{showClearButton && value.length > 0 && (
<button
onClick={() => {
debounced.cancel();
onChange("");
onChangeDebounced?.("");
}}
Expand All @@ -109,33 +117,36 @@ export const SearchBox = forwardRef(
},
);

// For client-rendered search views only. Updates the URL shallowly so useSearchParams-driven data fetching can run without RSC round-trip
export function SearchBoxPersisted({
urlParam = "search",
onChange,
onChangeDebounced,
...props
}: { urlParam?: string } & Partial<SearchBoxProps>) {
}: { urlParam?: string } & Partial<Omit<SearchBoxProps, "onChangeDebounced">>) {
const { queryParams, searchParams } = useRouterStuff();

const [value, setValue] = useState(searchParams.get(urlParam) ?? "");
const [debouncedValue, setDebouncedValue] = useState(value);

// Set URL param when debounced value changes
useEffect(() => {
if (searchParams.get(urlParam) ?? "" !== debouncedValue)
if ((searchParams.get(urlParam) ?? "") !== debouncedValue)
queryParams(
debouncedValue === ""
? { del: [urlParam, "page"] }
: { set: { [urlParam]: debouncedValue }, del: "page" },
? { del: [urlParam, "page"], shallow: true }
: { set: { [urlParam]: debouncedValue }, del: "page", shallow: true },
);
}, [debouncedValue]);

// Set value when URL param changes
useEffect(() => {
const search = searchParams.get(urlParam);
// Only update if the value and debouncedValue are synced (the user isn't actively typing)
if ((search ?? "" !== value) && value === debouncedValue)
if ((search ?? "") !== value && value === debouncedValue) {
// Sync browser back/forward URL changes without overwriting in-progress edits.
setValue(search ?? "");
setDebouncedValue(search ?? "");
}
}, [searchParams.get(urlParam)]);

return (
Expand All @@ -145,10 +156,7 @@ export function SearchBoxPersisted({
setValue(value);
onChange?.(value);
}}
onChangeDebounced={(value) => {
setDebouncedValue(value);
onChangeDebounced?.(value);
}}
onChangeDebounced={setDebouncedValue}
{...props}
/>
);
Expand Down
22 changes: 22 additions & 0 deletions packages/ui/src/hooks/use-router-stuff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,15 @@ export function useRouterStuff() {
set,
del,
replace,
shallow,
scroll = false,
getNewPath,
arrayDelimiter = ",",
}: {
set?: Record<string, string | string[]>;
del?: string | string[];
replace?: boolean;
shallow?: boolean;
scroll?: boolean;
getNewPath?: boolean;
arrayDelimiter?: string;
Expand All @@ -87,6 +89,26 @@ export function useRouterStuff() {
}`;
if (getNewPath) return newPath;

// Avoid no-op navigations, which can still trigger RSC work.
const currentQuery = searchParams.toString();
const currentPath = `${pathname}${
currentQuery.length > 0 ? `?${currentQuery}` : ""
}`;
if (newPath === currentPath) return;

// Client-owned params can update without triggering a new RSC round-trip.
if (shallow) {
// guard for SSR safety; mirror router.push/replace semantics.
if (typeof window !== "undefined") {
if (replace) {
window.history.replaceState({}, "", newPath);
} else {
window.history.pushState({}, "", newPath);
}
}
return;
}

// Nested overflow container scroll is not preserved by Next's `scroll: false` (window-only).
if (scroll === false && typeof document !== "undefined") {
const el = document.getElementById(DUB_DASHBOARD_MAIN_SCROLL_ID);
Expand Down
Loading