Skip to the code

Search suggestions as you type

The header at Leaf and Kettle has a search box that suggests teas as you type. The suggestions come from a Route Handler that's already written, GET /api/teas/suggest?q=gre in app/api/teas/suggest/route.ts, which answers { teas: [{ slug, name }] }: up to five teas whose name contains the text. Write the box, app/components/tea-search.tsx, a Client Component whose default export is TeaSearch, the way a combobox works.

Render an input with role="combobox", aria-label="Search teas", aria-autocomplete="list", aria-controls="tea-suggestions", and aria-expanded saying whether the suggestions are showing.

300 ms after the customer stops typing, if the trimmed text is at least 2 characters long, fetch /api/teas/suggest?q= with the text, URL-encoded. Show the answer's teas in a list with role="listbox" and the id tea-suggestions, each tea's name in an element with role="option", an id of its own, and aria-selected. When no tea matches, show No teas match "coffee". instead. Shorter text shows no suggestions and fetches nothing.

When the text changes, abort the request in flight with an AbortController, so an older answer can never show over a newer one, or over a box that's been cleared.

Arrow Down and Arrow Up move the active option, wrapping around at the ends: from none, Arrow Down goes to the first and Arrow Up to the last. The active option has aria-selected="true", and the input's aria-activedescendant is its id; typing again leaves no option active. Enter on an active option, or a click on an option, goes to its page with router.push("/teas/<slug>") and closes the suggestions; Enter with no option active goes to /search?q= with the text. Escape closes the suggestions and keeps the text.

type "gre", 300 ms later   → GET /api/teas/suggest?q=gre
                             Green tea · Jasmine green · Earl Grey · Lady Grey   (aria-expanded="true")
↓ ↓                        → Jasmine green is active (aria-selected, aria-activedescendant)
Enter                      → router.push("/teas/jasmine-green")
type "coffee"              → No teas match "coffee".
type "earl gr", Enter      → router.push("/search?q=earl%20gr")

The app's other files

lib/teas.ts, read-only. Import it as @/lib/teas.

export type Tea = { slug: string; name: string };
 
const teas: Tea[] = [
  { slug: "green", name: "Green tea" },
  { slug: "jasmine-green", name: "Jasmine green" },
  { slug: "earl-grey", name: "Earl Grey" },
  { slug: "lady-grey", name: "Lady Grey" },
  { slug: "genmaicha", name: "Genmaicha" },
  { slug: "oolong", name: "Oolong tea" },
  { slug: "masala-chai", name: "Masala chai" },
  { slug: "mint", name: "Mint tea" },
];
 
/** Up to `limit` teas whose name contains `text`, ignoring case, in the shop's order. */
export async function searchTeas(text: string, limit: number): Promise<Tea[]> {
  const wanted = text.toLowerCase();
  return teas.filter((tea) => tea.name.toLowerCase().includes(wanted)).slice(0, limit);
}

app/api/teas/suggest/route.ts, read-only. Import it as @/app/api/teas/suggest/route.

import { NextResponse, type NextRequest } from "next/server";
import { searchTeas } from "@/lib/teas";
 
/** GET /api/teas/suggest?q=gre → { teas: [{ slug, name }] }: up to 5 teas whose name contains q. */
export async function GET(request: NextRequest) {
  const q = request.nextUrl.searchParams.get("q")?.trim() ?? "";
  const teas = q.length < 2 ? [] : await searchTeas(q, 5);
  return NextResponse.json({ teas });
}

app/components/site-header.tsx, read-only. Import it as @/app/components/site-header.

import Link from "next/link";
import TeaSearch from "./tea-search";
 
export default function SiteHeader() {
  return (
    <header>
      <Link href="/">Leaf and Kettle</Link>
      <TeaSearch />
    </header>
  );
}

