Skip to content

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

refactor: debounced search (#21149)

ecmadaoc911d9a80362
diff --git a/frontend/src/components/AccountMultiSelect.tsx b/frontend/src/components/AccountMultiSelect.tsx
index c4b0be1572..bf66ff43c6 100644
--- a/frontend/src/components/AccountMultiSelect.tsx
+++ b/frontend/src/components/AccountMultiSelect.tsx
@@ -209,25 +209,17 @@ export function AccountMultiSelect({
const containerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
- const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Cache display labels for selected items so they persist across search changes
const labelCacheRef = useRef<Map<string, string>>(new Map());
- // Fetch on search change (debounced 300ms)
useEffect(() => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- debounceRef.current = setTimeout(() => {
- const query = search.trim();
- listUsers({ pageSize: getDefaultPagination(), filter: { query } }).then(
- ({ users: fetched }) => setUsers(fetched)
- );
- listGroups({ pageSize: getDefaultPagination(), filter: { query } }).then(
- ({ groups: fetched }) => setGroups(fetched)
- );
- }, 300);
- return () => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- };
+ const query = search.trim();
+ listUsers({ pageSize: getDefaultPagination(), filter: { query } }).then(
+ ({ users: fetched }) => setUsers(fetched)
+ );
+ listGroups({ pageSize: getDefaultPagination(), filter: { query } }).then(
+ ({ groups: fetched }) => setGroups(fetched)
+ );
}, [search, listUsers, listGroups]);
const handleClickOutside = useCallback(() => {
diff --git a/frontend/src/components/AdvancedSearch.tsx b/frontend/src/components/AdvancedSearch.tsx
index eed96e5db1..1ebfeb6339 100644
--- a/frontend/src/components/AdvancedSearch.tsx
+++ b/frontend/src/components/AdvancedSearch.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { HighlightLabelText } from "@/components/HighlightLabelText";
import { LAYER_SURFACE_CLASS } from "@/components/ui/layer";
import { cn } from "@/lib/utils";
+import { DEBOUNCE_SEARCH_DELAY } from "@/types/common";
// ============================================================
// Types
@@ -312,7 +313,7 @@ export function AdvancedSearch({
if (asyncRequestRef.current !== requestID) return;
setAsyncLoading(false);
});
- }, 300);
+ }, DEBOUNCE_SEARCH_DELAY);
return () => {
clearTimeout(asyncSearchRef.current);
};
@@ -446,7 +447,7 @@ export function AdvancedSearch({
if (text !== params.query) {
onParamsChange({ ...params, query: text });
}
- }, 300);
+ }, DEBOUNCE_SEARCH_DELAY);
},
[currentScope, params, onParamsChange]
);
diff --git a/frontend/src/components/AuditLogTable.tsx b/frontend/src/components/AuditLogTable.tsx
index 617ca1d99f..6ad8bb7dc3 100644
--- a/frontend/src/components/AuditLogTable.tsx
+++ b/frontend/src/components/AuditLogTable.tsx
@@ -677,18 +677,11 @@ export function AuditLogTable({
}
}
},
- [hasAuditLogFeature, parent, filter, orderBy, pageSize, t]
+ [hasAuditLogFeature, parent, filter, orderBy, pageSize]
);
- const isFirstLoad = useRef(true);
useEffect(() => {
- if (isFirstLoad.current) {
- isFirstLoad.current = false;
- fetchAuditLogs(true);
- return;
- }
- const timer = setTimeout(() => fetchAuditLogs(true), 300);
- return () => clearTimeout(timer);
+ fetchAuditLogs(true);
}, [fetchAuditLogs]);
const loadMore = useCallback(() => {
diff --git a/frontend/src/components/ExprEditor.tsx b/frontend/src/components/ExprEditor.tsx
index 38026bce19..35b7b37212 100644
--- a/frontend/src/components/ExprEditor.tsx
+++ b/frontend/src/components/ExprEditor.tsx
@@ -270,13 +270,11 @@ function SearchableSelect({
onChange: (value: string) => void;
}) {
const { t } = useTranslation();
- const [search, setSearch] = useState("");
const [open, setOpen] = useState(false);
const [options, setOptions] = useState<SearchableSelectOption[]>([]);
const [loading, setLoading] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
- const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const selectedLabel = useMemo(() => {
const found = options.find((o) => o.value === value);
@@ -320,19 +318,12 @@ function SearchableSelect({
const handleOpen = () => {
setOpen(true);
- doSearch(search);
- };
-
- const handleSearchChange = (q: string) => {
- setSearch(q);
- if (debounceRef.current) clearTimeout(debounceRef.current);
- debounceRef.current = setTimeout(() => doSearch(q), 300);
+ doSearch("");
};
const handleSelect = (v: string) => {
onChange(v);
setOpen(false);
- setSearch("");
};
const close = useCallback(() => setOpen(false), []);
@@ -396,8 +387,7 @@ function SearchableSelect({
autoFocus
size="sm"
placeholder={t("common.filter-by-name")}
- value={search}
- onChange={(e) => handleSearchChange(e.target.value)}
+ onChange={(e) => void doSearch(e.target.value)}
/>
</div>
<ul className="max-h-48 overflow-y-auto py-1">
@@ -447,7 +437,6 @@ function MultiSearchableSelect({
onChange: (value: string[]) => void;
}) {
const { t } = useTranslation();
- const [search, setSearch] = useState("");
const [open, setOpen] = useState(false);
const [searchOptions, setSearchOptions] = useState<SearchableSelectOption[]>(
[]
@@ -455,7 +444,6 @@ function MultiSearchableSelect({
const [loading, setLoading] = useState(false);
const triggerRef = useRef<HTMLDivElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
- const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [knownOptions, setKnownOptions] = useState<SearchableSelectOption[]>(
[]
);
@@ -514,13 +502,7 @@ function MultiSearchableSelect({
const handleOpen = () => {
setOpen(true);
- doSearch(search);
- };
-
- const handleSearchChange = (q: string) => {
- setSearch(q);
- if (debounceRef.current) clearTimeout(debounceRef.current);
- debounceRef.current = setTimeout(() => doSearch(q), 300);
+ doSearch("");
};
const toggleValue = (v: string) => {
@@ -596,8 +578,7 @@ function MultiSearchableSelect({
autoFocus
size="sm"
placeholder={t("common.filter-by-name")}
- value={search}
- onChange={(e) => handleSearchChange(e.target.value)}
+ onChange={(e) => void doSearch(e.target.value)}
/>
</div>
<ul className="max-h-48 overflow-y-auto py-1">
diff --git a/frontend/src/components/database/DatabaseTable.test.tsx b/frontend/src/components/database/DatabaseTable.test.tsx
index 91318b3b78..f2d0c934a5 100644
--- a/frontend/src/components/database/DatabaseTable.test.tsx
+++ b/frontend/src/components/database/DatabaseTable.test.tsx
@@ -169,6 +169,34 @@ describe("DatabaseTable", () => {
).toBe(`${db1.name},${db2.name}`);
});
+ test("refreshes immediately when the filter changes", async () => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [],
+ nextPageToken: "",
+ });
+
+ await act(async () => {
+ root!.render(
+ <DatabaseTable filter={{ query: "" }} parent="instances/i" />
+ );
+ await Promise.resolve();
+ });
+ await act(async () => {
+ root!.render(
+ <DatabaseTable filter={{ query: "payroll" }} parent="instances/i" />
+ );
+ await Promise.resolve();
+ });
+
+ expect(mocks.fetchDatabases).toHaveBeenLastCalledWith(
+ expect.objectContaining({ filter: { query: "payroll" } })
+ );
+ });
+
test("forwards empty placeholder only after a truly empty page loads", async () => {
container = document.createElement("div");
document.body.appendChild(container);
diff --git a/frontend/src/components/database/DatabaseTable.tsx b/frontend/src/components/database/DatabaseTable.tsx
index 4d661281f9..27827b0596 100644
--- a/frontend/src/components/database/DatabaseTable.tsx
+++ b/frontend/src/components/database/DatabaseTable.tsx
@@ -140,15 +140,8 @@ export function DatabaseTable({
[pageSize, filterKey, orderBy, parent, workspaceResourceName]
);
- const isFirstLoad = useRef(true);
useEffect(() => {
- if (isFirstLoad.current) {
- isFirstLoad.current = false;
- fetchDatabases(true);
- return;
- }
- const timer = setTimeout(() => fetchDatabases(true), 300);
- return () => clearTimeout(timer);
+ fetchDatabases(true);
}, [fetchDatabases]);
// Support external refresh trigger
diff --git a/frontend/src/components/header/ProjectSwitchPanel.test.tsx b/frontend/src/components/header/ProjectSwitchPanel.test.tsx
index e28fa4e503..49da9e14bb 100644
--- a/frontend/src/components/header/ProjectSwitchPanel.test.tsx
+++ b/frontend/src/components/header/ProjectSwitchPanel.test.tsx
@@ -1,7 +1,7 @@
import type { ChangeEvent, InputHTMLAttributes, ReactElement } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { PROJECT_V1_ROUTE_DETAIL } from "@/app/router";
(
@@ -50,6 +50,7 @@ const mocks = vi.hoisted(() => ({
allProjects: [] as Array<typeof allProject>,
recentOptions: undefined as { excludeDefault?: boolean } | undefined,
projectListOptions: undefined as { excludeDefault?: boolean } | undefined,
+ projectListQueries: [] as string[],
hasMore: false,
loadMore: vi.fn(),
onPageSizeChange: vi.fn(),
@@ -89,9 +90,10 @@ vi.mock("@/hooks/useAppState", () => ({
};
},
useProjectList: (
- _query: string,
+ query: string,
options?: { excludeDefault?: boolean }
) => {
+ mocks.projectListQueries.push(query);
mocks.projectListOptions = options;
return {
projects: mocks.allProjects,
@@ -177,13 +179,48 @@ beforeEach(async () => {
mocks.allProjects = [allProject];
mocks.recentOptions = undefined;
mocks.projectListOptions = undefined;
+ mocks.projectListQueries = [];
mocks.hasMore = false;
mocks.inputOnChange = undefined;
window.open = vi.fn();
({ ProjectSwitchPanel } = await import("./ProjectSwitchPanel"));
});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
describe("ProjectSwitchPanel", () => {
+ test("debounces the backend project query at the input owner", () => {
+ vi.useFakeTimers();
+ const { render, unmount } = renderIntoContainer(
+ <ProjectSwitchPanel
+ onClose={mocks.close}
+ onRequestCreate={mocks.requestCreate}
+ />
+ );
+
+ render();
+ expect(mocks.projectListQueries.at(-1)).toBe("");
+
+ act(() => {
+ mocks.inputOnChange?.({
+ target: { value: "payroll" },
+ } as ChangeEvent<HTMLInputElement>);
+ });
+ act(() => {
+ vi.advanceTimersByTime(299);
+ });
+ expect(mocks.projectListQueries.at(-1)).toBe("");
+
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(mocks.projectListQueries.at(-1)).toBe("payroll");
+
+ unmount();
+ });
+
test("records and navigates when selecting a project", () => {
const { container, render, unmount } = renderIntoContainer(
<ProjectSwitchPanel
@@ -258,6 +295,7 @@ describe("ProjectSwitchPanel", () => {
});
test("filters recent projects by keyword", () => {
+ vi.useFakeTimers();
mocks.recentProjects = [recentProject, otherRecentProject];
mocks.allProjects = [];
const { container, render, unmount } = renderIntoContainer(
@@ -274,6 +312,9 @@ describe("ProjectSwitchPanel", () => {
target: { value: "recent project" },
} as ChangeEvent<HTMLInputElement>);
});
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
expect(container.textContent).toContain("Recent Project");
expect(container.textContent).not.toContain("Other Project");
diff --git a/frontend/src/components/header/ProjectSwitchPanel.tsx b/frontend/src/components/header/ProjectSwitchPanel.tsx
index b8fffe0f76..7d9a7633cd 100644
--- a/frontend/src/components/header/ProjectSwitchPanel.tsx
+++ b/frontend/src/components/header/ProjectSwitchPanel.tsx
@@ -15,7 +15,7 @@ import {
} from "@/app/router";
import { ProjectTable } from "@/components/ProjectTable";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
+import { SearchInput } from "@/components/ui/search-input";
import {
Select,
SelectContent,
@@ -162,7 +162,9 @@ export function ProjectSwitchPanel({
pageSize,
pageSizeOptions,
onPageSizeChange,
- } = useProjectList(searchText, { excludeDefault: excludeDefaultProject });
+ } = useProjectList(searchText, {
+ excludeDefault: excludeDefaultProject,
+ });
const handleProjectSelect = useCallback(
(project: Project, event: ReactMouseEvent<HTMLElement>) => {
@@ -238,9 +240,9 @@ export function ProjectSwitchPanel({
</TabsList>
<div className="flex items-center gap-x-1.5">
- <Input
+ <SearchInput
size="sm"
- className="w-36"
+ wrapperClassName="flex-none w-36"
value={searchText}
placeholder={t("common.filter-by-name")}
onChange={(event) => setSearchText(event.target.value)}
diff --git a/frontend/src/components/instance/InstanceDashboard.tsx b/frontend/src/components/instance/InstanceDashboard.tsx
index 9d1913235e..bb5caaaa8a 100644
--- a/frontend/src/components/instance/InstanceDashboard.tsx
+++ b/frontend/src/components/instance/InstanceDashboard.tsx
@@ -714,15 +714,8 @@ export function InstanceDashboard({
);
// Fetch on mount + re-fetch on filter/sort/pageSize changes
- const isFirstLoad = useRef(true);
useEffect(() => {
- if (isFirstLoad.current) {
- isFirstLoad.current = false;
- fetchInstances(true);
- return;
- }
- const timer = setTimeout(() => fetchInstances(true), 300);
- return () => clearTimeout(timer);
+ fetchInstances(true);
}, [fetchInstances]);
const loadMore = useCallback(() => {
diff --git a/frontend/src/components/ui/combobox.test.tsx b/frontend/src/components/ui/combobox.test.tsx
index 1eb4b75bb0..8ae73213cf 100644
--- a/frontend/src/components/ui/combobox.test.tsx
+++ b/frontend/src/components/ui/combobox.test.tsx
@@ -19,6 +19,7 @@ vi.mock("react-i18next", () => ({
describe("Combobox", () => {
afterEach(() => {
+ vi.useRealTimers();
document.body.innerHTML = "";
});
@@ -123,6 +124,7 @@ describe("Combobox", () => {
});
test("passes the search query to custom option renderers", () => {
+ vi.useFakeTimers();
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
@@ -158,6 +160,7 @@ describe("Combobox", () => {
)?.set;
valueSetter?.call(input, "byte");
input.dispatchEvent(new Event("input", { bubbles: true }));
+ vi.advanceTimersByTime(300);
});
expect(
diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx
index d69a4e3e91..0e0a404be8 100644
--- a/frontend/src/components/ui/combobox.tsx
+++ b/frontend/src/components/ui/combobox.tsx
@@ -143,11 +143,10 @@ export function Combobox(props: ComboboxProps) {
[allOptions, selectedValues]
);
- // Debounced server-side search
+ // SearchInput owns the debounce.
useEffect(() => {
if (!onSearch || !open) return;
- const timer = setTimeout(() => onSearch(search), 300);
- return () => clearTimeout(timer);
+ void onSearch(search);
}, [search, onSearch, open]);
// Filter options
diff --git a/frontend/src/components/ui/search-input.test.tsx b/frontend/src/components/ui/search-input.test.tsx
new file mode 100644
index 0000000000..7e036779bb
--- /dev/null
+++ b/frontend/src/components/ui/search-input.test.tsx
@@ -0,0 +1,91 @@
+import type { ChangeEvent } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { SearchInput } from "./search-input";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("SearchInput", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.useRealTimers();
+ });
+
+ const type = (input: HTMLInputElement, value: string) => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
+ input,
+ value
+ );
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ };
+
+ test("shows the raw value immediately and debounces onChange", () => {
+ const onChange = vi.fn<(event: ChangeEvent<HTMLInputElement>) => void>();
+ act(() => {
+ root.render(<SearchInput value="" onChange={onChange} />);
+ });
+ const input = container.querySelector("input") as HTMLInputElement;
+
+ act(() => type(input, "byte"));
+ expect(input.value).toBe("byte");
+ expect(onChange).not.toHaveBeenCalled();
+
+ act(() => vi.advanceTimersByTime(299));
+ expect(onChange).not.toHaveBeenCalled();
+
+ act(() => vi.advanceTimersByTime(1));
+ expect(onChange).toHaveBeenCalledOnce();
+ expect(onChange.mock.calls[0][0].target.value).toBe("byte");
+ });
+
+ test("emits only the latest value", () => {
+ const onChange = vi.fn<(event: ChangeEvent<HTMLInputElement>) => void>();
+ act(() => {
+ root.render(<SearchInput value="" onChange={onChange} />);
+ });
+ const input = container.querySelector("input") as HTMLInputElement;
+
+ act(() => type(input, "b"));
+ act(() => vi.advanceTimersByTime(200));
+ act(() => type(input, "byte"));
+ act(() => vi.advanceTimersByTime(300));
+
+ expect(onChange).toHaveBeenCalledOnce();
+ expect(onChange.mock.calls[0][0].target.value).toBe("byte");
+ });
+
+ test("synchronizes an external value change without emitting onChange", () => {
+ const onChange = vi.fn<(event: ChangeEvent<HTMLInputElement>) => void>();
+ act(() => {
+ root.render(<SearchInput value="draft" onChange={onChange} />);
+ });
+ const input = container.querySelector("input") as HTMLInputElement;
+
+ act(() => type(input, "pending"));
+ act(() => {
+ root.render(<SearchInput value="reset" onChange={onChange} />);
+ });
+ act(() => vi.advanceTimersByTime(300));
+
+ expect(input.value).toBe("reset");
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/components/ui/search-input.tsx b/frontend/src/components/ui/search-input.tsx
index 22f835014f..e9bffa7462 100644
--- a/frontend/src/components/ui/search-input.tsx
+++ b/frontend/src/components/ui/search-input.tsx
@@ -1,8 +1,15 @@
import { Search } from "lucide-react";
-import type { ComponentProps } from "react";
-import { forwardRef } from "react";
+import type { ChangeEvent, ComponentProps } from "react";
+import {
+ forwardRef,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
+import { DEBOUNCE_SEARCH_DELAY } from "@/types/common";
import { Input } from "./input";
type SearchInputProps = Omit<ComponentProps<typeof Input>, "className"> & {
@@ -10,12 +17,54 @@ type SearchInputProps = Omit<ComponentProps<typeof Input>, "className"> & {
wrapperClassName?: string;
};
+const stringifyInputValue = (
+ value: ComponentProps<typeof Input>["value"]
+): string => {
+ if (value === undefined || value === null) return "";
+ return Array.isArray(value) ? value.join(",") : String(value);
+};
+
export const SearchInput = forwardRef<HTMLInputElement, SearchInputProps>(
function SearchInput(
- { className, wrapperClassName, placeholder, style, ...props },
+ {
+ className,
+ wrapperClassName,
+ defaultValue,
+ onChange,
+ placeholder,
+ style,
+ value,
+ ...props
+ },
ref
) {
const { t } = useTranslation();
+ const [rawValue, setRawValue] = useState(() =>
+ stringifyInputValue(value ?? defaultValue)
+ );
+ const pendingChangeRef = useRef<ChangeEvent<HTMLInputElement> | undefined>(
+ undefined
+ );
+ const onChangeRef = useRef(onChange);
+ onChangeRef.current = onChange;
+
+ useLayoutEffect(() => {
+ if (value === undefined) return;
+ pendingChangeRef.current = undefined;
+ setRawValue(stringifyInputValue(value));
+ }, [value]);
+
+ useEffect(() => {
+ const event = pendingChangeRef.current;
+ if (!event) return;
+ const timer = window.setTimeout(() => {
+ if (pendingChangeRef.current !== event) return;
+ pendingChangeRef.current = undefined;
+ onChangeRef.current?.(event);
+ }, DEBOUNCE_SEARCH_DELAY);
+ return () => window.clearTimeout(timer);
+ }, [rawValue]);
+
return (
<div className={cn("relative flex-1", wrapperClassName)}>
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-control-placeholder pointer-events-none" />
@@ -25,6 +74,11 @@ export const SearchInput = forwardRef<HTMLInputElement, SearchInputProps>(
className={cn("pl-8", className)}
placeholder={placeholder ?? t("common.type-to-search")}
style={{ ...style, paddingInlineStart: "2rem" }}
+ value={rawValue}
+ onChange={(event) => {
+ pendingChangeRef.current = event;
+ setRawValue(event.target.value);
+ }}
{...props}
/>
</div>
diff --git a/frontend/src/hooks/useAppState.test.tsx b/frontend/src/hooks/useAppState.test.tsx
index db5de71676..75f976d832 100644
--- a/frontend/src/hooks/useAppState.test.tsx
+++ b/frontend/src/hooks/useAppState.test.tsx
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
loadCurrentUser: vi.fn(),
loadServerInfo: vi.fn(),
projectsByName: {} as Record<string, Project>,
+ searchProjects: vi.fn(),
}));
vi.mock("@/stores/app", () => ({
@@ -30,11 +31,12 @@ vi.mock("@/stores/app", () => ({
loadCurrentUser: mocks.loadCurrentUser,
loadServerInfo: mocks.loadServerInfo,
projectsByName: mocks.projectsByName,
+ searchProjects: mocks.searchProjects,
serverInfo: { saas: false },
}),
}));
-import { useRecentProjects } from "./useAppState";
+import { useProjectList, useRecentProjects } from "./useAppState";
const recentProjectsKey = storageKeyRecentProjects(
workspaceCacheScope(false, "workspaces/default"),
@@ -50,6 +52,32 @@ describe("useRecentProjects", () => {
mocks.getProjectByName.mockImplementation((name: string) => ({
name: name === "projects/default" ? name : "projects/-1",
}));
+ mocks.searchProjects.mockResolvedValue({
+ projects: [],
+ nextPageToken: "",
+ });
+ });
+
+ test("fetches an already-settled project query immediately", () => {
+ const { rerender } = renderHook(
+ ({ query }: { query: string }) => useProjectList(query),
+ { initialProps: { query: "alpha" } }
+ );
+
+ expect(mocks.searchProjects).toHaveBeenLastCalledWith({
+ pageSize: 50,
+ pageToken: "",
+ query: "alpha",
+ excludeDefault: true,
+ });
+
+ rerender({ query: "beta" });
+ expect(mocks.searchProjects).toHaveBeenLastCalledWith({
+ pageSize: 50,
+ pageToken: "",
+ query: "beta",
+ excludeDefault: true,
+ });
});
test("does not expose the unknown project placeholder for uncached recent projects", async () => {
diff --git a/frontend/src/hooks/useAppState.ts b/frontend/src/hooks/useAppState.ts
index cf65110d58..81e3649089 100644
--- a/frontend/src/hooks/useAppState.ts
+++ b/frontend/src/hooks/useAppState.ts
@@ -397,10 +397,7 @@ export function useProjectList(
);
useEffect(() => {
- const timer = window.setTimeout(() => {
- void fetchPage("refresh");
- }, 200);
- return () => window.clearTimeout(timer);
+ void fetchPage("refresh");
}, [fetchPage]);
const onPageSizeChange = useCallback((next: number) => {
diff --git a/frontend/src/hooks/usePagedData.test.tsx b/frontend/src/hooks/usePagedData.test.tsx
index e4befd0f11..6896c5c88f 100644
--- a/frontend/src/hooks/usePagedData.test.tsx
+++ b/frontend/src/hooks/usePagedData.test.tsx
@@ -92,8 +92,7 @@ describe("usePagedData", () => {
document.body.innerHTML = "";
});
- test("keeps loading while a debounced refresh is pending", async () => {
- vi.useFakeTimers();
+ test("refreshes immediately when the fetch function changes", async () => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
@@ -115,16 +114,7 @@ describe("usePagedData", () => {
await Promise.resolve();
});
- expect(container.querySelector("[data-state]")?.textContent).toBe(
- "loading"
- );
- expect(dataFetch).not.toHaveBeenCalled();
-
- await act(async () => {
- vi.advanceTimersByTime(300);
- await Promise.resolve();
- });
-
+ expect(dataFetch).toHaveBeenCalledOnce();
expect(container.querySelector("[data-state]")?.textContent).toBe(
"items/1"
);
@@ -332,7 +322,7 @@ describe("usePagedData", () => {
expect(container.querySelector("[data-state]")?.textContent).toBe(
"items/entry-1"
);
- expect(fetchList).toHaveBeenCalledOnce();
+ expect(fetchList).toHaveBeenCalledTimes(2);
});
test("consumes cache restoration once per history entry", async () => {
@@ -382,10 +372,6 @@ describe("usePagedData", () => {
"items/cached-100"
);
- await act(async () => {
- vi.advanceTimersByTime(300);
- await Promise.resolve();
- });
expect(fetchList).toHaveBeenCalledWith({ pageSize: 100, pageToken: "" });
expect(container.querySelector("[data-state]")?.textContent).toBe(
"items/current-100"
diff --git a/frontend/src/hooks/usePagedData.tsx b/frontend/src/hooks/usePagedData.tsx
index 885a5b996f..ffa53b4449 100644
--- a/frontend/src/hooks/usePagedData.tsx
+++ b/frontend/src/hooks/usePagedData.tsx
@@ -313,15 +313,7 @@ export function usePagedData<T extends { name: string }>({
doFetch(true);
return;
}
- fetchIdRef.current++;
- abortRef.current?.abort();
- dispatch({
- type: "fetch-start",
- mode: "refresh",
- cacheKey: activeCacheKeyRef.current,
- });
- const timer = setTimeout(() => doFetch(true), 300);
- return () => clearTimeout(timer);
+ doFetch(true);
}, [cacheRestoreToken, doFetch, enabled, resolvedCacheKey]);
useEffect(() => {
diff --git a/frontend/src/modules/schema-editor/Aside/AsideTree.tsx b/frontend/src/modules/schema-editor/Aside/AsideTree.tsx
index ab0d09aec5..3e08f2763b 100644
--- a/frontend/src/modules/schema-editor/Aside/AsideTree.tsx
+++ b/frontend/src/modules/schema-editor/Aside/AsideTree.tsx
@@ -1,5 +1,4 @@
import { create } from "@bufbuild/protobuf";
-import { debounce } from "lodash-es";
import {
ChevronDown,
ChevronRight,
@@ -88,11 +87,6 @@ export function AsideTree() {
const arboristData = useMemo(() => convertToArboristData(tree), [tree]);
- const handleSearchChange = useMemo(
- () => debounce((value: string) => setSearchPattern(value), 200),
- []
- );
-
// Context menu
const { menuState, menuOptions, showMenu, hideMenu } =
useContextMenu(editStatus);
@@ -575,7 +569,7 @@ export function AsideTree() {
<div className="sticky top-0 flex items-center gap-x-1 px-1 pt-1">
<SearchInput
placeholder={t("common.search")}
- onChange={(e) => handleSearchChange(e.target.value)}
+ onChange={(e) => setSearchPattern(e.target.value)}
className="h-7 flex-1"
/>
{createActions.length > 0 && (
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/tree.ts b/frontend/src/modules/sql-editor/components/ConnectionPane/tree.ts
index c251951001..b88add69a8 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/tree.ts
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/tree.ts
@@ -10,7 +10,6 @@ import type {
SQLEditorTreeNode,
StatefulSQLEditorTreeFactor as StatefulFactor,
} from "@/types";
-import { DEBOUNCE_SEARCH_DELAY } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
getDefaultPagination,
@@ -130,19 +129,6 @@ export function useSQLEditorTreeByEnvironment(
[storageKey]
);
- // Debounced fetch — mirror the Vue `useDebounceFn(..., DEBOUNCE_SEARCH_DELAY)` wrapper.
- const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
-
- useEffect(
- () => () => {
- if (debounceTimerRef.current !== null) {
- clearTimeout(debounceTimerRef.current);
- debounceTimerRef.current = null;
- }
- },
- []
- );
-
const fetchDatabasesImpl = useCallback(
async (filter?: DatabaseFilter) => {
setFetchDataState((prev) => ({ ...prev, loading: true }));
@@ -169,25 +155,13 @@ export function useSQLEditorTreeByEnvironment(
[fetchDatabaseList, project, environment]
);
- // Keep a ref to the latest fetchDataState so the debounced fn can read it
- // without resubscribing.
+ // Keep a ref to the latest page token for refresh and load-more requests.
const fetchDataStateRef = useRef(fetchDataState);
useEffect(() => {
fetchDataStateRef.current = fetchDataState;
}, [fetchDataState]);
- const fetchDatabases = useCallback(
- (filter?: DatabaseFilter): Promise<void> =>
- new Promise((resolve) => {
- if (debounceTimerRef.current !== null) {
- clearTimeout(debounceTimerRef.current);
- }
- debounceTimerRef.current = setTimeout(() => {
- void fetchDatabasesImpl(filter).finally(() => resolve());
- }, DEBOUNCE_SEARCH_DELAY);
- }),
- [fetchDatabasesImpl]
- );
+ const fetchDatabases = fetchDatabasesImpl;
const prepareDatabases = useCallback(
async (filter?: DatabaseFilter) => {
diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx
index b63a168483..11c07a3946 100644
--- a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx
+++ b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx
@@ -12,7 +12,7 @@ import { useTranslation } from "react-i18next";
import { EngineIcon } from "@/components/EngineIcon";
import { TableSchemaViewer } from "@/components/TableSchemaViewer";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
+import { SearchInput } from "@/components/ui/search-input";
import { Tree, type TreeDataNode } from "@/components/ui/tree";
import { countVisibleRows } from "@/components/ui/tree-utils";
import { cn } from "@/lib/utils";
@@ -55,7 +55,6 @@ import { Label } from "./TreeNode/Label";
const ROW_HEIGHT = 21;
const TREE_FALLBACK_HEIGHT = 360;
const FLAT_TABLE_THRESHOLD = 1000;
-const SEARCH_DEBOUNCE_MS = 200;
// Stable empty array reference used by the expandedKeys selector — a
// fresh `[]` per call would re-trigger Zustand subscribers on every
// store mutation.
@@ -108,7 +107,6 @@ function SchemaPaneInner() {
const panelViewState = currentTab?.viewState;
const [searchPattern, setSearchPattern] = useState("");
- const debouncedSearch = useDebouncedValue(searchPattern, SEARCH_DEBOUNCE_MS);
// Reset the search box on every tab switch — matches Vue's
// `watch(() => currentTab.value?.id, ...)`.
@@ -276,7 +274,7 @@ function SchemaPaneInner() {
}, [tree]);
const expandedKeySet = useMemo(() => new Set(expandedKeys), [expandedKeys]);
- const searchKeyword = debouncedSearch.trim();
+ const searchKeyword = searchPattern.trim();
const visibleRowCount = useMemo(() => {
if (!tree) return 0;
return tree.reduce(
@@ -428,7 +426,7 @@ function SchemaPaneInner() {
>
<div className="px-1 flex flex-row gap-1">
<div className="flex-1 overflow-hidden">
- <Input
+ <SearchInput
size="sm"
value={searchPattern}
placeholder={t("common.search")}
@@ -451,7 +449,7 @@ function SchemaPaneInner() {
totalTableCount > FLAT_TABLE_THRESHOLD ? (
<FlatTableList
metadata={metadata}
- search={debouncedSearch}
+ search={searchPattern}
database={database.name}
onSelect={onFlatSelect}
onSelectAll={onFlatSelectAll}
@@ -594,15 +592,6 @@ function defaultExpandedKeys(tree: SchemaTreeNode[]): string[] {
return keys;
}
-function useDebouncedValue<T>(value: T, delayMs: number): T {
- const [debounced, setDebounced] = useState(value);
- useEffect(() => {
- const id = setTimeout(() => setDebounced(value), delayMs);
- return () => clearTimeout(id);
- }, [value, delayMs]);
- return debounced;
-}
-
/**
* Direct re-export of `useSchemaPaneActions` so SchemaPaneInner can
* grab `selectAllFromTableOrView` for the double-click handler. The
diff --git a/frontend/src/modules/sql-editor/model/Sheet/context.ts b/frontend/src/modules/sql-editor/model/Sheet/context.ts
index 8cb21cad28..14147b752b 100644
--- a/frontend/src/modules/sql-editor/model/Sheet/context.ts
+++ b/frontend/src/modules/sql-editor/model/Sheet/context.ts
@@ -937,17 +937,6 @@ const fetchSheetListFor = async (view: SheetViewMode) => {
}
};
-const fetchSheetListDebounced: Partial<Record<SheetViewMode, () => void>> = {};
-const getFetchSheetListFn = (view: SheetViewMode): (() => void) => {
- const existed = fetchSheetListDebounced[view];
- if (existed) return existed;
- const debounced = debounce(() => {
- void fetchSheetListFor(view);
- }, DEBOUNCE_SEARCH_DELAY);
- fetchSheetListDebounced[view] = debounced;
- return debounced;
-};
-
const fetchNextSheetPageFor = async (
view: SheetViewMode,
folderKey?: string
@@ -1364,7 +1353,7 @@ const bindWatchers = () => {
) {
for (const view of ["my", "shared"] as const) {
if (state.viewStates[view].isInitialized) {
- getFetchSheetListFn(view)();
+ void fetchSheetListFor(view);
}
}
}
diff --git a/frontend/src/routes/project/ProjectSyncSchemaPage.test.tsx b/frontend/src/routes/project/ProjectSyncSchemaPage.test.tsx
index b4716621bf..7a5415c95a 100644
--- a/frontend/src/routes/project/ProjectSyncSchemaPage.test.tsx
+++ b/frontend/src/routes/project/ProjectSyncSchemaPage.test.tsx
@@ -201,9 +201,10 @@ describe("ProjectSyncSchemaPage target database search", () => {
afterEach(() => {
act(() => root.unmount());
container.remove();
+ vi.useRealTimers();
});
- test("uses the database name query for the first page and load more", async () => {
+ test("debounces the database name query and reuses it for load more", async () => {
act(() => {
root.render(<ProjectSyncSchemaPage projectId="project" />);
});
@@ -217,6 +218,8 @@ describe("ProjectSyncSchemaPage target database search", () => {
const searchInput = container.querySelector("input");
expect(searchInput).not.toBeNull();
+ const initialRequestCount = mocks.fetchDatabases.mock.calls.length;
+ vi.useFakeTimers();
act(() => {
Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
@@ -224,13 +227,22 @@ describe("ProjectSyncSchemaPage target database search", () => {
)?.set?.call(searchInput, "Payroll");
searchInput!.dispatchEvent(new Event("input", { bubbles: true }));
});
- await flush();
+
+ expect(mocks.fetchDatabases).toHaveBeenCalledTimes(initialRequestCount);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(299);
+ });
+ expect(mocks.fetchDatabases).toHaveBeenCalledTimes(initialRequestCount);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
expect(mocks.fetchDatabases).toHaveBeenCalledWith({
parent: "projects/project",
pageSize: 50,
filter: { engines: [1], query: "Payroll" },
});
+ vi.useRealTimers();
const loadMoreButton = Array.from(
container.querySelectorAll("button")
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
index 5ba1c436a1..1616cbef03 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -1773,8 +1773,7 @@ function DatabaseSelector({
);
useEffect(() => {
- const timer = setTimeout(() => void doFetch(true), 300);
- return () => clearTimeout(timer);
+ void doFetch(true);
}, [doFetch]);
const toggleDatabase = (name: string) => {
diff --git a/frontend/src/routes/workspace/ProjectsPage.tsx b/frontend/src/routes/workspace/ProjectsPage.tsx
index bbae166066..c3ba1b84d0 100644
--- a/frontend/src/routes/workspace/ProjectsPage.tsx
+++ b/frontend/src/routes/workspace/ProjectsPage.tsx
@@ -418,21 +418,15 @@ export function ProjectsPage() {
[isLoggedIn, pageSize, searchText, selectedState, selectedLabels, orderBy]
);
- // Fetch on mount + re-fetch on filter/sort/pageSize changes (debounced after first load)
+ // AdvancedSearch owns text debounce; settled filter and table changes fetch immediately.
const prevDepsRef = useRef<string>("");
- const isFirstLoad = useRef(true);
useEffect(() => {
const depsKey = `${searchText}|${stateFilter}|${selectedLabels.join(",")}|${pageSize}|${orderBy}`;
if (prevDepsRef.current === depsKey) return;
prevDepsRef.current = depsKey;
- if (isFirstLoad.current) {
- isFirstLoad.current = false;
- fetchProjects(true);
- return () => abortRef.current?.abort();
- }
- const timer = setTimeout(() => fetchProjects(true), 300);
- return () => clearTimeout(timer);
+ fetchProjects(true);
+ return () => abortRef.current?.abort();
}, [
searchText,
stateFilter,