Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Apps: a long list mounts only the rows on screen (#6765)

Milind Soni464175e2970c
diff --git a/src/components/AppsSection.tsx b/src/components/AppsSection.tsx
index 71a7743522..78428918a3 100644
--- a/src/components/AppsSection.tsx
+++ b/src/components/AppsSection.tsx
@@ -1,6 +1,7 @@
// One section of the Apps page (PluginsPanel.tsx): its title, a note beside it, View all, and its apps in a grid.
-export function AppsSection({ id, title, note, viewAll, after, children }: {
+export function AppsSection({ id, gridRef, title, note, viewAll, after, children }: {
id: string;
+ gridRef?: React.Ref<HTMLDivElement>;
title: string;
note?: string;
viewAll?: { label: string; onClick: () => void };
@@ -24,7 +25,7 @@ export function AppsSection({ id, title, note, viewAll, after, children }: {
</button>
)}
</div>
- <div className="grid grid-cols-1 items-start gap-x-6 gap-y-1 @xl:grid-cols-2">{children}</div>
+ <div ref={gridRef} className="grid grid-cols-1 items-start gap-x-6 gap-y-1 @xl:grid-cols-2">{children}</div>
{after}
</section>
);
diff --git a/src/components/PluginsPanel.listing.test.ts b/src/components/PluginsPanel.listing.test.ts
index 1920355462..c0f214f272 100644
--- a/src/components/PluginsPanel.listing.test.ts
+++ b/src/components/PluginsPanel.listing.test.ts
@@ -98,6 +98,12 @@ const tileRenders = async (step: () => void) => {
await flush();
return fixture.tileRenders - before;
};
+/** The tiles rendered while `step` ran, and the tiles it put on the page that were not on it before. */
+const rendersAndAdded = async (step: () => void) => {
+ const before = new Set(host.querySelectorAll("[data-app-tile]"));
+ const renders = await tileRenders(step);
+ return { renders, added: Array.from(host.querySelectorAll("[data-app-tile]")).filter((tile) => !before.has(tile)).length };
+};
const storeChange = () => {
fixture.state = { ...fixture.state, tick: Number(fixture.state.tick) + 1 };
for (const watch of Array.from(fixture.watchers)) watch();
@@ -109,6 +115,15 @@ const type = (text: string) => {
};
const loadingShown = () => host.textContent!.includes(t("connectors.loadingCatalog"));
+// happy-dom lays nothing out: a long list needs a view to mount the rows in it.
+Object.defineProperty(HTMLElement.prototype, "offsetHeight", {
+ configurable: true,
+ get(this: HTMLElement) {
+ if (this.classList.contains("overflow-y-auto")) return 640;
+ return this.hasAttribute("data-app-tile") ? 56 : 0;
+ },
+});
+
beforeEach(() => {
host = document.createElement("div");
document.body.append(host);
@@ -155,8 +170,10 @@ describe("how often the Apps panel renders its tiles", () => {
expect(await tileRenders(storeChange)).toBe(0);
const showAll = Array.from(host.querySelectorAll("button")).find((button) => button.textContent === t("apps.showAll", { count: String(APPS) }))!;
- expect(await tileRenders(() => showAll.click())).toBeGreaterThan(0);
- expect(tiles()).toBeGreaterThanOrEqual(APPS);
+ const shown = await rendersAndAdded(() => showAll.click());
+ expect(shown.renders).toBe(shown.added);
+ expect(tiles()).toBeGreaterThan(0);
+ expect(tiles()).toBeLessThan(APPS);
expect(await tileRenders(storeChange)).toBe(0);
});
@@ -173,11 +190,15 @@ describe("how often the Apps panel renders its tiles", () => {
it("renders only the tiles a search brings in, and none of those it keeps as the search narrows", async () => {
const all = APPS / KINDS.length;
- expect(await tileRenders(() => type("m"))).toBeGreaterThan(0);
- expect(tiles()).toBe(3 * all);
- expect(await tileRenders(() => type("ma"))).toBe(0);
- expect(tiles()).toBe(2 * all);
- expect(await tileRenders(() => type("mai"))).toBe(0);
+ const m = await rendersAndAdded(() => type("m"));
+ expect(m.renders).toBeGreaterThan(0);
+ expect(m.renders).toBe(m.added);
+ expect(tiles()).toBeLessThan(3 * all);
+ const ma = await rendersAndAdded(() => type("ma"));
+ expect(ma.renders).toBe(ma.added);
+ expect(tiles()).toBeLessThan(2 * all);
+ const mai = await rendersAndAdded(() => type("mai"));
+ expect(mai.renders).toBe(mai.added);
expect(tiles()).toBe(all);
expect(host.querySelector("input")!.value).toBe("mai");
expect(await tileRenders(storeChange)).toBe(0);
diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx
index bdf29f01b0..9880c04adc 100644
--- a/src/components/PluginsPanel.tsx
+++ b/src/components/PluginsPanel.tsx
@@ -44,6 +44,7 @@ import { AppGrantPrompt, botsForApps, useAppGrants } from "./AppGrantPrompt";
import { ConfirmDialog } from "./ConfirmDialog";
import { ServiceIcon, type ToolkitCard } from "./ServiceIcon"; import { AppsSection } from "./AppsSection";
import { AppTile, tileStanding, useTileActions } from "./AppTile";
+import { useAppTileWindow } from "./app-tile-window";
import { appCatalogMemory, loadAppCatalog, onAppCatalog, type AppCatalog, type CatalogPagination, type ConnectorSetup } from "@/lib/app-catalog-cache";
export { ServiceIcon, type ToolkitCard } from "./ServiceIcon";
@@ -460,6 +461,7 @@ export function PluginsPanel() {
disconnect: setDisconnecting,
openBotApps: (botId) => { close(); openBotSettings(dispatch, "access", { botId, page: "apps" }); },
});
+ const tileWindow = useAppTileWindow(allShown, filter !== "mcp" && allShown.length > APPS_PREVIEW_COUNT, aliasSlug);
const pickCategory = (next: string | null) => {
setCategory(next);
setTab("marketplace");
@@ -600,7 +602,7 @@ export function PluginsPanel() {
</div>
</header>
- <div className="min-h-0 flex-1 overflow-y-auto px-5 pb-7 sm:px-7">
+ <div ref={tileWindow.scrollRef} className="min-h-0 flex-1 overflow-y-auto px-5 pb-7 sm:px-7">
{stale ? (
<div className="mb-3 flex items-start gap-2 rounded-xl bg-warning/10 px-3 py-2 text-[13px] text-warning">
<TriangleAlert size={14} className="mt-px shrink-0" />
@@ -677,6 +679,7 @@ export function PluginsPanel() {
))}
<AppsSection
id="apps-grid-title"
+ gridRef={tileWindow.gridRef}
title={listTitle}
note={filter === "all" && !search && category === null && pagination
&& (pagination.stalled || (pagination.totalItems !== undefined && pagination.items < pagination.totalItems))
@@ -736,7 +739,7 @@ export function PluginsPanel() {
<div data-native-card="x" className={showX && !inCategoryView ? "contents" : "hidden"}><XCard refreshKey={cardsRefresh} onConnection={setXConnected} /></div>
<div data-native-card="email" className={showEmail && !inCategoryView ? "contents" : "hidden"}><EmailCard refreshKey={cardsRefresh} onConnection={setEmailConnected} /></div>
<div data-native-card="postiz" className={postizHere ? "contents" : "hidden"}><PostizCard refreshKey={cardsRefresh} onConnection={setPostizConnected} /></div>
- {allShown.map((card) => renderTile(card))}
+ {tileWindow.render(renderTile)}
</AppsSection>
</div>
)}
diff --git a/src/components/PluginsPanel.window.test.ts b/src/components/PluginsPanel.window.test.ts
new file mode 100644
index 0000000000..2e1aaae8d5
--- /dev/null
+++ b/src/components/PluginsPanel.window.test.ts
@@ -0,0 +1,260 @@
+// @vitest-environment happy-dom
+// A long app list mounts only the grid rows near the view, and still finds, scrolls to and focuses every app.
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({
+ cards: [] as Array<{ slug: string; label: string; blurb: string; logo: null; domain: null; categories: string[] }>,
+ tileRenders: 0,
+ xTile: false,
+ state: { pluginsSurface: "apps", bots: [], instances: [], config: null } as Record<string, unknown>,
+}));
+
+vi.mock("@/state/store", () => ({
+ api: vi.fn(async (path: string) => {
+ if (path === "/api/connectors/catalog") return { cards: fixture.cards, source: "api", configured: true, mode: "managed", setup: "ready" };
+ if (path.startsWith("/api/connectors/suggestions")) return { cards: [], pick: "available" };
+ throw new Error(`unexpected ${path}`);
+ }),
+ useStore: () => ({ state: fixture.state, dispatch: () => {} }),
+}));
+vi.mock("./ServiceIcon", () => ({
+ ServiceIcon: ({ className }: { className?: string }) => {
+ if (className?.includes("size-10")) fixture.tileRenders += 1;
+ return null;
+ },
+}));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
+vi.mock("@/lib/connected-apps", () => ({
+ preloadConnectedApps: vi.fn(async () => ({ services: {}, authoritative: true })),
+ connectorStatusMemory: () => null,
+ rememberConnectorStatus: () => {},
+}));
+vi.mock("@/lib/connected-apps-cache", () => ({ readCachedInventory: () => null, writeCachedInventory: () => {} }));
+vi.mock("@/lib/product-events", () => ({ connectorConnect: vi.fn() }));
+vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));
+vi.mock("./XCard", async () => {
+ const { createElement: element } = await import("react");
+ return { X_CARD_SEARCH: "x", XCard: () => fixture.xTile ? element("div", { "data-app-tile": "x" }, "X") : null };
+});
+vi.mock("./PostizCard", () => ({ PostizCard: () => null }));
+vi.mock("./EmailCard", () => ({ EmailCard: () => null }));
+vi.mock("./Avatar", () => ({ BotAvatar: () => null }));
+
+const { PluginsPanel } = await import("./PluginsPanel");
+const { StoreSourceContext } = await import("@/state/store-context");
+const { t } = await import("@/lib/i18n");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const APPS = 1000;
+const VIEW = 640;
+const TILE = 56;
+const KINDS = ["Mail", "Sheet", "Chat", "Code", "Pay", "Docs", "Cal", "Crm", "Ads", "Map"];
+const catalog = (count: number) => Array.from({ length: count }, (_, index) => ({
+ slug: `app${index}`, label: `${KINDS[index % KINDS.length]} ${index}`, blurb: `does thing ${index}`, logo: null, domain: null, categories: [`Kind ${index % 9}`],
+}));
+
+// happy-dom lays nothing out: the pop-up's scroller gets a fixed view, each tile a fixed height, the list starts at the
+// top of the scrolled content, and in two-column mode the grid resolves its columns and row gap as the browser would.
+const layout = vi.hoisted(() => ({ columns: 1 }));
+Object.defineProperty(HTMLElement.prototype, "offsetHeight", {
+ configurable: true,
+ get(this: HTMLElement) {
+ if (this.classList.contains("overflow-y-auto")) return VIEW;
+ return this.hasAttribute("data-app-tile") ? TILE : 0;
+ },
+});
+const realRect = Element.prototype.getBoundingClientRect;
+Element.prototype.getBoundingClientRect = function (this: Element) {
+ const view = this.closest<HTMLElement>(".overflow-y-auto");
+ return view && view !== this ? DOMRect.fromRect({ x: 0, y: -view.scrollTop, width: 0, height: 0 }) : realRect.call(this);
+};
+const realStyle = window.getComputedStyle.bind(window);
+vi.spyOn(window, "getComputedStyle").mockImplementation((element: Element) => {
+ const style = realStyle(element);
+ const classes = element.classList;
+ const resolved: Record<string, string> = {
+ display: classes.contains("contents") ? "contents" : classes.contains("hidden") ? "none" : style.display,
+ gridColumnEnd: classes.contains("col-span-full") ? "-1" : "auto",
+ gridTemplateColumns: classes.contains("grid") ? Array.from({ length: layout.columns }, () => "300px").join(" ") : "none",
+ rowGap: classes.contains("grid") && layout.columns > 1 ? "4px" : "normal",
+ };
+ return new Proxy(style, { get: (target, key) => typeof key === "string" && key in resolved ? resolved[key] : target[key as keyof CSSStyleDeclaration] });
+});
+
+const source = { getState: () => fixture.state, subscribe: () => () => {}, dispatch: () => {} } as never;
+let host: HTMLDivElement;
+let root: Root;
+const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+const draw = async () => {
+ await act(async () => root.render(createElement(StoreSourceContext, { value: source }, createElement(PluginsPanel))));
+ await flush();
+};
+const open = async () => {
+ root = createRoot(host);
+ await draw();
+};
+const scroller = () => host.querySelector<HTMLElement>(".overflow-y-auto")!;
+const list = () => host.querySelector<HTMLElement>('[data-apps-section="apps-grid-title"] .grid')!;
+const listed = () => Array.from(list().querySelectorAll<HTMLElement>("[data-app-tile]")).map((tile) => tile.dataset.appTile!).filter((slug) => slug !== "x");
+const mounted = () => host.querySelectorAll("[data-app-tile]").length;
+const scrollTo = async (top: number) => {
+ Object.defineProperty(scroller(), "scrollTop", { configurable: true, value: top });
+ await act(async () => { scroller().dispatchEvent(new Event("scroll")); });
+ await flush();
+};
+const button = (text: string) => Array.from(host.querySelectorAll("button")).find((candidate) => candidate.textContent === text)!;
+const showAll = async () => {
+ await act(async () => button(t("apps.showAll", { count: APPS.toLocaleString("en-US") })).click());
+ await flush();
+};
+const type = async (text: string) => {
+ const input = host.querySelector("input")!;
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, text);
+ await act(async () => { input.dispatchEvent(new Event("input", { bubbles: true })); });
+ await flush();
+};
+/** The list's rows below the first `skip` grid items, as the browser stacks them: each spacer and each row of tiles is
+ * one grid row. */
+const listHeight = (skip = 0) => {
+ let height = 0;
+ let rows = 0;
+ let inRow = 0;
+ const items = Array.from(list().querySelectorAll("[data-tile-gap], [data-app-tile]")).slice(skip);
+ for (const item of items) {
+ if (item.hasAttribute("data-tile-gap")) {
+ height += parseFloat((item as HTMLElement).style.height);
+ rows += 1;
+ inRow = 0;
+ } else if (inRow++ % layout.columns === 0) {
+ height += TILE;
+ rows += 1;
+ }
+ }
+ const gap = layout.columns > 1 ? 4 : 0;
+ return height + Math.max(0, rows - 1) * gap;
+};
+
+beforeEach(() => {
+ host = document.createElement("div");
+ document.body.append(host);
+ fixture.cards = catalog(APPS);
+ fixture.tileRenders = 0;
+ fixture.xTile = false;
+ layout.columns = 1;
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ host.remove();
+});
+
+describe("a long app list", () => {
+ it("mounts a bounded number of tiles for a 1,000-app catalog, and keeps the grid its full height", async () => {
+ await open();
+ await showAll();
+ const rows = Math.ceil(VIEW / TILE) + 6;
+ expect(listed().length).toBeGreaterThan(0);
+ expect(listed().length).toBeLessThanOrEqual(rows + 1);
+ expect(listed()[0]).toBe("app0");
+ expect(mounted()).toBeLessThan(60);
+ expect(listHeight()).toBe(APPS * TILE);
+ });
+
+ it("mounts the rows scrolled to and lets go of those scrolled past", async () => {
+ await open();
+ await showAll();
+ await scrollTo(500 * TILE);
+ const shown = listed();
+ expect(shown).toContain("app500");
+ expect(shown).toContain("app505");
+ expect(shown).not.toContain("app0");
+ expect(shown).not.toContain("app999");
+ const indexes = shown.map((slug) => Number(slug.slice(3)));
+ expect(indexes).toEqual(indexes.map((_, offset) => indexes[0]! + offset));
+ expect(listHeight()).toBe(APPS * TILE);
+
+ await scrollTo(APPS * TILE);
+ expect(listed().at(-1)).toBe("app999");
+ expect(listHeight()).toBe(APPS * TILE);
+ });
+
+ it("keeps the scroll where it is and mounts the rows in view when Show all opens the list part way down", async () => {
+ await open();
+ const writes: number[] = [];
+ let top = 30 * TILE;
+ Object.defineProperty(scroller(), "scrollTop", { configurable: true, get: () => top, set: (value: number) => { writes.push(value); top = value; } });
+ scroller().scrollTo = ((options: ScrollToOptions) => { writes.push(options.top ?? top); top = options.top ?? top; }) as HTMLElement["scrollTo"];
+ await showAll();
+ expect(writes.filter((value) => value !== 30 * TILE)).toEqual([]);
+ expect(listed()).toContain("app30");
+ expect(listed()).toContain("app40");
+ expect(listed()).not.toContain("app0");
+ expect(listHeight()).toBe(APPS * TILE);
+ });
+
+ it("finds an app far down the list by search", async () => {
+ await open();
+ await type("Map 999");
+ expect(listed()).toEqual(["app999"]);
+ await type("does thing");
+ expect(listed().length).toBeLessThan(30);
+ await type("does thing 99");
+ expect(listed()).toHaveLength(19);
+ expect(listed().at(-1)).toBe("app999");
+ });
+
+ it("lays two columns out in rows of two after a native card, as the grid places them", async () => {
+ layout.columns = 2;
+ fixture.xTile = true;
+ await open();
+ await showAll();
+ const before = Array.from(list().querySelectorAll("[data-tile-gap], [data-app-tile]"));
+ expect(before.slice(0, 3).map((child) => child.getAttribute("data-app-tile"))).toEqual(["x", "app0", "app1"]);
+ expect(listHeight(2)).toBe(Math.ceil((APPS - 1) / 2) * TILE + (Math.ceil((APPS - 1) / 2) - 1) * 4);
+
+ await scrollTo(200 * (TILE + 4));
+ const items = Array.from(list().querySelectorAll("[data-tile-gap], [data-app-tile]"));
+ expect(items.slice(0, 3).map((child) => child.getAttribute("data-app-tile") ?? "gap")).toEqual(["x", "app0", "gap"]);
+ const after = listed().slice(1).map((slug) => Number(slug.slice(3)));
+ expect(after[0]! % 2).toBe(1);
+ expect(after.length % 2).toBe(0);
+ expect(after).toContain(1 + 200 * 2);
+ expect(listHeight(2)).toBe(Math.ceil((APPS - 1) / 2) * TILE + (Math.ceil((APPS - 1) / 2) - 1) * 4);
+ });
+});
+
+describe("keyboard focus in a long app list", () => {
+ it("reaches the next tile by Tab once the browser scrolls the focused one into view", async () => {
+ await open();
+ await showAll();
+ const last = listed().at(-1)!;
+ const index = Number(last.slice(3));
+ const control = list().querySelector<HTMLButtonElement>(`[data-app-tile="${last}"] button`)!;
+ act(() => control.focus());
+ // The browser scrolls a focused control into view: here, the bottom of its row to the bottom of the view.
+ await scrollTo((index + 1) * TILE - VIEW);
+ expect(document.activeElement).toBe(control);
+ const tiles = Array.from(list().querySelectorAll("[data-app-tile]"));
+ const position = tiles.findIndex((tile) => tile.contains(control));
+ expect(tiles[position + 1]?.getAttribute("data-app-tile")).toBe(`app${index + 1}`);
+ });
+
+ it("keeps the focused tile mounted while the list scrolls far away, after the list was taken off the page and back", async () => {
+ await open();
+ await showAll();
+ fixture.state = { ...fixture.state, pluginsSurface: "mcp" };
+ await draw();
+ expect(host.querySelector('[data-apps-section="apps-grid-title"]')).toBeNull();
+ fixture.state = { ...fixture.state, pluginsSurface: "apps" };
+ await draw();
+ const control = list().querySelector<HTMLButtonElement>('[data-app-tile="app2"] button')!;
+ act(() => control.focus());
+ await scrollTo(700 * TILE);
+ expect(listed()).toContain("app700");
+ expect(listed()).toContain("app2");
+ expect(document.activeElement).toBe(control);
+ expect(listHeight()).toBe(APPS * TILE);
+ });
+});
diff --git a/src/components/app-tile-window.tsx b/src/components/app-tile-window.tsx
new file mode 100644
index 0000000000..881ee9d47d
--- /dev/null
+++ b/src/components/app-tile-window.tsx
@@ -0,0 +1,200 @@
+import { useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual";
+
+const TILE_HEIGHT = 56;
+const OVERSCAN_ROWS = 6;
+
+interface GridLayout {
+ columns: number;
+ /** Tiles that finish the grid row the cards before the list started. */
+ lead: number;
+ margin: number;
+ gap: number;
+}
+
+const FIRST_LAYOUT: GridLayout = { columns: 1, lead: 0, margin: 0, gap: 0 };
+
+const sameLayout = (a: GridLayout, b: GridLayout) =>
+ a.columns === b.columns && a.lead === b.lead && a.gap === b.gap && Math.abs(a.margin - b.margin) < 0.5;
+
+const gridColumns = (style: CSSStyleDeclaration) =>
+ Math.max(1, style.gridTemplateColumns.split(" ").filter((track) => track.endsWith("px")).length);
+
+/** The column the next auto-placed item takes after `items`, following `display: contents` and skipping hidden ones. */
+function nextColumn(items: Element[], columns: number): number {
+ let column = 0;
+ const place = (element: Element) => {
+ const style = getComputedStyle(element);
+ if (style.display === "none") return;
+ if (style.display === "contents") {
+ for (const child of Array.from(element.children)) place(child);
+ return;
+ }
+ column = style.gridColumnEnd === "-1" ? 0 : (column + 1) % columns;
+ };
+ for (const item of items) place(item);
+ return column;
+}
+
+/** Keeps the measurements current and the focused tile known while the window is on. */
+function watchGrid(grid: HTMLElement, scroller: HTMLElement, measure: () => void, onFocus: (slug: string | null) => void, ownCount: () => number) {
+ const resizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
+ resizes?.observe(grid);
+ resizes?.observe(scroller);
+ const mutations = new MutationObserver(measure);
+ mutations.observe(grid, { childList: true, subtree: true, attributes: true, attributeFilter: ["class"] });
+ const ownTile = (target: EventTarget | null) => {
+ const children = Array.from(grid.children);
+ const own = children.slice(children.length - ownCount());
+ return own.find((child) => target instanceof Node && child.contains(target))?.getAttribute("data-app-tile") ?? null;
+ };
+ const onFocusIn = (event: FocusEvent) => onFocus(ownTile(event.target));
+ const onFocusOut = (event: FocusEvent) => {
+ if (event.relatedTarget !== null && ownTile(event.relatedTarget) === null) onFocus(null);
+ };
+ grid.addEventListener("focusin", onFocusIn);
+ grid.addEventListener("focusout", onFocusOut);
+ return () => {
+ resizes?.disconnect();
+ mutations.disconnect();
+ grid.removeEventListener("focusin", onFocusIn);
+ grid.removeEventListener("focusout", onFocusOut);
+ };
+}
+
+/**
+ * Mounts only the grid rows of `cards` near the view, as the last items of the grid at `gridRef`, scrolled by
+ * `scrollRef`. Columns, row gap and the place the first card lands are read from the laid-out grid, and full-width
+ * spacers stand in for the rows left out, so the grid looks as it would with every card in it. The row of the focused
+ * tile and of `keep` stay mounted.
+ */
+export function useAppTileWindow<Card extends { slug: string }>(cards: readonly Card[], enabled: boolean, keep: string | null) {
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const gridRef = useRef<HTMLDivElement>(null);
+ const [kept, setLayout] = useState(FIRST_LAYOUT);
+ // Measured while the list is short as well, so the render that turns the window on already places it.
+ const seen = useRef(FIRST_LAYOUT);
+ const wasEnabled = useRef(false);
+ const layout = enabled && !wasEnabled.current ? seen.current : kept;
+ const focused = useRef<string | null>(null);
+ const placed = useRef<number[]>([]);
+ const columns = layout.columns;
+ const lead = Math.min(layout.lead, cards.length);
+ const rows = enabled ? Math.ceil((cards.length - lead) / columns) : 0;
+ const indexOf = useMemo(() => new Map(cards.map((card, index) => [card.slug, index])), [cards]);
+ const getItemKey = useCallback((row: number) => `${columns}:${cards[lead + row * columns]?.slug}`, [cards, lead, columns]);
+ const virtualizer = useVirtualizer({
+ count: rows,
+ enabled,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: () => TILE_HEIGHT,
+ getItemKey,
+ overscan: OVERSCAN_ROWS,
+ gap: layout.gap,
+ scrollMargin: layout.margin,
+ initialRect: { width: 0, height: scrollRef.current?.offsetHeight ?? 0 },
+ // The virtualizer scrolls to this offset when it takes the scroller, and the list can turn on part way down.
+ initialOffset: () => scrollRef.current?.scrollTop ?? 0,
+ rangeExtractor: (range) => {
+ const shown = new Set(defaultRangeExtractor(range));
+ for (const slug of [focused.current, keep]) {
+ const index = slug === null ? undefined : indexOf.get(slug);
+ if (index !== undefined && index >= lead) shown.add(Math.floor((index - lead) / columns));
+ }
+ return [...shown].sort((a, b) => a - b);
+ },
+ });
+ // The rows are in the page's flow, so the browser's scroll anchoring already keeps the view still when one above it
+ // changes height; moving the scroll as well would move it twice.
+ virtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => false;
+
+ const pass: number[] = [];
+ const measure = useRef(() => {});
+ measure.current = () => {
+ const grid = gridRef.current;
+ const scroller = scrollRef.current;
+ if (!grid || !scroller) return;
+ const own = placed.current;
+ const children = Array.from(grid.children);
+ const first = children.length - own.length;
+ const style = getComputedStyle(grid);
+ const nextColumns = gridColumns(style);
+ const column = nextColumn(children.slice(0, first), nextColumns);
+ const nextLead = column === 0 ? 0 : nextColumns - column;
+ const start = children[first + nextLead];
+ const next = {
+ columns: nextColumns,
+ lead: nextLead,
+ margin: start ? start.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop : layout.margin,
+ gap: parseFloat(style.rowGap) || 0,
+ };
+ seen.current = next;
+ if (!enabled) return;
+ if (!sameLayout(next, kept)) {
+ setLayout(next);
+ return;
+ }
+ const heights = new Map<number, number>();
+ own.forEach((index, position) => {
+ if (index < lead) return;
+ const row = Math.floor((index - lead) / columns);
+ const height = (children[first + position] as HTMLElement).offsetHeight;
+ heights.set(row, Math.max(heights.get(row) ?? 0, height));
+ });
+ for (const [row, height] of heights) if (height > 0) virtualizer.resizeItem(row, height);
+ };
+
+ const watched = useRef<{ grid: HTMLElement; scroller: HTMLElement; stop: () => void } | null>(null);
+ useLayoutEffect(() => {
+ placed.current = pass;
+ wasEnabled.current = enabled;
+ const grid = gridRef.current;
+ const scroller = scrollRef.current;
+ const watch = enabled && grid && scroller ? { grid, scroller } : null;
+ if (watched.current && (watched.current.grid !== watch?.grid || watched.current.scroller !== watch?.scroller)) {
+ watched.current.stop();
+ watched.current = null;
+ }
+ if (watch && !watched.current) {
+ const stop = watchGrid(watch.grid, watch.scroller, () => measure.current(), (slug) => { focused.current = slug; }, () => placed.current.length);
+ watched.current = { ...watch, stop };
+ }
+ measure.current();
+ });
+ useLayoutEffect(() => () => {
+ watched.current?.stop();
+ watched.current = null;
+ }, []);
+
+ const render = (renderCard: (card: Card) => ReactNode): ReactNode[] => {
+ if (!enabled) {
+ pass.push(...cards.keys());
+ return cards.map(renderCard);
+ }
+ const nodes: ReactNode[] = [];
+ const add = (index: number) => {
+ nodes.push(renderCard(cards[index]!));
+ pass.push(index);
+ };
+ const spacer = (key: string, height: number) => {
+ nodes.push(<div key={key} aria-hidden="true" data-tile-gap="" className="col-span-full" style={{ height: Math.max(0, height) }} />);
+ pass.push(-1);
+ };
+ for (let index = 0; index < lead; index += 1) add(index);
+ const { gap, scrollMargin } = virtualizer.options;
+ // A spacer is a grid row of its own, so it takes the row gap on each side that the rows it replaces had between them.
+ let end = scrollMargin - gap;
+ let next = 0;
+ for (const row of virtualizer.getVirtualItems()) {
+ if (row.index > next) spacer(`gap-${next}`, row.start - end - 2 * gap);
+ const last = Math.min(cards.length, lead + (row.index + 1) * columns);
+ for (let index = lead + row.index * columns; index < last; index += 1) add(index);
+ end = row.end;
+ next = row.index + 1;
+ }
+ if (next < rows) spacer(`gap-${next}`, virtualizer.getTotalSize() + scrollMargin - end - gap);
+ return nodes;
+ };
+
+ return { scrollRef, gridRef, render };
+}