What the tests check

  1. asks the Route Handler once typing pauses for 300 ms
    const renderOnServer = async (element, options) => {
      try {
        return await renderServer(element, options);
      } catch (error) {
        if (/reading 'use[A-Za-z]*'/.test(String(error && error.message))) {
          throw new Error('A component that calls hooks ran as a Server Component, where there are none. Does its file start with "use client"? (' + error.message + ")");
        }
        throw error;
      }
    };
    const clock = useFakeTimers();
    // The browser's fetch, answered by the app's own Route Handler after `latency` ms.
    let latency = 100;
    let reading = 0;
    const api = mockFetch(async (url) => {
      await new Promise((resolve) => setTimeout(resolve, latency));
      const response = await GET(request(url));
      // A browser reads a response's body in tasks of its own, which the fake clock doesn't run:
      // count the reads in progress, so elapse() can wait for them.
      for (const method of ["json", "text"]) {
        const read = response[method].bind(response);
        response[method] = () => {
          reading += 1;
          return read().finally(() => (reading -= 1));
        };
      }
      return response;
    });
    // Moves the clock on by ms, then gives the browser the turns it needs to finish reading answers.
    const elapse = async (ms) => {
      await clock.advance(ms);
      for (let turn = 0; turn < 100 && reading > 0; turn++) await flush();
      await flush();
    };
    const box = () => screen.getByRole("combobox", { name: "Search teas" });
    const options = () => screen.queryAllByRole("option").map((option) => option.textContent);
    const selected = () => screen.queryAllByRole("option").filter((option) => option.getAttribute("aria-selected") === "true").map((option) => option.textContent);
    const asked = () => api.calls.map((call) => new URL(call.url, "http://localhost:3000").searchParams.get("q"));
    const typeAndWait = async (text) => {
      await user.type(box(), text);
      await elapse(300 + latency);
    };
    await renderOnServer(<SiteHeader />);
    expect(box()).toHaveAttribute("aria-expanded", "false");
    await user.type(box(), "gre");
    await elapse(299);
    expect(api.calls).toHaveLength(0);
    await elapse(1);
    expect(asked()).toEqual(["gre"]);
    await elapse(100);
    expect(options()).toEqual(["Green tea", "Jasmine green", "Earl Grey", "Lady Grey"]);
    expect(screen.getByRole("listbox")).toHaveAttribute("id", "tea-suggestions");
    expect(box()).toHaveAttribute("aria-expanded", "true");
    expect(box()).toHaveAttribute("aria-controls", "tea-suggestions");
    expect(box()).toHaveAttribute("aria-autocomplete", "list");
    
  2. fetches nothing for under 2 characters, and says when nothing matches
    const clock = useFakeTimers();
    // The browser's fetch, answered by the app's own Route Handler after `latency` ms.
    let latency = 100;
    let reading = 0;
    const api = mockFetch(async (url) => {
      await new Promise((resolve) => setTimeout(resolve, latency));
      const response = await GET(request(url));
      // A browser reads a response's body in tasks of its own, which the fake clock doesn't run:
      // count the reads in progress, so elapse() can wait for them.
      for (const method of ["json", "text"]) {
        const read = response[method].bind(response);
        response[method] = () => {
          reading += 1;
          return read().finally(() => (reading -= 1));
        };
      }
      return response;
    });
    // Moves the clock on by ms, then gives the browser the turns it needs to finish reading answers.
    const elapse = async (ms) => {
      await clock.advance(ms);
      for (let turn = 0; turn < 100 && reading > 0; turn++) await flush();
      await flush();
    };
    const box = () => screen.getByRole("combobox", { name: "Search teas" });
    const options = () => screen.queryAllByRole("option").map((option) => option.textContent);
    const selected = () => screen.queryAllByRole("option").filter((option) => option.getAttribute("aria-selected") === "true").map((option) => option.textContent);
    const asked = () => api.calls.map((call) => new URL(call.url, "http://localhost:3000").searchParams.get("q"));
    const typeAndWait = async (text) => {
      await user.type(box(), text);
      await elapse(300 + latency);
    };
    render(<TeaSearch />);
    await typeAndWait("g ");
    expect(api.calls).toHaveLength(0);
    expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
    await user.clear(box());
    await typeAndWait("coffee");
    expect(asked()).toEqual(["coffee"]);
    expect(screen.getByText('No teas match "coffee".')).toBeInTheDocument();
    expect(options()).toEqual([]);
    expect(box()).toHaveAttribute("aria-expanded", "false");
    await user.clear(box());
    await typeAndWait("earl gr");
    expect(asked()).toEqual(["coffee", "earl gr"]);
    expect(options()).toEqual(["Earl Grey"]);
    
  3. aborts the request in flight when the text changes
    const clock = useFakeTimers();
    // The browser's fetch, answered by the app's own Route Handler after `latency` ms.
    let latency = 100;
    let reading = 0;
    const api = mockFetch(async (url) => {
      await new Promise((resolve) => setTimeout(resolve, latency));
      const response = await GET(request(url));
      // A browser reads a response's body in tasks of its own, which the fake clock doesn't run:
      // count the reads in progress, so elapse() can wait for them.
      for (const method of ["json", "text"]) {
        const read = response[method].bind(response);
        response[method] = () => {
          reading += 1;
          return read().finally(() => (reading -= 1));
        };
      }
      return response;
    });
    // Moves the clock on by ms, then gives the browser the turns it needs to finish reading answers.
    const elapse = async (ms) => {
      await clock.advance(ms);
      for (let turn = 0; turn < 100 && reading > 0; turn++) await flush();
      await flush();
    };
    const box = () => screen.getByRole("combobox", { name: "Search teas" });
    const options = () => screen.queryAllByRole("option").map((option) => option.textContent);
    const selected = () => screen.queryAllByRole("option").filter((option) => option.getAttribute("aria-selected") === "true").map((option) => option.textContent);
    const asked = () => api.calls.map((call) => new URL(call.url, "http://localhost:3000").searchParams.get("q"));
    const typeAndWait = async (text) => {
      await user.type(box(), text);
      await elapse(300 + latency);
    };
    latency = 500;
    render(<TeaSearch />);
    await user.type(box(), "gr");
    await elapse(300);
    expect(asked()).toEqual(["gr"]);
    await user.type(box(), "e");
    await elapse(300);
    expect(asked()).toEqual(["gr", "gre"]);
    expect(api.calls[0].init.signal?.aborted).toBe(true);
    expect(api.calls[1].init.signal?.aborted).toBe(false);
    await elapse(500);
    expect(options()).toEqual(["Green tea", "Jasmine green", "Earl Grey", "Lady Grey"]);
    // A new request, then the box is cleared before its answer comes.
    await user.type(box(), "y");
    await elapse(300);
    expect(asked()).toEqual(["gr", "gre", "grey"]);
    await user.clear(box());
    await elapse(1000);
    expect(api.calls[2].init.signal?.aborted).toBe(true);
    expect(options()).toEqual([]);
    expect(box()).toHaveAttribute("aria-expanded", "false");
    
  4. the arrow keys move the active option, wrapping around
    const clock = useFakeTimers();
    // The browser's fetch, answered by the app's own Route Handler after `latency` ms.
    let latency = 100;
    let reading = 0;
    const api = mockFetch(async (url) => {
      await new Promise((resolve) => setTimeout(resolve, latency));
      const response = await GET(request(url));
      // A browser reads a response's body in tasks of its own, which the fake clock doesn't run:
      // count the reads in progress, so elapse() can wait for them.
      for (const method of ["json", "text"]) {
        const read = response[method].bind(response);
        response[method] = () => {
          reading += 1;
          return read().finally(() => (reading -= 1));
        };
      }
      return response;
    });
    // Moves the clock on by ms, then gives the browser the turns it needs to finish reading answers.
    const elapse = async (ms) => {
      await clock.advance(ms);
      for (let turn = 0; turn < 100 && reading > 0; turn++) await flush();
      await flush();
    };
    const box = () => screen.getByRole("combobox", { name: "Search teas" });
    const options = () => screen.queryAllByRole("option").map((option) => option.textContent);
    const selected = () => screen.queryAllByRole("option").filter((option) => option.getAttribute("aria-selected") === "true").map((option) => option.textContent);
    const asked = () => api.calls.map((call) => new URL(call.url, "http://localhost:3000").searchParams.get("q"));
    const typeAndWait = async (text) => {
      await user.type(box(), text);
      await elapse(300 + latency);
    };
    render(<TeaSearch />);
    await typeAndWait("grey");
    expect(options()).toEqual(["Earl Grey", "Lady Grey"]);
    expect(selected()).toEqual([]);
    await user.keyboard("{ArrowDown}");
    expect(selected()).toEqual(["Earl Grey"]);
    const earl = screen.getByRole("option", { name: "Earl Grey" });
    expect(earl.id).not.toBe("");
    expect(box()).toHaveAttribute("aria-activedescendant", earl.id);
    await user.keyboard("{ArrowDown}");
    expect(selected()).toEqual(["Lady Grey"]);
    expect(box()).toHaveAttribute("aria-activedescendant", screen.getByRole("option", { name: "Lady Grey" }).id);
    await user.keyboard("{ArrowDown}");
    expect(selected()).toEqual(["Earl Grey"]);
    await user.keyboard("{ArrowUp}");
    expect(selected()).toEqual(["Lady Grey"]);
    await typeAndWait("{Backspace}");
    expect(options()).toEqual(["Green tea", "Jasmine green", "Earl Grey", "Lady Grey"]);
    expect(selected()).toEqual([]);
    await user.keyboard("{ArrowUp}");
    expect(selected()).toEqual(["Lady Grey"]);
    
  5. Enter opens the active tea, or searches for the text
    const clock = useFakeTimers();
    // The browser's fetch, answered by the app's own Route Handler after `latency` ms.
    let latency = 100;
    let reading = 0;
    const api = mockFetch(async (url) => {
      await new Promise((resolve) => setTimeout(resolve, latency));
      const response = await GET(request(url));
      // A browser reads a response's body in tasks of its own, which the fake clock doesn't run:
      // count the reads in progress, so elapse() can wait for them.
      for (const method of ["json", "text"]) {
        const read = response[method].bind(response);
        response[method] = () => {
          reading += 1;
          return read().finally(() => (reading -= 1));
        };
      }
      return response;
    });
    // Moves the clock on by ms, then gives the browser the turns it needs to finish reading answers.
    const elapse = async (ms) => {
      await clock.advance(ms);
      for (let turn = 0; turn < 100 && reading > 0; turn++) await flush();
      await flush();
    };
    const box = () => screen.getByRole("combobox", { name: "Search teas" });
    const options = () => screen.queryAllByRole("option").map((option) => option.textContent);
    const selected = () => screen.queryAllByRole("option").filter((option) => option.getAttribute("aria-selected") === "true").map((option) => option.textContent);
    const asked = () => api.calls.map((call) => new URL(call.url, "http://localhost:3000").searchParams.get("q"));
    const typeAndWait = async (text) => {
      await user.type(box(), text);
      await elapse(300 + latency);
    };
    render(<TeaSearch />);
    await typeAndWait("gre");
    await user.keyboard("{ArrowDown}{ArrowDown}{Enter}");
    expect(router.calls).toEqual([{ method: "push", href: "/teas/jasmine-green", options: {} }]);
    expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
    expect(box()).toHaveAttribute("aria-expanded", "false");
    await user.clear(box());
    await typeAndWait("earl gr");
    await user.keyboard("{Enter}");
    expect(router.pathname).toBe("/search");
    expect(router.searchParams.get("q")).toBe("earl gr");
    
  6. Escape closes the suggestions and keeps the text, and a click opens a tea
    const clock = useFakeTimers();
    // The browser's fetch, answered by the app's own Route Handler after `latency` ms.
    let latency = 100;
    let reading = 0;
    const api = mockFetch(async (url) => {
      await new Promise((resolve) => setTimeout(resolve, latency));
      const response = await GET(request(url));
      // A browser reads a response's body in tasks of its own, which the fake clock doesn't run:
      // count the reads in progress, so elapse() can wait for them.
      for (const method of ["json", "text"]) {
        const read = response[method].bind(response);
        response[method] = () => {
          reading += 1;
          return read().finally(() => (reading -= 1));
        };
      }
      return response;
    });
    // Moves the clock on by ms, then gives the browser the turns it needs to finish reading answers.
    const elapse = async (ms) => {
      await clock.advance(ms);
      for (let turn = 0; turn < 100 && reading > 0; turn++) await flush();
      await flush();
    };
    const box = () => screen.getByRole("combobox", { name: "Search teas" });
    const options = () => screen.queryAllByRole("option").map((option) => option.textContent);
    const selected = () => screen.queryAllByRole("option").filter((option) => option.getAttribute("aria-selected") === "true").map((option) => option.textContent);
    const asked = () => api.calls.map((call) => new URL(call.url, "http://localhost:3000").searchParams.get("q"));
    const typeAndWait = async (text) => {
      await user.type(box(), text);
      await elapse(300 + latency);
    };
    render(<TeaSearch />);
    await typeAndWait("gre");
    await user.keyboard("{Escape}");
    expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
    expect(box()).toHaveAttribute("aria-expanded", "false");
    expect(box()).toHaveValue("gre");
    await typeAndWait("e");
    expect(options()).toEqual(["Green tea", "Jasmine green"]);
    await user.click(screen.getByRole("option", { name: "Jasmine green" }));
    expect(router.calls.map((call) => call.href)).toEqual(["/teas/jasmine-green"]);
    expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
    

Learn more

app/components/tea-search.tsxSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).