TypeScript
perf(web): diff file boundaries observe visibility once instead of on every render (#25134)
Julius Marmingec298a401f2d6
diff --git a/apps/web/src/components/diffs/DiffFileLoadingBoundary.browser.test.tsx b/apps/web/src/components/diffs/DiffFileLoadingBoundary.browser.test.tsxnew file mode 100644index 00000000000..4cffc00fad9--- /dev/null+++ b/apps/web/src/components/diffs/DiffFileLoadingBoundary.browser.test.tsx@@ -0,0 +1,49 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { render } from "../../../test/render";+import { DiffFileLoadingBoundary } from "./DiffFileLoadingBoundary";++// Like the real observer, every observe() reports the target's current state; this boundary+// is always in range.+class InRangeIntersectionObserver {+ static observeCount = 0;+ constructor(readonly callback: IntersectionObserverCallback) {}+ observe(target: Element) {+ InRangeIntersectionObserver.observeCount += 1;+ this.callback(+ [{ target, isIntersecting: true } as IntersectionObserverEntry],+ this as unknown as IntersectionObserver,+ );+ }+ unobserve() {}+ disconnect() {}+}++function stubIntersectionObserver() {+ InRangeIntersectionObserver.observeCount = 0;+ vi.stubGlobal("IntersectionObserver", InRangeIntersectionObserver);+ return { [Symbol.dispose]: () => vi.unstubAllGlobals() };+}++describe("DiffFileLoadingBoundary", () => {+ it("observes once and loads once while its parent re-renders with a new load", async () => {+ using _observer = stubIntersectionObserver();+ const load = vi.fn();+ // DiffPanel hands over a new loadNextFiles whenever any file patch changes.+ await using screen = await render(<DiffFileLoadingBoundary load={() => load()} count={8} />, {+ router: false, // the boundary does not touch routing+ });+ await screen.rerender(<DiffFileLoadingBoundary load={() => load()} count={8} />);+ await screen.rerender(<DiffFileLoadingBoundary load={() => load()} count={8} />);+ await screen.rerender(<DiffFileLoadingBoundary load={() => load()} count={8} />);++ await expect.element(screen.getByRole("status", { name: "Loading diff…" })).toBeInTheDocument();+ expect(InRangeIntersectionObserver.observeCount).toBe(1);+ expect(load).toHaveBeenCalledTimes(1);++ // A settled batch leaves the boundary in range, so it asks for the next one.+ await screen.rerender(<DiffFileLoadingBoundary load={() => load()} count={4} />);+ expect(InRangeIntersectionObserver.observeCount).toBe(1);+ expect(load).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx b/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsxindex e4c7c685ef9..51716106c74 100644--- a/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx+++ b/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx@@ -1,22 +1,28 @@+import { useEffect, useState } from "react";++import { useStableCallback } from "~/hooks/useStableCallback";import { observeIntersection } from "~/lib/observeIntersection";import { DiffFileHeaderSkeleton } from "../DiffPanelShell";export function DiffFileLoadingBoundary({ load, count }: { load: () => void; count: number }) {+ const [isNear, setIsNear] = useState(false);+ const loadLatest = useStableCallback(load);+ // A fresh observe redelivers the current intersection, so this ref must keep its identity+ // across renders: it captures nothing but the state setter.+ const observe = (node: HTMLDivElement | null) => {+ if (!node) return;+ return observeIntersection(node, (entry) => setIsNear(entry.isIntersecting), {+ rootMargin: "600px",+ });+ };+ // A settled batch shrinks `count` without moving the boundary out of range, and no new+ // intersection entry arrives for that, so ask for the next batch whenever it changes.+ useEffect(() => {+ if (isNear && count > 0) loadLatest();+ }, [isNear, count, loadLatest]);+return (- <div- ref={(node) => {- if (!node) return;- return observeIntersection(- node,- (entry) => {- if (entry.isIntersecting) load();- },- { rootMargin: "600px" },- );- }}- role="status"- aria-label="Loading diff…"- >+ <div ref={observe} role="status" aria-label="Loading diff…">{Array.from({ length: Math.min(count, 4) }, (_, index) => (<div key={index} aria-hidden className="border-b border-border/40"><DiffFileHeaderSkeleton titleWidth="medium" />diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.tsindex cb68c2cf708..e7fbfc4116f 100644--- a/apps/web/src/components/diffs/useReviewFilePatches.ts+++ b/apps/web/src/components/diffs/useReviewFilePatches.ts@@ -92,8 +92,11 @@ export function useReviewFilePatches({const added = indices.filter((index) => !previous.includes(index));return added.length === 0 ? current : { scope, indices: [...previous, ...added] };});- const loadNextFiles = () =>+ // The first unsettled file already requested means a batch is in flight; wait for it.+ const loadNextFiles = () => {+ if (queries.some(({ index }) => index === settledFileCount)) return;requestFiles(Array.from({ length: 4 }, (_, index) => settledFileCount + index));+ };const requestFile = (index: number) => requestFiles([index]);const renderableFiles = source? files.map((file, index): FileDiffMetadata => {diff --git a/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx b/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsxindex 2850f05ba7f..854de02b4cc 100644--- a/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx+++ b/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx@@ -6,11 +6,13 @@ import { usePermissionStatus } from "./usePermissionStatus";function PermissionProbe({check,label,+ enabled = true,}: {readonly check: () => Promise<{ screen: boolean }>;readonly label: string;+ readonly enabled?: boolean;}) {- const { status } = usePermissionStatus(async () => check(), { screen: false });+ const { status } = usePermissionStatus(async () => check(), { screen: false }, enabled);return (<p>{label}: {status.screen ? "granted" : "missing"}@@ -32,4 +34,17 @@ describe("usePermissionStatus", () => {await expect.element(screen.getByText("third: missing")).toBeInTheDocument();expect(check).toHaveBeenCalledTimes(1);});++ it("checks with the latest check after the caller passes a new one", async () => {+ const first = vi.fn(() => new Promise<{ screen: boolean }>(() => {}));+ const second = vi.fn(async () => ({ screen: true }));+ await using screen = await render(<PermissionProbe check={first} label="probe" />, {+ router: false, // the hook does not touch routing+ });+ await screen.rerender(<PermissionProbe check={second} label="probe" enabled={false} />);+ await screen.rerender(<PermissionProbe check={second} label="probe" />);++ await expect.element(screen.getByText("probe: granted")).toBeInTheDocument();+ expect(first).toHaveBeenCalledTimes(1);+ });});diff --git a/apps/web/src/components/permissions/usePermissionStatus.ts b/apps/web/src/components/permissions/usePermissionStatus.tsindex 894ffcdf297..ae247d2cde6 100644--- a/apps/web/src/components/permissions/usePermissionStatus.ts+++ b/apps/web/src/components/permissions/usePermissionStatus.ts@@ -1,5 +1,6 @@import { useState, useSyncExternalStore } from "react";+import { useStableCallback } from "~/hooks/useStableCallback";import { getDocumentActivity, subscribeDocumentActivity } from "~/lib/documentActivity";const POLL_INTERVAL_MS = 1500;@@ -61,16 +62,16 @@ export function createPermissionPoller<Id extends string>(const noopSubscribe = () => () => {};/**- * `check` and `initialStatus` are read once, when the component mounts, so the- * subscription only restarts when `enabled` flips. Key the component if what it- * checks can change.+ * Each check calls the latest `check`, since callers close over props. `initialStatus` is+ * read once, when the component mounts, and the subscription only restarts when `enabled` flips.*/export function usePermissionStatus<Id extends string>(check: () => Promise<Record<Id, boolean>>,initialStatus: Record<Id, boolean>,enabled = true,) {- const [poller] = useState(() => createPermissionPoller(check, initialStatus));+ const checkLatest = useStableCallback(check);+ const [poller] = useState(() => createPermissionPoller(checkLatest, initialStatus));const { status, error } = useSyncExternalStore(enabled ? poller.subscribe : noopSubscribe,poller.getSnapshot,