diff --git a/site/src/components/Filter/FilterCombobox/FilterCombobox.stories.tsx b/site/src/components/Filter/FilterCombobox/FilterCombobox.stories.tsx index 1137b5ccc47..13e78c4f1e0 100644 --- a/site/src/components/Filter/FilterCombobox/FilterCombobox.stories.tsx +++ b/site/src/components/Filter/FilterCombobox/FilterCombobox.stories.tsx @@ -619,6 +619,169 @@ export const TypedInlinePrefix: Story = { }, }; +const singleTemplateCategories: FilterCategory[] = [ + { + key: "owner", + label: "Owner", + icon: , + getOptions: async (query) => filterOptions(ownerOptions, query), + }, + { + key: "template", + label: "Template", + icon: , + hideWhenSingleOption: true, + getOptions: async (query) => + filterOptions(templateOptions.slice(0, 1), query), + }, +]; + +const openFilterMenu = async (canvasElement: HTMLElement) => { + await userEvent.click( + within(canvasElement).getByRole("button", { name: "Filters" }), + ); + await within(canvasElement.ownerDocument.body).findByRole("option", { + name: "Owner", + }); +}; + +// Template has one option, so the menu omits it. +export const SingleOptionCategoryHidden: Story = { + render: () => ( + + ), + play: ({ canvasElement }) => openFilterMenu(canvasElement), +}; + +// Placeholder rows hold the category list until Template's options load. +export const CategoryListLoading: Story = { + render: () => ( + new Promise(() => {}), + }, + ]} + /> + ), + play: async ({ canvasElement }) => { + await userEvent.click( + within(canvasElement).getByRole("button", { name: "Filters" }), + ); + }, +}; + +// Template settled at one option while Organization still loads, so the +// placeholders keep one row per submenu category. +export const CategoryListLoadingAfterOneSettles: Story = { + render: () => ( + , + hideWhenSingleOption: true, + getOptions: () => new Promise(() => {}), + }, + ]} + /> + ), + play: async ({ canvasElement }) => { + await userEvent.click( + within(canvasElement).getByRole("button", { name: "Filters" }), + ); + }, +}; + +// A category opened while Template's options load shows the category rows +// beside its options, not placeholder rows. +export const CategoryOpenWhileCategoryListLoads: Story = { + render: () => ( + new Promise(() => {}), + }, + ]} + /> + ), + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const input = canvas.getByRole("combobox", { name: "Search and filter…" }); + await userEvent.click(input); + await userEvent.type(input, "owner:"); + }, +}; + +// The template:docker chip keeps Template listed. +export const SingleOptionCategoryWithChip: Story = { + render: () => ( + + ), + play: ({ canvasElement }) => openFilterMenu(canvasElement), +}; + +// Template's options failed to load, so it stays in the menu to offer a retry. +export const SingleOptionCategoryLoadFailed: Story = { + render: () => ( + { + throw new Error("Failed to load templates"); + }, + }, + ]} + /> + ), + play: ({ canvasElement }) => openFilterMenu(canvasElement), +}; + +// A Retry that returns one option hides Template and closes its flyout. +export const SingleOptionCategoryRetried: Story = { + render: () => { + let thrown = false; + const categories: FilterCategory[] = [ + singleTemplateCategories[0], + { + ...singleTemplateCategories[1], + getOptions: async (query) => { + if (!thrown) { + thrown = true; + throw new Error("Failed to load templates"); + } + return singleTemplateCategories[1].getOptions(query); + }, + }, + ]; + return ; + }, + play: async ({ canvasElement }) => { + const body = within(canvasElement.ownerDocument.body); + await openFilterMenu(canvasElement); + await userEvent.hover(body.getByRole("option", { name: "Template" })); + await userEvent.click(await body.findByRole("button", { name: "Retry" })); + }, +}; + // Escape closes the popup without clearing the committed chips. export const DismissOnEscape: Story = { render: () => , @@ -700,16 +863,11 @@ export const CategoryOptionsErrorRetry: Story = { }); await userEvent.click(input); await userEvent.type(input, "status:"); - await expect( - await body.findByText(/Couldn.t load Status options/, { - ignore: '[role="status"], script, style', - }), - ).toBeVisible(); - await expect(body.getByRole("status")).toHaveTextContent( - /Couldn.t load Status options/, - ); + await body.findByText(/Couldn.t load Status options/, { + ignore: '[role="status"], script, style', + }); await userEvent.click(body.getByRole("button", { name: /retry/i })); - await waitFor(() => expect(body.getByText("Running")).toBeVisible()); + await body.findByText("Running"); }, }; @@ -836,18 +994,11 @@ export const TypeaheadErrorRetry: Story = { }); await userEvent.click(input); await userEvent.type(input, "alice"); - await expect( - await body.findByText(/Couldn.t load suggestions/, { - ignore: '[role="status"], script, style', - }), - ).toBeVisible(); - await expect(body.getByRole("status")).toHaveTextContent( - /Couldn.t load suggestions/, - ); + await body.findByText(/Couldn.t load suggestions/, { + ignore: '[role="status"], script, style', + }); await userEvent.click(body.getByRole("button", { name: /retry/i })); - await waitFor(() => - expect(body.getByRole("option", { name: /alice/i })).toBeVisible(), - ); + await body.findByRole("option", { name: /alice/i }); }, }; diff --git a/site/src/components/Filter/FilterCombobox/FilterCombobox.test.tsx b/site/src/components/Filter/FilterCombobox/FilterCombobox.test.tsx index e3227d0e983..9289c4e3aca 100644 --- a/site/src/components/Filter/FilterCombobox/FilterCombobox.test.tsx +++ b/site/src/components/Filter/FilterCombobox/FilterCombobox.test.tsx @@ -3,7 +3,11 @@ import userEvent from "@testing-library/user-event"; import { useState } from "react"; import { render } from "#/testHelpers/renderHelpers"; import { mobileViewportMediaQuery } from "#/utils/mobile"; -import { FilterCombobox, SEARCHABLE_OPTION_COUNT } from "./FilterCombobox"; +import { + CATEGORY_HOVER_DELAY_MS, + FilterCombobox, + SEARCHABLE_OPTION_COUNT, +} from "./FilterCombobox"; import { SEARCH_DEBOUNCE_MS } from "./queries"; import type { FilterCategory, FilterOption } from "./types"; import { @@ -175,6 +179,448 @@ describe("FilterCombobox", () => { await flushTimers(); }; + it("fetches hideable categories before the menu opens and skips others", async () => { + const hideable = vi.fn(async () => [{ label: "Docker", value: "docker" }]); + const other = vi.fn(async () => [{ label: "alice", value: "alice" }]); + render( + , + ); + await waitFor(() => expect(hideable).toHaveBeenCalledWith("")); + expect(other).not.toHaveBeenCalled(); + }); + + it("announces loading until hideable categories load, then offers them", async () => { + const templates = heldSearch( + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => [], + }, + "", + ); + const { user, onChange, filtersButton } = setup([ + templates.category, + ownerCategory, + ]); + + await user.click(filtersButton); + expect(screen.getByRole("status")).toHaveTextContent("Loading filters"); + await act(async () => + templates.resolve([ + { label: "docker", value: "docker" }, + { label: "k8s", value: "k8s" }, + ]), + ); + await screen.findByRole("option", { name: "Template" }); + await user.keyboard("{Home}{ArrowRight}"); + await user.click(await screen.findByRole("option", { name: "k8s" })); + + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("template:k8s"), + ); + }); + + it("highlights the first category once placeholder rows are replaced", async () => { + const templates = heldSearch( + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => [], + }, + "", + ); + const { user, onChange, filtersButton } = setup([ + ownerCategory, + templates.category, + statusCategory, + ]); + + await user.click(filtersButton); + await screen.findByRole("option", { name: /Running/ }); + await act(async () => + templates.resolve([ + { label: "docker", value: "docker" }, + { label: "k8s", value: "k8s" }, + ]), + ); + await screen.findByRole("option", { name: "Template" }); + await user.keyboard("{Enter}"); + await screen.findByRole("option", { name: "alice" }); + await user.keyboard("{ArrowDown}{Enter}"); + + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("owner:alice"), + ); + }); + + it("keeps a highlight moved to an inline row while placeholder rows show", async () => { + const templates = heldSearch( + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => [], + }, + "", + ); + const { user, onChange, filtersButton } = setup([ + ownerCategory, + templates.category, + statusCategory, + ]); + + await user.click(filtersButton); + await screen.findByRole("option", { name: /Running/ }); + await user.keyboard("{ArrowDown}"); + await act(async () => + templates.resolve([ + { label: "docker", value: "docker" }, + { label: "k8s", value: "k8s" }, + ]), + ); + await screen.findByRole("option", { name: "Template" }); + await user.keyboard("{Enter}"); + + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("status:running"), + ); + }); + + it("matches typed text to a hideable category while its options load", async () => { + const templates = heldSearch( + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => [], + }, + "", + ); + const { user, onChange, input } = setup([ + ownerCategory, + templates.category, + ]); + + await user.click(input); + await user.type(input, "tem"); + await user.keyboard("{ArrowDown}{Enter}"); + await act(async () => + templates.resolve([ + { label: "docker", value: "docker" }, + { label: "k8s", value: "k8s" }, + ]), + ); + await user.click(await screen.findByRole("option", { name: "k8s" })); + + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("template:k8s"), + ); + }); + + it("announces the error of a hideable category whose options failed to load", async () => { + const { user, filtersButton } = setup([ + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => { + throw new Error("failed"); + }, + }, + ownerCategory, + ]); + + await user.click(filtersButton); + await screen.findByRole("option", { name: "Template" }); + await user.keyboard("{Home}{ArrowRight}"); + + await waitFor(() => + expect(screen.getByRole("status")).toHaveTextContent( + "Couldn’t load Template options.", + ), + ); + }); + + it("keeps the category list through a hideable category's Retry", async () => { + let failed = false; + const retry = Promise.withResolvers(); + const { user, onChange, filtersButton } = setup( + [ + ownerCategory, + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => { + if (!failed) { + failed = true; + throw new Error("failed"); + } + return retry.promise; + }, + }, + ], + { skipHover: true }, + ); + + await user.click(filtersButton); + await user.hover(await screen.findByRole("option", { name: "Template" })); + await user.click(await screen.findByRole("button", { name: "Retry" })); + expect(screen.getByRole("status")).not.toHaveTextContent("Loading filters"); + await user.hover(screen.getByRole("option", { name: "Template" })); + await act(async () => + retry.resolve([ + { label: "docker", value: "docker" }, + { label: "k8s", value: "k8s" }, + ]), + ); + await user.click(await screen.findByRole("button", { name: "k8s" })); + + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("template:k8s"), + ); + }); + + it("ignores hidden options for suggestions but keeps hidden categories reachable by name and prefix", async () => { + const getOptions = vi.fn(async (query: string) => + [{ label: "Docker", value: "docker" }].filter((option) => + option.label.toLowerCase().includes(query.toLowerCase()), + ), + ); + const { user, input, onChange } = setup( + [ + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions, + }, + ], + { fakeTimers: true }, + ); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + expect(onChange).toHaveBeenLastCalledWith("dock"); + expect(getOptions).not.toHaveBeenCalledWith("dock"); + await user.keyboard("{ArrowDown}{Enter}"); + expect(onChange).not.toHaveBeenCalledWith("template:docker"); + + await user.clear(input); + await user.type(input, "templ"); + await settleTypedText(); + expect(onChange).not.toHaveBeenCalledWith("templ"); + + await user.clear(input); + await user.type(input, "template:"); + await user.click(await screen.findByRole("option", { name: "Docker" })); + expect(onChange).toHaveBeenLastCalledWith("template:docker"); + }); + + const docker = { label: "Docker", value: "docker" }; + + const setupDeferredTemplateLoads = ( + initialValue: string, + { + category = {}, + getFilteredOptions = () => Promise.resolve([docker]), + skipHover = false, + // A clock that follows real time lets a slow run fire the lookup timeout + // before a deferred load settles. + shouldAdvanceTime = false, + }: { + category?: Partial; + getFilteredOptions?: (query: string) => Promise; + skipHover?: boolean; + shouldAdvanceTime?: boolean; + } = {}, + ) => { + const [firstLoad, retryLoad] = [ + Promise.withResolvers(), + Promise.withResolvers(), + ]; + let unfilteredLoads = 0; + const rendered = setup( + [ + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: (query) => { + if (query !== "") { + return getFilteredOptions(query); + } + unfilteredLoads += 1; + return unfilteredLoads === 1 + ? firstLoad.promise + : retryLoad.promise; + }, + ...category, + }, + ], + { + initialValue, + fakeTimers: shouldAdvanceTime ? true : "manual", + skipHover, + }, + ); + return { ...rendered, firstLoad, retryLoad }; + }; + + it("searches text matching a hideable category whose first load settles at one option", async () => { + const { user, input, onChange, firstLoad } = setupDeferredTemplateLoads(""); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + await act(async () => firstLoad.resolve([docker])); + + expect(onChange).toHaveBeenLastCalledWith("dock"); + }); + + it("holds back text matching a hideable category whose first load settles at one option with its chip", async () => { + const { user, input, onChange, firstLoad } = + setupDeferredTemplateLoads("template:docker"); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + await act(async () => firstLoad.resolve([docker])); + await act(() => vi.advanceTimersByTimeAsync(TYPED_TEXT_LOOKUP_TIMEOUT_MS)); + + expect(onChange).not.toHaveBeenCalledWith("template:docker dock"); + }); + + it("searches text matching a hideable category whose chip is removed before its first load settles", async () => { + const { user, input, onChange, firstLoad } = + setupDeferredTemplateLoads("template:docker"); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + await user.click( + screen.getByRole("button", { name: "Remove template:docker" }), + ); + await act(async () => firstLoad.resolve([docker])); + + expect(onChange).toHaveBeenLastCalledWith("dock"); + }); + + it("holds back text matching a hideable category when its first load and lookup each fit the timeout but their sum does not", async () => { + const loadMs = TYPED_TEXT_LOOKUP_TIMEOUT_MS * 0.8; + const lookupMs = TYPED_TEXT_LOOKUP_TIMEOUT_MS * 0.4; + const { user, input, onChange, firstLoad } = setupDeferredTemplateLoads( + "", + { + getFilteredOptions: () => + new Promise((resolve) => setTimeout(resolve, lookupMs, [docker])), + }, + ); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + await act(() => vi.advanceTimersByTimeAsync(loadMs)); + await act(async () => + firstLoad.resolve([ + { label: "Docker", value: "docker" }, + { label: "Kubernetes", value: "kubernetes" }, + ]), + ); + await act(() => vi.advanceTimersByTimeAsync(TYPED_TEXT_LOOKUP_TIMEOUT_MS)); + + expect(onChange).not.toHaveBeenCalledWith("dock"); + }); + + it("holds back text matching a hideable category whose first load fails", async () => { + const { user, input, onChange, firstLoad } = setupDeferredTemplateLoads(""); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + await act(async () => firstLoad.reject(new Error("boom"))); + await act(() => vi.advanceTimersByTimeAsync(TYPED_TEXT_LOOKUP_TIMEOUT_MS)); + + expect(onChange).not.toHaveBeenCalledWith("dock"); + }); + + it("holds back text matching a hideable category whose first load already failed", async () => { + const { user, input, onChange, firstLoad } = setupDeferredTemplateLoads(""); + await act(async () => firstLoad.reject(new Error("boom"))); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + await act(() => vi.advanceTimersByTimeAsync(TYPED_TEXT_LOOKUP_TIMEOUT_MS)); + + expect(onChange).not.toHaveBeenCalledWith("dock"); + }); + + it("searches text matching a hideable category whose Retry settles at one option", async () => { + const { user, input, filtersButton, onChange, firstLoad, retryLoad } = + setupDeferredTemplateLoads("", { + skipHover: true, + shouldAdvanceTime: true, + }); + await act(async () => firstLoad.reject(new Error("boom"))); + await user.click(filtersButton); + await user.hover(await screen.findByRole("option", { name: "Template" })); + await user.click(await screen.findByRole("button", { name: "Retry" })); + await user.click(input); + // Only the test moves the clock from here, so a slow run cannot fire + // the lookup timeout. + vi.setTimerTickMode("manual"); + await user.type(input, "dock"); + await settleTypedText(); + await act(async () => retryLoad.resolve([docker])); + + expect(onChange).toHaveBeenLastCalledWith("dock"); + }); + + it("searches text matching a settled hideable category whose chip is removed during the lookup", async () => { + const kubernetes = Promise.withResolvers(); + const { user, input, onChange, firstLoad } = setupDeferredTemplateLoads( + "template:docker", + { getFilteredOptions: () => kubernetes.promise }, + ); + await act(async () => firstLoad.resolve([docker])); + await user.click(input); + await user.type(input, "kub"); + await settleTypedText(); + await user.click( + screen.getByRole("button", { name: "Remove template:docker" }), + ); + await act(async () => + kubernetes.resolve([{ label: "Kubernetes", value: "kubernetes" }]), + ); + + expect(onChange).toHaveBeenLastCalledWith("kub"); + }); + + it("holds back text matching an inline category that sets hideWhenSingleOption", async () => { + const { user, input, onChange, firstLoad } = setupDeferredTemplateLoads( + "", + { + category: { inlineOptions: true }, + }, + ); + await user.click(input); + await user.type(input, "dock"); + await settleTypedText(); + await act(async () => firstLoad.resolve([docker])); + await act(() => vi.advanceTimersByTimeAsync(TYPED_TEXT_LOOKUP_TIMEOUT_MS)); + + expect(onChange).not.toHaveBeenCalledWith("dock"); + }); + it("opens from the Filters button with keyboard focus and navigates categories", async () => { const { user, onChange, input, filtersButton } = setup([ownerCategory]); @@ -1459,6 +1905,101 @@ describe("FilterCombobox", () => { await waitFor(() => expect(onChange).toHaveBeenLastCalledWith("owner:zed")); }); + it("returns keyboard navigation to a listed category after a one-option filter is removed", async () => { + const { user, onChange, input } = setup([ + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => [{ label: "Docker", value: "docker" }], + }, + { + ...manyOwnersCategory, + key: "owner", + getOptions: async () => [ + { label: "alice", value: "alice" }, + { label: "bob", value: "bob" }, + ], + }, + ]); + await user.click(input); + await user.type(input, "template:"); + await user.click(await screen.findByRole("option", { name: "Docker" })); + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("template:docker"), + ); + await user.keyboard("{Enter}"); + await screen.findByRole("option", { name: "Docker" }); + await user.click(await screen.findByRole("option", { name: "Docker" })); + await waitFor(() => expect(onChange).toHaveBeenLastCalledWith("")); + await user.keyboard("{Enter}"); + await screen.findByRole("option", { name: "alice" }); + await user.keyboard("{ArrowDown}{Enter}"); + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("owner:alice"), + ); + }); + + it.each([ + ["own", "keeps Owner listed"], + ["zzz", "removes every listed row"], + ])( + "restores a hover flyout when typed %s, which %s, is cleared", + async (typed) => { + const { user, input } = setup( + [{ ...ownerCategory, getOptions: neverResolves }, statusCategory], + { skipHover: true }, + ); + + await user.click(input); + await user.hover(await screen.findByRole("option", { name: "Owner" })); + await expectStatus("Loading Owner options."); + await user.type(input, typed); + await waitFor(() => + expect(screen.getByRole("status")).not.toHaveTextContent( + "Loading Owner options.", + ), + ); + await user.clear(input); + + await expectStatus("Loading Owner options."); + }, + ); + + it("does not open another flyout after a Retry hides the open one", async () => { + const retry = Promise.withResolvers(); + let calls = 0; + const { user, filtersButton } = setup( + [ + { ...ownerCategory, getOptions: neverResolves }, + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: async () => { + calls += 1; + if (calls === 1) { + throw new Error("boom"); + } + await retry.promise; + return [{ label: "Docker", value: "docker" }]; + }, + }, + ], + { skipHover: true, fakeTimers: true }, + ); + + await user.click(filtersButton); + await user.hover(await screen.findByRole("option", { name: "Template" })); + await user.click(await screen.findByRole("button", { name: "Retry" })); + await act(async () => retry.resolve(undefined)); + await act(() => vi.advanceTimersByTimeAsync(CATEGORY_HOVER_DELAY_MS * 2)); + + expect(screen.getByRole("status")).not.toHaveTextContent( + "Loading Owner options.", + ); + }); + it("retries a hover flyout whose options failed to load", async () => { let failed = false; const getOptions = vi.fn(async (query: string) => { @@ -1484,8 +2025,11 @@ describe("FilterCombobox", () => { ); }); - // Owner comes first so a highlight that leaves the Status rows lands on it. - const setupFailedInlineStatus = () => { + // With no categoriesBeforeStatus, Owner is the only row above Status, so + // ArrowUp from Status highlights it. + const setupFailedInlineStatus = ( + categoriesBeforeStatus: readonly FilterCategory[] = [], + ) => { const retry = Promise.withResolvers(); let calls = 0; const getOptions = async (query: string) => { @@ -1497,7 +2041,11 @@ describe("FilterCombobox", () => { return statusCategory.getOptions(query); }; return { - ...setup([ownerCategory, { ...statusCategory, getOptions }]), + ...setup([ + ownerCategory, + ...categoriesBeforeStatus, + { ...statusCategory, getOptions }, + ]), retry, }; }; @@ -1571,6 +2119,30 @@ describe("FilterCombobox", () => { expectHighlighted("Owner"); }); + it("hands a Retry's highlight to the first loaded option while placeholder rows show", async () => { + const { user, onChange, filtersButton, retry } = setupFailedInlineStatus([ + { + key: "template", + label: "Template", + hideWhenSingleOption: true, + getOptions: neverResolves, + }, + ]); + + await user.click(filtersButton); + await screen.findByRole("option", { name: "Retry" }); + await user.keyboard("{End}{Enter}"); + await screen.findByRole("option", { name: "Loading Status options." }); + expect(screen.getByRole("status")).toHaveTextContent("Loading filters"); + await act(async () => retry.resolve(undefined)); + await screen.findByRole("option", { name: "Running" }); + await user.keyboard("{Enter}"); + + await waitFor(() => + expect(onChange).toHaveBeenLastCalledWith("status:running"), + ); + }); + it("announces every failed inline category", async () => { const failing = async () => { throw new Error("boom"); diff --git a/site/src/components/Filter/FilterCombobox/FilterCombobox.tsx b/site/src/components/Filter/FilterCombobox/FilterCombobox.tsx index ef0b50864ac..520d0f20a3c 100644 --- a/site/src/components/Filter/FilterCombobox/FilterCombobox.tsx +++ b/site/src/components/Filter/FilterCombobox/FilterCombobox.tsx @@ -14,6 +14,7 @@ import { InputGroupAddon, InputGroupButton, } from "#/components/InputGroup/InputGroup"; +import { Skeleton } from "#/components/Skeleton/Skeleton"; import { Spinner } from "#/components/Spinner/Spinner"; import { useDebouncedValue } from "#/hooks/debounce"; import { useMediaQuery } from "#/hooks/useMediaQuery"; @@ -53,7 +54,7 @@ import { * Delay before hovering another category swaps an open flyout, so a diagonal * move into the current flyout does not switch panels. */ -const CATEGORY_HOVER_DELAY_MS = 300; +export const CATEGORY_HOVER_DELAY_MS = 300; const labelOnlyChipClassName = "text-content-primary [&_[data-slot=combobox-chip-remove]]:text-content-secondary"; @@ -106,8 +107,10 @@ export function FilterCombobox({ activeOptionsError, activeOptionsEmptyText, statusMessage, + menuCategories, listedCategories, categoriesNarrowedByText, + categoryPlaceholderCount, autoHighlight, unfilteredOptionsByKey, unfilteredOptionsErroredKeys, @@ -132,12 +135,19 @@ export function FilterCombobox({ // Category shown in the pointer flyout. Distinct from `activeCategoryKey`, // which is the committed drill-in state shared with keyboard navigation. // Reset whenever the menu opens or closes so a dismissed flyout does not - // reappear next time. + // reappear next time, and when its category leaves the menu. const [flyout, setFlyout] = useState<{ categoryKey: string | null; openAtReset: boolean; }>({ categoryKey: null, openAtReset: open }); - if (flyout.openAtReset !== open) { + // Reads menuCategories, not listedCategories: typed text removes a row only + // from listedCategories, and its flyout must return when the text is + // deleted. + if ( + flyout.openAtReset !== open || + (flyout.categoryKey !== null && + !menuCategories.some((category) => category.key === flyout.categoryKey)) + ) { setFlyout({ categoryKey: null, openAtReset: open }); } const flyoutCategoryKey = flyout.categoryKey; @@ -203,7 +213,14 @@ export function FilterCombobox({ previous: string, ) => { actions.onHighlightedValueChange(highlighted, previous); - if (flyoutCategoryKey === null || highlighted === flyoutCategoryKey) { + // While typed text turns `autoHighlight` off, cmdk's pick arrives as "". + // It must not close a flyout the text only hides, such as Owner's while + // `own` is typed, so the flyout returns when the text is deleted. + if ( + flyoutCategoryKey === null || + highlighted === "" || + highlighted === flyoutCategoryKey + ) { return; } const isCategoryRow = listedCategories.some( @@ -216,7 +233,7 @@ export function FilterCombobox({ // viewports. const flyoutOptions = useFlyoutOptions( activeCategoryKey === null && !categoriesNarrowedByText && !isMobile - ? categories.find((category) => category.key === flyoutCategoryKey) + ? listedCategories.find((category) => category.key === flyoutCategoryKey) : undefined, unfilteredOptionsByKey, unfilteredOptionsErroredKeys, @@ -239,12 +256,14 @@ export function FilterCombobox({ const mainPanelEmpty = listedCategories.length === 0 && + categoryPlaceholderCount === 0 && valueSuggestions.length === 0 && inlineSections.length === 0 && !typeaheadError; const mainPanelProps = { listedCategories, + categoryPlaceholderCount, valueSuggestions, inlineSections, typeaheadError, @@ -616,6 +635,8 @@ const groupByCategoryLabel = ( type MainPanelProps = Readonly<{ listedCategories: readonly FilterCategory[]; + /** Nonzero while the category list is still unknown. */ + categoryPlaceholderCount: number; valueSuggestions: readonly ValueSuggestion[]; inlineSections: readonly InlineSection[]; typeaheadError: boolean; @@ -640,6 +661,7 @@ type MainPanelProps = Readonly<{ function MainPanel({ listedCategories, + categoryPlaceholderCount, valueSuggestions, inlineSections, typeaheadError, @@ -662,7 +684,19 @@ function MainPanel({ embedded && "w-full rounded-none border-0 bg-transparent p-0 shadow-none", )} + aria-busy={categoryPlaceholderCount > 0 || undefined} > + {Array.from({ length: categoryPlaceholderCount }, (_, index) => ( +
+ + +
+ ))} {listedCategories.map((category) => ( registerCategoryRow(category.key, element)} diff --git a/site/src/components/Filter/FilterCombobox/primitives.tsx b/site/src/components/Filter/FilterCombobox/primitives.tsx index 1217b795809..511cbf85456 100644 --- a/site/src/components/Filter/FilterCombobox/primitives.tsx +++ b/site/src/components/Filter/FilterCombobox/primitives.tsx @@ -87,8 +87,9 @@ type FilterComboboxRootProps = { highlightRef?: React.Ref; /** * Called when cmdk moves the highlight, with the new value and the one it - * replaced ("" when none). Not called for `highlightRef.set` or for a - * highlight suppressed while `autoHighlight` is off. + * replaced ("" when none). While `autoHighlight` is off, a row cmdk + * highlights on its own is cleared at once, and this is called with "" as + * the new value. Not called for `highlightRef.set`. */ onHighlightedValueChange?: (value: string, previous: string) => void; /** Accessible label for the input. cmdk wires it via `aria-labelledby`. */ @@ -181,15 +182,17 @@ export function FilterComboboxRoot({ onValueChange={(value) => { const navigating = userNavigatingRef.current; userNavigatingRef.current = false; + const previous = highlightedValueRef.current; if (!autoHighlight && !navigating) { // cmdk has already stored the row it picked and only re-reads // a controlled value when it changes. It trims the value, so // switching between "" and " " resets it to nothing. - setHighlightedValue((previous) => (previous === "" ? " " : "")); + setHighlightedValue((current) => (current === "" ? " " : "")); highlightedValueRef.current = ""; + // Lets the caller re-highlight after the highlighted row unmounts. + onHighlightedValueChange?.("", previous); return; } - const previous = highlightedValueRef.current; highlightedValueRef.current = value; setHighlightedValue(value); onHighlightedValueChange?.(value, previous); diff --git a/site/src/components/Filter/FilterCombobox/types.ts b/site/src/components/Filter/FilterCombobox/types.ts index e8d48475562..853df78e0a1 100644 --- a/site/src/components/Filter/FilterCombobox/types.ts +++ b/site/src/components/Filter/FilterCombobox/types.ts @@ -38,4 +38,15 @@ export type FilterCategory = { inlineOptionsExclusive?: boolean; /** Applied chips show only the option label, without the category prefix. */ chipLabelOnly?: boolean; + /** + * Leave the category out of the menu while `getOptions("")` returns at most + * one option. When `getOptions("")` omits values the results can contain, + * the row can hide while its one option would still narrow the results. Its + * empty-query options are fetched when the filter renders. Until every + * category with this flag finishes its first load, successfully or not, the + * unnarrowed menu shows placeholder rows in place of all submenu rows. An + * applied chip keeps it in the menu. A failed lookup keeps it until a retry + * returns at most one option. Does not apply to inline categories. + */ + hideWhenSingleOption?: boolean; }; diff --git a/site/src/components/Filter/FilterCombobox/useFilterCombobox.ts b/site/src/components/Filter/FilterCombobox/useFilterCombobox.ts index 70e358b2afb..0d4d9c1d8c2 100644 --- a/site/src/components/Filter/FilterCombobox/useFilterCombobox.ts +++ b/site/src/components/Filter/FilterCombobox/useFilterCombobox.ts @@ -153,6 +153,7 @@ type StatusMessageInput = { activeOptionsLoading: boolean; activeOptionsError: boolean; activeOptionsEmpty: boolean; + categoryListLoading: boolean; activeOptionsSearched: boolean; typeaheadLoading: boolean; typeaheadError: boolean; @@ -259,6 +260,7 @@ const deriveStatusMessage = ({ activeOptionsLoading, activeOptionsError, activeOptionsEmpty, + categoryListLoading, activeOptionsSearched, typeaheadLoading, typeaheadError, @@ -276,6 +278,9 @@ const deriveStatusMessage = ({ }) ?? `Filtering by ${activeCategoryLabel}` ); } + if (categoryListLoading) { + return "Loading filters"; + } if (typeaheadLoading) { return "Loading suggestions"; } @@ -405,10 +410,19 @@ export const useFilterCombobox = ({ () => queryToChips(value, chipKeys), [chipKeys, value], ); + const categoryForChip = (token: string) => { + const key = parseChipToken(token, chipKeys)?.key; + return key === undefined + ? undefined + : categories.find((category) => + (category.chipKeys ?? [category.key]).includes(key), + ); + }; - // Categories with a flyout or drill-in list. Inline categories render their + // Categories with a flyout or drill-in list, including those + // hideWhenSingleOption leaves out of the menu. Inline categories render their // options directly in the main panel and never enter category mode. - const submenuCategories = categories.filter( + const allSubmenuCategories = categories.filter( (category) => !category.inlineOptions, ); const inlineCategories = categories.filter( @@ -422,9 +436,10 @@ export const useFilterCombobox = ({ ? parseTypedCategoryPrefix(inputValue, inlineCategories) : null; - // Each category's unfiltered options, fetched while browsing for the pointer - // flyouts and always for inline categories, whose chips take their labels - // from them. Shares its cache key with the category view. + // Empty-query options load while browsing the category list. Inline + // categories, whose chips take their labels from them, and categories with + // `hideWhenSingleOption` load when the filter renders. Shares its cache key + // with the category view. const unfilteredOptionsEnabled = isBrowsing && activeCategoryKey === null; const unfilteredOptions = useQueries({ queries: categories.map((category) => @@ -432,23 +447,35 @@ export const useFilterCombobox = ({ category.key, category.getOptions, "", - unfilteredOptionsEnabled || Boolean(category.inlineOptions), + unfilteredOptionsEnabled || + Boolean(category.inlineOptions || category.hideWhenSingleOption), ), ), combine: (results) => { const optionsByKey = new Map(); const erroredKeys = new Set(); + const failedOrRetryingKeys = new Set(); + const hideableFirstLoadKeys = new Set(); results.forEach((result, index) => { - const { key } = categories[index]; + const { key, hideWhenSingleOption, inlineOptions } = categories[index]; if (result.data) { optionsByKey.set(key, result.data); } else if (result.isError) { erroredKeys.add(key); } + // A retry puts a failed query back to pending, so + // `errorUpdateCount` tells a retry from the first load. + if (!result.data && result.errorUpdateCount > 0) { + failedOrRetryingKeys.add(key); + } else if (hideWhenSingleOption && !inlineOptions && result.isPending) { + hideableFirstLoadKeys.add(key); + } }); return { optionsByKey, erroredKeys, + failedOrRetryingKeys, + hideableFirstLoadKeys, refetch: (categoryKey: string) => { const index = categories.findIndex( (category) => category.key === categoryKey, @@ -458,15 +485,58 @@ export const useFilterCombobox = ({ }; }, }); + const isHideableFirstLoad = (category: FilterCategory) => + unfilteredOptions.hideableFirstLoadKeys.has(category.key); + const hasSeveralOptionsOrChip = ( + category: FilterCategory, + options: readonly FilterOption[] | undefined, + chips: readonly string[], + ) => + (options?.length ?? 0) > 1 || + chips.some((token) => categoryForChip(token) === category); + // A hideable category stays in the menu while its options first load, so + // typed text can match it; while it has an applied chip, so the chip can be + // changed. After a failed lookup, including while its retry runs, it stays + // so its flyout can offer a retry, until a retry returns at most one option. + const isInMenu = (category: FilterCategory, chips = chipValues) => + !category.hideWhenSingleOption || + isHideableFirstLoad(category) || + unfilteredOptions.failedOrRetryingKeys.has(category.key) || + hasSeveralOptionsOrChip( + category, + unfilteredOptions.optionsByKey.get(category.key), + chips, + ); + const menuCategories = allSubmenuCategories.filter((category) => + isInMenu(category), + ); + const hideableFirstLoadPending = + allSubmenuCategories.some(isHideableFirstLoad); const categoryQuery = activeCategoryKey !== null || browseAll ? "" : inputValue.trim(); + // Until every hideable category finishes its first load, successfully or + // not, the full list is unknown, so the unnarrowed category list shows one + // placeholder row per submenu category. The list that replaces them can be + // shorter. + const categoryPlaceholderCount = + open && + activeCategoryKey === null && + typedInlinePrefix === null && + categoryQuery.length === 0 && + hideableFirstLoadPending + ? allSubmenuCategories.length + : 0; + // Placeholder rows are not cmdk items, so automatic highlight is off while + // they show; otherwise cmdk would highlight the first inline row and Enter + // would apply it. + const placeholdersShown = categoryPlaceholderCount > 0; const listedCategories = - !open || typedInlinePrefix !== null + !open || typedInlinePrefix !== null || placeholdersShown ? [] : categoryQuery.length === 0 - ? submenuCategories - : matchCategories(categoryQuery, submenuCategories); + ? menuCategories + : matchCategories(categoryQuery, menuCategories); const activeOptionsQuerySource = activeCategoryKey !== null ? inputValue.trim() : ""; @@ -523,8 +593,9 @@ export const useFilterCombobox = ({ typeaheadQuerySource.length > 0 && typeaheadQuerySource !== debouncedTypeaheadQuery; + const optionLookupCategories = [...menuCategories, ...inlineCategories]; const suggestionOptions = useQueries({ - queries: categories.map((category) => + queries: optionLookupCategories.map((category) => filterComboboxOptions( category.key, category.getOptions, @@ -543,9 +614,9 @@ export const useFilterCombobox = ({ const erroredKeys = new Set(); results.forEach((result, index) => { if (result.data) { - optionsByKey.set(categories[index].key, result.data); + optionsByKey.set(optionLookupCategories[index].key, result.data); } else if (result.isError) { - erroredKeys.add(categories[index].key); + erroredKeys.add(optionLookupCategories[index].key); } }); return { @@ -670,7 +741,7 @@ export const useFilterCombobox = ({ ? [] : collectValueSuggestions( inputValue, - submenuCategories, + menuCategories, typeaheadOptionsByKey, chipValues, ); @@ -716,6 +787,7 @@ export const useFilterCombobox = ({ activeOptionsLoading, activeOptionsError, activeOptionsEmpty, + categoryListLoading: placeholdersShown, activeOptionsSearched, typeaheadLoading, typeaheadError, @@ -736,17 +808,9 @@ export const useFilterCombobox = ({ // other applied options. Queries that already combine several of them, such // as a bookmarked URL, are left alone until one is picked. const withInlineOption = (token: string) => { - const categoryFor = (chip: string) => { - const key = parseChipToken(chip, chipKeys)?.key; - return key === undefined - ? undefined - : categories.find((category) => - (category.chipKeys ?? [category.key]).includes(key), - ); - }; - const category = categoryFor(token); + const category = categoryForChip(token); const kept = category?.inlineOptionsExclusive - ? chipValues.filter((chip) => categoryFor(chip) !== category) + ? chipValues.filter((chip) => categoryForChip(chip) !== category) : chipValues; return [...kept, token]; }; @@ -781,20 +845,35 @@ export const useFilterCombobox = ({ }; // Returning to the category list highlights the row that was open, so the - // keyboard position is never lost when the option rows unmount. - const returnToCategories = () => { - setHighlightedValue(activeCategoryKey ?? ""); + // keyboard position is never lost when the option rows unmount. When that + // row is not in the menu, because the picked option hid it or the category + // was entered by typing its hidden key, the first row in the menu is + // highlighted instead; cmdk keeps a highlight that names no row. + const returnToCategories = (nextChips = chipValues) => { + const staysInMenu = (category: FilterCategory) => + isInMenu(category, nextChips); + const activeCategoryStaysInMenu = + activeCategory !== undefined && staysInMenu(activeCategory); + const nextHighlight = activeCategoryStaysInMenu + ? activeCategoryKey + : (allSubmenuCategories.find( + (category) => + category.key !== activeCategoryKey && staysInMenu(category), + )?.key ?? ""); + setHighlightedValue(nextHighlight ?? ""); dispatch({ type: "leaveCategory" }); }; const commitCategoryOption = (token: string) => { - updateFromChips([...chipValues, token], typedFreeText); - returnToCategories(); + const nextChips = [...chipValues, token]; + updateFromChips(nextChips, typedFreeText); + returnToCategories(nextChips); }; const toggleCategoryOption = (token: string) => { - updateFromChips(toggledChips(token), typedFreeText); - returnToCategories(); + const nextChips = toggledChips(token); + updateFromChips(nextChips, typedFreeText); + returnToCategories(nextChips); }; // Typed filter text is dropped once an option is picked. Free-text search @@ -848,25 +927,70 @@ export const useFilterCombobox = ({ returnToCategories(); }; - // True when matchCategories matches text, text matches a loaded option, or - // a category's getOptions returns a matching option within - // TYPED_TEXT_LOOKUP_TIMEOUT_MS; a failed lookup counts as no match. Callers - // hold such text back so results do not empty out mid-word. + // A hideable submenu category's empty-query options, which decide whether it + // stays in the menu. Awaits a pending first load or Retry. A failed load + // that is not retrying keeps the category listed; it returns undefined here + // because `ensureQueryData` would refetch it. + const unfilteredForMenuCheck = ( + category: FilterCategory, + ): Promise | undefined => { + if (!category.hideWhenSingleOption || category.inlineOptions) { + return undefined; + } + const options = filterComboboxOptions( + category.key, + category.getOptions, + "", + true, + ); + const state = queryClient.getQueryState(options.queryKey); + if (state?.status === "error" && state.data === undefined) { + return undefined; + } + return queryClient.ensureQueryData(options).catch(() => undefined); + }; + + // True when text matches the name of any category, including one left out + // of the menu, or a loaded option or an option getOptions returns within + // TYPED_TEXT_LOOKUP_TIMEOUT_MS of an inline category or a category that is + // still in the menu once the lookup settles, judged by its settled + // empty-query options and the last sent chips. Failed and pending lookups + // count as no match. Callers hold such text back from the search so results + // do not empty out mid-word. const couldBeFilterSearch = (text: string): Promise => { if (text.length === 0) { return Promise.resolve(false); } - const matchesLoadedOption = [ - ...unfilteredOptions.optionsByKey.values(), - ].some((options) => filterOptionsByText(options, text).length > 0); - if (matchCategories(text, categories).length > 0 || matchesLoadedOption) { + const matchesLoadedOption = optionLookupCategories.some( + (category) => + filterOptionsByText( + unfilteredOptions.optionsByKey.get(category.key) ?? [], + text, + ).length > 0, + ); + const matchesCategory = matchCategories(text, categories).length > 0; + if (matchesCategory || matchesLoadedOption) { return Promise.resolve(true); } - const matches = categories.map(async (category) => { - const options = await queryClient.fetchQuery( - filterComboboxOptions(category.key, category.getOptions, text, true), - ); - if (filterOptionsByText(options, text).length === 0) { + const matches = optionLookupCategories.map(async (category) => { + const [unfiltered, filtered] = await Promise.all([ + unfilteredForMenuCheck(category), + queryClient.fetchQuery( + filterComboboxOptions(category.key, category.getOptions, text, true), + ), + ]); + // Chips may change while the lookup runs, so read the last sent query. + if ( + unfiltered && + !hasSeveralOptionsOrChip( + category, + unfiltered, + queryToChips(lastEmittedRef.current, chipKeys), + ) + ) { + throw new Error("Category leaves the menu"); + } + if (filterOptionsByText(filtered, text).length === 0) { throw new Error("No matching option"); } return true; @@ -976,7 +1100,7 @@ export const useFilterCombobox = ({ cancelTypedTextLookup(); const typedCategory = parseTypedCategoryPrefix( nextValue, - submenuCategories, + allSubmenuCategories, ); if (typedCategory) { dispatch({ @@ -1213,9 +1337,11 @@ export const useFilterCombobox = ({ ? optionsEmptyText(activeOptionsSearched) : undefined, statusMessage, + menuCategories, listedCategories, categoriesNarrowedByText: categoryQuery.length > 0, - autoHighlight: !typingFreeText, + categoryPlaceholderCount, + autoHighlight: !typingFreeText && !placeholdersShown, unfilteredOptionsByKey: unfilteredOptions.optionsByKey, unfilteredOptionsErroredKeys: unfilteredOptions.erroredKeys, valueSuggestions, diff --git a/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.stories.tsx b/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.stories.tsx index 5bb57af38b7..454859f4696 100644 --- a/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.stories.tsx +++ b/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.stories.tsx @@ -1,10 +1,12 @@ import type { Meta, StoryObj } from "@storybook/react-vite"; import { useState } from "react"; import { expect, userEvent, waitFor, within } from "storybook/test"; +import { templates } from "#/api/queries/templates"; import type { UseFilterResult } from "#/components/Filter/Filter"; import { MockNoPermissions, MockPermissions, + MockTemplate, MockUserOwner, mockApiError, } from "#/testHelpers/entities"; @@ -121,3 +123,19 @@ export const WithFilterError: Story = { await expect(input).toHaveAttribute("aria-errormessage", alert.id); }, }; + +// Owner and User each offer only the current user, and stay in the menu +// because they do not set hideWhenSingleOption. Template has one option, so it +// is hidden. +export const OrdinaryUserSeesOwnerAndUser: Story = { + args: { initialQuery: "" }, + parameters: { + permissions: MockNoPermissions, + queries: [{ key: templates().queryKey, data: [MockTemplate] }], + }, + play: async ({ canvasElement }) => { + await userEvent.click( + within(canvasElement).getByRole("button", { name: "Filters" }), + ); + }, +}; diff --git a/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.tsx b/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.tsx index 1ec00148776..49fac7761df 100644 --- a/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.tsx +++ b/site/src/pages/WorkspacesPage/filter/WorkspacesFilter.tsx @@ -95,6 +95,9 @@ export const WorkspacesFilter: React.FC = ({ { key: "template", label: "Template", + // Deprecated templates are not offered, so the row can hide while + // its one active template would still narrow the results. + hideWhenSingleOption: true, icon: , getOptions: (query) => getTemplateFilterOptions(query, queryClient), }, @@ -104,6 +107,9 @@ export const WorkspacesFilter: React.FC = ({ next.push({ key: "organization", label: "Organization", + // Only organizations with `audit_log:read` are offered, so the row + // can hide while its one option would still narrow the results. + hideWhenSingleOption: true, icon: , getOptions: (query) => getOrganizationFilterOptions(query, queryClient), });