From 2bdc32e3deacb5b8381bc1ea631c885a34de84ea Mon Sep 17 00:00:00 2001 From: Andreas Schultz Date: Wed, 18 Nov 2026 12:07:30 +0100 Subject: [PATCH] Ignore stale autocomplete responses - Invalidate pending searches and pagination when the query or search context changes. - Prevent overlapping page loads - add regression tests for stale search and pagination responses --- .../AutoCompleteField.test.tsx | 78 ++++++++++- .../AutocompleteField/AutoCompleteField.tsx | 132 ++++++++++++------ 2 files changed, 167 insertions(+), 43 deletions(-) diff --git a/src/components/AutocompleteField/AutoCompleteField.test.tsx b/src/components/AutocompleteField/AutoCompleteField.test.tsx index 709a8e78..30f66908 100644 --- a/src/components/AutocompleteField/AutoCompleteField.test.tsx +++ b/src/components/AutocompleteField/AutoCompleteField.test.tsx @@ -1,5 +1,5 @@ import React from "react"; -import { fireEvent, render, screen } from "@testing-library/react"; +import { act, fireEvent, render, screen } from "@testing-library/react"; import "@testing-library/jest-dom"; @@ -24,4 +24,80 @@ describe("SuggestField", () => { expect(listbox.querySelectorAll('[role="option"]')).toHaveLength(1); expect(listbox.querySelectorAll('[role="menuitem"]')).toHaveLength(0); }); + + it("ignores an old result as soon as the query changes", async () => { + jest.useFakeTimers(); + try { + let resolveFirst!: (items: string[]) => void; + const first = new Promise((resolve) => { + resolveFirst = resolve; + }); + const onSearch = jest.fn((query: string) => (query === "first" ? first : Promise.resolve(["New choice"]))); + render( + + onSearch={onSearch} + itemRenderer={(item) => item} + itemValueRenderer={(item) => item} + itemValueSelector={(item) => item} + itemValueString={(item) => item} + noResultText="No results" + />, + ); + const input = screen.getByRole("combobox"); + act(() => input.focus()); + fireEvent.change(input, { target: { value: "first" } }); + await act(async () => jest.advanceTimersByTime(200)); + expect(onSearch).toHaveBeenCalledTimes(1); + + fireEvent.change(input, { target: { value: "second" } }); + await act(async () => resolveFirst(["Old choice"])); + expect(onSearch).toHaveBeenCalledTimes(1); + expect(screen.queryByRole("option", { name: "Old choice" })).not.toBeInTheDocument(); + expect(screen.getByRole("progressbar")).toBeVisible(); + + await act(async () => jest.advanceTimersByTime(200)); + expect(screen.getByRole("option", { name: "New choice" })).toBeVisible(); + } finally { + jest.useRealTimers(); + } + }); + + it("does not append a pending page to the next search", async () => { + jest.useFakeTimers(); + try { + let resolvePage!: (items: string[]) => void; + const page = new Promise((resolve) => { + resolvePage = resolve; + }); + const loadMoreResults = jest.fn(() => page); + render( + + onSearch={(query) => (query ? ["Current choice"] : ["Initial choice"])} + loadMoreResults={loadMoreResults} + itemRenderer={(item) => item} + itemValueRenderer={(item) => item} + itemValueSelector={(item) => item} + itemValueString={(item) => item} + noResultText="No results" + />, + ); + const input = screen.getByRole("combobox"); + act(() => input.focus()); + await act(async () => jest.advanceTimersByTime(200)); + + const listbox = screen.getByRole("listbox"); + fireEvent.scroll(listbox); + fireEvent.scroll(listbox); + expect(loadMoreResults).toHaveBeenCalledTimes(1); + fireEvent.change(input, { target: { value: "next" } }); + await act(async () => jest.advanceTimersByTime(200)); + expect(screen.getByRole("option", { name: "Current choice" })).toBeVisible(); + + await act(async () => resolvePage(["Stale page"])); + expect(screen.queryByRole("option", { name: "Stale page" })).not.toBeInTheDocument(); + expect(screen.getByRole("option", { name: "Current choice" })).toBeVisible(); + } finally { + jest.useRealTimers(); + } + }); }); diff --git a/src/components/AutocompleteField/AutoCompleteField.tsx b/src/components/AutocompleteField/AutoCompleteField.tsx index e8027a48..1c248db3 100644 --- a/src/components/AutocompleteField/AutoCompleteField.tsx +++ b/src/components/AutocompleteField/AutoCompleteField.tsx @@ -18,8 +18,13 @@ import { OverflowText } from "../Typography/OverflowText"; import { SuggestFieldItemRendererModifierProps } from "./interfaces"; -type SearchFunction = (value: string) => T[]; -type AsyncSearchFunction = (value: string) => Promise; +type SearchFunction = (value: string, isCurrent: () => boolean) => T[] | Promise; + +function errorDetails(error: unknown): string { + return error && typeof error === "object" && "message" in error && typeof error.message === "string" + ? error.message + : ""; +} /** * Parameters for the auto-complete field parameterized by T and U. @@ -32,9 +37,11 @@ export interface SuggestFieldProps { */ className?: string; /** - * Fired when text is typed into the input field. Returns a list of items of type T. + * Returns suggestions for the input text. Call isCurrent before applying any caller-owned side effects. */ - onSearch: SearchFunction | AsyncSearchFunction; + onSearch: SearchFunction; + /** Change this key when the same search query may return different results, e.g. after switching projects. */ + searchContextKey?: string; /** * Fired when value selected from input @@ -155,8 +162,8 @@ export interface SuggestFieldProps { * Use the full available width of the parent container. */ fill?: boolean; - /** Utility that fetches more options when clicked*/ - loadMoreResults?: () => Promise; + /** Fetches more options for the current search. */ + loadMoreResults?: (isCurrent: () => boolean) => Promise; } /** @@ -182,6 +189,7 @@ export function SuggestField(props: SuggestFieldProps(props: SuggestFieldProps(false); - const [query, setQuery] = useState(""); + const [queryState, setQuery] = useState({ text: "" }); + const query = queryState.text; + const currentQuery = React.useRef(""); + const activeSearch = React.useRef<{ ready: boolean; pagePending: boolean }>(); // If the input field has focus const [inputHasFocus, setInputHasFocus] = useState(false); const [highlightingEnabled, setHighlightingEnabled] = useState(true); @@ -210,6 +221,14 @@ export function SuggestField(props: SuggestFieldProps { + if (currentQuery.current !== nextQuery) { + currentQuery.current = nextQuery; + activeSearch.current = undefined; + setQuery({ text: nextQuery }); + } + }; + // Sets the query to the item value if it has a valid string value const setQueryToSelectedValue = (item?: T) => { if (item) { @@ -219,7 +238,7 @@ export function SuggestField(props: SuggestFieldProps(props: SuggestFieldProps { - if (!disabled && !readOnly && inputHasFocus) { - setListLoading(true); - const timeout: number = window.setTimeout(async () => { - fetchQueryResults(query); - }, 200); - return () => { - clearTimeout(timeout); - setListLoading(false); - }; + React.useLayoutEffect(() => { + if (disabled || readOnly || !inputHasFocus) { + setListLoading(false); + return; } - return; - }, [inputHasFocus, query]); + const search = { ready: false, pagePending: false }; + activeSearch.current = search; + const isCurrent = () => activeSearch.current === search; + setListLoading(true); + setRequestError(undefined); + const timeout = window.setTimeout(async () => { + if (isCurrent()) { + search.ready = await fetchQueryResults(query, isCurrent); + } + }, 200); + return () => { + window.clearTimeout(timeout); + if (isCurrent()) activeSearch.current = undefined; + }; + }, [inputHasFocus, queryState, disabled, readOnly, searchContextKey]); // We need to fire some actions when the auto-complete widget gets or loses focus const handleOnFocusIn = () => { @@ -252,6 +278,7 @@ export function SuggestField(props: SuggestFieldProps { + activeSearch.current = undefined; setInputHasFocus(false); }; @@ -285,11 +312,10 @@ export function SuggestField(props: SuggestFieldProps { - setListLoading(true); - setRequestError(undefined); + const fetchQueryResults = async (input: string, isCurrent: () => boolean): Promise => { try { - let result = await onSearch(input); + let result = await onSearch(input, isCurrent); + if (!isCurrent()) return false; const onlySelectItemReturned = result.length <= 1 && selectedItem && @@ -298,7 +324,8 @@ export function SuggestField(props: SuggestFieldProps(props: SuggestFieldProps(props: SuggestFieldProps () => { setSelectedItem(undefined); onChange?.(resetValue); - setQuery(""); + updateQuery(""); }; const requestErrorRenderer = () => { return ; @@ -446,22 +476,40 @@ export function SuggestField(props: SuggestFieldProps { - const menu = event.target; + async (event: React.UIEvent) => { + const menu = event.currentTarget; const { scrollTop, scrollHeight, clientHeight } = menu; + const search = activeSearch.current; // Check if scrolled to the bottom of the list - if (Math.round(scrollTop + clientHeight) >= scrollHeight && loadMoreResults) { - const results = await loadMoreResults(); - if (results) { - setFiltered((prev) => [...prev, ...results]); - setTimeout(() => { - menu.scrollTop = scrollTop; //safari adaptation - menu.scrollTo({ left: 0, top: scrollTop, behavior: "auto" }); - }); + if ( + Math.round(scrollTop + clientHeight) >= scrollHeight && + loadMoreResults && + search?.ready && + !search.pagePending + ) { + const isCurrent = () => activeSearch.current === search; + search.pagePending = true; + try { + const results = await loadMoreResults(isCurrent); + if (results && isCurrent()) { + setFiltered((prev) => [...prev, ...results]); + setTimeout(() => { + if (isCurrent()) { + menu.scrollTop = scrollTop; // Safari adaptation + menu.scrollTo({ left: 0, top: scrollTop, behavior: "auto" }); + } + }); + } + } catch (error) { + if (isCurrent()) { + setRequestError(requestErrorPrefix + errorDetails(error)); + } + } finally { + search.pagePending = false; } } }, - [loadMoreResults], + [loadMoreResults, requestErrorPrefix], ); return ( @@ -476,7 +524,7 @@ export function SuggestField(props: SuggestFieldProps} onItemSelect={onSelectionChange} - onQueryChange={(q) => setQuery(q)} + onQueryChange={updateQuery} resetOnQuery={false} closeOnSelect={true} menuProps={{