Skip to content

Commit 8994adb

Browse files
committed
fix(web): narrow font picker fix to row invalidation and add a regression test
The stale highlight came from LegendList reusing memoized rows whose Base UI index no longer matched their position after filtering. Passing the filtered list as extraData is enough on its own, so drop the separate items/filteredItems collections. Add a jsdom test that types a query, moves the highlight with ArrowDown, and selects with Enter; it fails without the fix.
1 parent baa063e commit 8994adb

2 files changed

Lines changed: 120 additions & 11 deletions

File tree

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// @vitest-environment jsdom
2+
3+
import { act } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6+
7+
const families = vi.hoisted(() => {
8+
const families = [
9+
"Arial",
10+
"Courier New",
11+
"Fira Code",
12+
"Georgia",
13+
"Helvetica",
14+
"JetBrains Mono",
15+
"Menlo",
16+
"Times New Roman",
17+
];
18+
// The picker decides at module load whether the engine can list fonts.
19+
Object.assign(window, { queryLocalFonts: async () => families.map((family) => ({ family })) });
20+
return families;
21+
});
22+
23+
vi.mock("../../appearanceFonts", () => ({
24+
isMonospaceFamily: () => true,
25+
queryInstalledFontFamilies: async () => ({ status: "granted", families }),
26+
}));
27+
28+
import { discoverInstalledFonts, FontFamilyPicker } from "./FontFamilyPicker";
29+
30+
let root: Root;
31+
let container: HTMLDivElement;
32+
33+
beforeEach(async () => {
34+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
35+
vi.stubGlobal(
36+
"ResizeObserver",
37+
class {
38+
observe() {}
39+
disconnect() {}
40+
unobserve() {}
41+
},
42+
);
43+
// jsdom has no layout; give LegendList a 30px viewport and 30px rows so it
44+
// renders a window of rows the way it does in a browser.
45+
vi.spyOn(Element.prototype, "getBoundingClientRect").mockReturnValue(
46+
DOMRect.fromRect({ width: 288, height: 30 }),
47+
);
48+
Object.defineProperty(Element.prototype, "getAnimations", {
49+
configurable: true,
50+
value: () => [],
51+
});
52+
container = document.createElement("div");
53+
document.body.append(container);
54+
root = createRoot(container);
55+
await act(async () => discoverInstalledFonts());
56+
});
57+
58+
afterEach(async () => {
59+
await act(() => root.unmount());
60+
container.remove();
61+
vi.restoreAllMocks();
62+
vi.unstubAllGlobals();
63+
});
64+
65+
function highlightedOptions(): string[] {
66+
return [...document.querySelectorAll('[role="option"][data-highlighted]')].map(
67+
(option) => option.textContent ?? "",
68+
);
69+
}
70+
71+
async function typeQuery(input: HTMLInputElement, value: string) {
72+
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
73+
await act(async () => {
74+
setValue.call(input, value);
75+
input.dispatchEvent(new Event("input", { bubbles: true }));
76+
});
77+
}
78+
79+
describe("FontFamilyPicker", () => {
80+
it("highlights, moves through, and selects matches after filtering", async () => {
81+
const onSelect = vi.fn();
82+
await act(async () =>
83+
root.render(
84+
<FontFamilyPicker
85+
ariaLabel="Code font"
86+
defaultFamily="Menlo"
87+
selectedFamily=""
88+
initialOpen
89+
onSelect={onSelect}
90+
/>,
91+
),
92+
);
93+
94+
const input = document.querySelector<HTMLInputElement>('input[placeholder="Search fonts…"]');
95+
expect(input).not.toBeNull();
96+
const press = (key: string) =>
97+
act(async () => {
98+
input!.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));
99+
});
100+
101+
// Both matches were already rendered further down the unfiltered list.
102+
await typeQuery(input!, "co");
103+
expect(highlightedOptions()).toEqual(["Courier New"]);
104+
105+
await press("ArrowDown");
106+
expect(highlightedOptions()).toEqual(["Fira Code"]);
107+
108+
await press("Enter");
109+
expect(onSelect).toHaveBeenCalledWith("Fira Code");
110+
});
111+
});

‎apps/web/src/components/settings/FontFamilyPicker.tsx‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,7 @@ export function FontFamilyPicker({
144144
return requireMonospace ? enumeration.families.filter(isMonospaceFamily) : enumeration.families;
145145
}, [enumeration, requireMonospace]);
146146

147-
const collectionItems = useMemo(() => [DEFAULT_FONT_VALUE, ...families], [families]);
148-
149-
const filteredItems = useMemo(() => {
147+
const items = useMemo(() => {
150148
const trimmedQuery = query.trim().toLowerCase();
151149
const result: string[] = [];
152150
if (trimmedQuery.length === 0) result.push(DEFAULT_FONT_VALUE);
@@ -189,8 +187,8 @@ export function FontFamilyPicker({
189187

190188
return (
191189
<Combobox
192-
items={collectionItems}
193-
filteredItems={filteredItems}
190+
items={items}
191+
filteredItems={items}
194192
autoHighlight
195193
virtualized
196194
open={open}
@@ -237,16 +235,16 @@ export function FontFamilyPicker({
237235
<ComboboxListVirtualized className="size-full min-w-0 p-0">
238236
<LegendList<string>
239237
ref={listRef}
240-
data={filteredItems}
241-
// LegendList memoizes rows by item identity. Invalidate them
242-
// when filtering moves a surviving item to a different index,
243-
// because Base UI highlights and selects virtualized items by index.
244-
extraData={filteredItems}
238+
data={items}
239+
// Rows are memoized by item, but Base UI highlights and selects
240+
// virtualized rows by index. Re-render them when filtering moves
241+
// a surviving item to a new index.
242+
extraData={items}
245243
keyExtractor={(item) => item}
246244
renderItem={({ item, index }) => renderItem(item, index)}
247245
estimatedItemSize={30}
248246
drawDistance={360}
249-
style={{ height: Math.min(filteredItems.length * 30, 288) }}
247+
style={{ height: Math.min(items.length * 30, 288) }}
250248
/>
251249
</ComboboxListVirtualized>
252250
</div>

0 commit comments

Comments
 (0)