TypeScript
refactor(web): shared intersection and document-activity stores (#25020)
Julius Marmingec6b9c389ff05
diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex f2ff8d22e6a..1164cfa5261 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -30,6 +30,7 @@ import {import type { SidebarThreadSummary, Thread } from "../types";import { normalizeSearchText } from "../lib/utils";import { isLatestRunSettled } from "../session-logic";+import { observeIntersection } from "../lib/observeIntersection";export function shouldNavigateAfterThreadPark(input: {readonly threadKey: string;@@ -68,31 +69,23 @@ const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;export function useSidebarRowSubscriptionLease(isActive: boolean): {readonly leaseLiveStatus: boolean;- readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;+ readonly rowRef: (row: HTMLElement | null) => (() => void) | undefined;} {- const [row, setRow] = React.useState<HTMLElement | null>(null);const [isNearViewport, setIsNearViewport] = React.useState(isActive);if (isActive && !isNearViewport) setIsNearViewport(true);const canObserve = typeof IntersectionObserver !== "undefined";- React.useEffect(() => {- if (isActive || row === null || !canObserve) return;-- const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');- const observer = new IntersectionObserver(- ([entry]) => setIsNearViewport(entry?.isIntersecting === true),- {- root: scrollRoot,- rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,- },- );- observer.observe(row);- return () => observer.disconnect();- }, [canObserve, isActive, row]);-return {leaseLiveStatus: isActive || isNearViewport || !canObserve,- rowRef: setRow,+ rowRef: (row) => {+ if (row === null || isActive || !canObserve) return undefined;+ // The overscan has to apply to the sidebar's own scroller; a viewport-rooted+ // margin is still clipped by it.+ return observeIntersection(row, (entry) => setIsNearViewport(entry.isIntersecting), {+ root: row.closest('[data-slot="scroll-area-viewport"]'),+ rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,+ });+ },};}diff --git a/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx b/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsxindex 81a542c2401..e4c7c685ef9 100644--- a/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx+++ b/apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx@@ -1,21 +1,22 @@-import { useEffect, useRef } from "react";+import { observeIntersection } from "~/lib/observeIntersection";import { DiffFileHeaderSkeleton } from "../DiffPanelShell";export function DiffFileLoadingBoundary({ load, count }: { load: () => void; count: number }) {- const ref = useRef<HTMLDivElement>(null);- useEffect(() => {- if (!ref.current) return;- const observer = new IntersectionObserver(- (entries) => {- if (entries.some((entry) => entry.isIntersecting)) load();- },- { rootMargin: "600px" },- );- observer.observe(ref.current);- return () => observer.disconnect();- }, [load]);return (- <div ref={ref} role="status" aria-label="Loading diff…">+ <div+ ref={(node) => {+ if (!node) return;+ return observeIntersection(+ node,+ (entry) => {+ if (entry.isIntersecting) load();+ },+ { rootMargin: "600px" },+ );+ }}+ 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/permissions/usePermissionStatus.browser.test.tsx b/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsxnew file mode 100644index 00000000000..2850f05ba7f--- /dev/null+++ b/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { render } from "../../../test/render";+import { usePermissionStatus } from "./usePermissionStatus";++function PermissionProbe({+ check,+ label,+}: {+ readonly check: () => Promise<{ screen: boolean }>;+ readonly label: string;+}) {+ const { status } = usePermissionStatus(async () => check(), { screen: false });+ return (+ <p>+ {label}: {status.screen ? "granted" : "missing"}+ </p>+ );+}++describe("usePermissionStatus", () => {+ it("does not start a new check when the component re-renders", async () => {+ // A check that never settles keeps the interval from adding calls, so any+ // extra call can only come from the subscription restarting.+ const check = vi.fn(() => new Promise<{ screen: boolean }>(() => {}));+ await using screen = await render(<PermissionProbe check={check} label="first" />, {+ router: false, // the hook does not touch routing+ });+ await screen.rerender(<PermissionProbe check={check} label="second" />);+ await screen.rerender(<PermissionProbe check={check} label="third" />);++ await expect.element(screen.getByText("third: missing")).toBeInTheDocument();+ expect(check).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/web/src/components/permissions/usePermissionStatus.test.ts b/apps/web/src/components/permissions/usePermissionStatus.test.tsnew file mode 100644index 00000000000..537b67c99ca--- /dev/null+++ b/apps/web/src/components/permissions/usePermissionStatus.test.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++import { createPermissionPoller } from "./usePermissionStatus";++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++describe("createPermissionPoller", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("checks on subscribe and on every interval, publishing each result", async () => {+ const onChange = vi.fn();+ let granted = false;+ const check = vi.fn(async () => ({ screen: granted }));+ const poller = createPermissionPoller(check, { screen: false });+ const stop = poller.subscribe(onChange);++ await vi.advanceTimersByTimeAsync(0);+ expect(check).toHaveBeenCalledTimes(1);+ granted = true;+ await vi.advanceTimersByTimeAsync(1500);+ expect(check).toHaveBeenCalledTimes(2);+ expect(poller.getSnapshot()).toEqual({ status: { screen: true }, error: null });+ expect(onChange).toHaveBeenCalledTimes(2);++ stop();+ await vi.advanceTimersByTimeAsync(3000);+ expect(check).toHaveBeenCalledTimes(2);+ });++ it("never overlaps checks while one is still pending", async () => {+ const pending = deferred<{ screen: boolean }>();+ const check = vi.fn(() => pending.promise);+ const poller = createPermissionPoller(check, { screen: false });+ const stop = poller.subscribe(() => {});++ await vi.advanceTimersByTimeAsync(4500);+ expect(check).toHaveBeenCalledTimes(1);+ pending.resolve({ screen: true });+ await vi.advanceTimersByTimeAsync(1500);+ expect(check).toHaveBeenCalledTimes(2);+ stop();+ });++ it("keeps the last status on failure and clears the error on the next success", async () => {+ let fail = false;+ const check = vi.fn(async () => {+ if (fail) throw new Error("unavailable");+ return { screen: true };+ });+ const poller = createPermissionPoller(check, { screen: false });+ const stop = poller.subscribe(() => {});++ await vi.advanceTimersByTimeAsync(0);+ fail = true;+ await vi.advanceTimersByTimeAsync(1500);+ expect(poller.getSnapshot().status).toEqual({ screen: true });+ expect(poller.getSnapshot().error).not.toBeNull();+ fail = false;+ await vi.advanceTimersByTimeAsync(1500);+ expect(poller.getSnapshot().error).toBeNull();+ stop();+ });++ it("drops a result that lands after unsubscribing", async () => {+ const pending = deferred<{ screen: boolean }>();+ const onChange = vi.fn();+ const poller = createPermissionPoller(() => pending.promise, { screen: false });+ const stop = poller.subscribe(onChange);++ stop();+ pending.resolve({ screen: true });+ await vi.advanceTimersByTimeAsync(0);+ expect(onChange).not.toHaveBeenCalled();+ expect(poller.getSnapshot().status).toEqual({ screen: false });+ });+});diff --git a/apps/web/src/components/permissions/usePermissionStatus.ts b/apps/web/src/components/permissions/usePermissionStatus.tsindex f28c9c755da..894ffcdf297 100644--- a/apps/web/src/components/permissions/usePermissionStatus.ts+++ b/apps/web/src/components/permissions/usePermissionStatus.ts@@ -1,42 +1,80 @@-import { useEffect, useEffectEvent, useState } from "react";+import { useState, useSyncExternalStore } from "react";+import { getDocumentActivity, subscribeDocumentActivity } from "~/lib/documentActivity";++const POLL_INTERVAL_MS = 1500;+const CHECK_FAILED_MESSAGE = "Could not check permissions. We'll try again automatically.";++interface PermissionSnapshot<Id extends string> {+ readonly status: Record<Id, boolean>;+ readonly error: string | null;+}++/**+ * Holds the last permission check result and polls while subscribed: on+ * subscribe, every interval, and when the window regains focus or visibility.+ * Checks are skipped while the tab is hidden and never overlap.+ */+export function createPermissionPoller<Id extends string>(+ check: () => Promise<Record<Id, boolean>>,+ initialStatus: Record<Id, boolean>,+) {+ let snapshot: PermissionSnapshot<Id> = { status: initialStatus, error: null };+ return {+ getSnapshot: () => snapshot,+ subscribe(onChange: () => void): () => void {+ let disposed = false;+ let checking = false;+ const publish = (next: PermissionSnapshot<Id>) => {+ if (disposed) return;+ snapshot = next;+ onChange();+ };+ const refresh = async () => {+ if (disposed || checking || !getDocumentActivity().visible) return;+ checking = true;+ try {+ publish({ status: await check(), error: null });+ } catch {+ publish({ status: snapshot.status, error: CHECK_FAILED_MESSAGE });+ }+ checking = false;+ };+ void refresh();+ const timer = setInterval(() => void refresh(), POLL_INTERVAL_MS);+ let previous = getDocumentActivity();+ const stopActivity = subscribeDocumentActivity(() => {+ const next = getDocumentActivity();+ const regained = (next.focused && !previous.focused) || next.visible !== previous.visible;+ previous = next;+ if (regained) void refresh();+ });+ return () => {+ disposed = true;+ clearInterval(timer);+ stopActivity();+ };+ },+ };+}++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.+ */export function usePermissionStatus<Id extends string>(check: () => Promise<Record<Id, boolean>>,initialStatus: Record<Id, boolean>,enabled = true,) {- const [status, setStatus] = useState(initialStatus);- const [error, setError] = useState<string | null>(null);- const checkLatest = useEffectEvent(check);- useEffect(() => {- if (!enabled) return;- let disposed = false;- let checking = false;- const refresh = async () => {- if (disposed || checking || document.visibilityState === "hidden") return;- checking = true;- try {- const next = await checkLatest();- if (!disposed) {- setStatus(next);- setError(null);- }- } catch {- if (!disposed) setError("Could not check permissions. We'll try again automatically.");- }- checking = false;- };- void refresh();- const timer = window.setInterval(() => void refresh(), 1500);- window.addEventListener("focus", refresh);- document.addEventListener("visibilitychange", refresh);- return () => {- disposed = true;- window.clearInterval(timer);- window.removeEventListener("focus", refresh);- document.removeEventListener("visibilitychange", refresh);- };- }, [enabled]);+ const [poller] = useState(() => createPermissionPoller(check, initialStatus));+ const { status, error } = useSyncExternalStore(+ enabled ? poller.subscribe : noopSubscribe,+ poller.getSnapshot,+ );return {status,error,diff --git a/apps/web/src/components/settings/ProjectFaviconThumbnail.tsx b/apps/web/src/components/settings/ProjectFaviconThumbnail.tsxindex 15da891fc0f..29aa103c67c 100644--- a/apps/web/src/components/settings/ProjectFaviconThumbnail.tsx+++ b/apps/web/src/components/settings/ProjectFaviconThumbnail.tsx@@ -1,7 +1,8 @@import type { EnvironmentId } from "@t3tools/contracts";-import { type ReactNode, useEffect, useRef, useState } from "react";+import { type ReactNode, useState } from "react";import { useAssetUrlState } from "~/assets/assetUrls";+import { observeIntersection } from "~/lib/observeIntersection";export function ProjectFaviconThumbnail(props: {readonly cwd: string;@@ -9,22 +10,10 @@ export function ProjectFaviconThumbnail(props: {readonly fallback: ReactNode;readonly path: string;}) {- const ref = useRef<HTMLSpanElement>(null);const [inView, setInView] = useState(() => typeof IntersectionObserver === "undefined");const [loadedUrl, setLoadedUrl] = useState<string | null>(null);const [failedUrl, setFailedUrl] = useState<string | null>(null);- // Asset URLs require a server request, so defer acquisition until the row is visible.- useEffect(() => {- const element = ref.current;- if (inView || !element) return;- const observer = new IntersectionObserver((entries) => {- if (entries.some((entry) => entry.isIntersecting)) setInView(true);- });- observer.observe(element);- return () => observer.disconnect();- }, [inView]);-const state = useAssetUrlState(props.environmentId,inView ? { _tag: "draft-workspace-file", cwd: props.cwd, path: props.path } : null,@@ -35,7 +24,20 @@ export function ProjectFaviconThumbnail(props: {const imageLoaded = showImage && loadedUrl === url;return (- <span ref={ref} className="relative flex size-8 shrink-0 items-center justify-center">+ <span+ // Asset URLs require a server request, so defer acquisition until the row is visible.+ ref={+ inView+ ? undefined+ : (node) => {+ if (!node) return;+ return observeIntersection(node, (entry) => {+ if (entry.isIntersecting) setInView(true);+ });+ }+ }+ className="relative flex size-8 shrink-0 items-center justify-center"+ >{!imageLoaded ? props.fallback : null}{showImage ? (<imgdiff --git a/apps/web/src/lib/documentActivity.ts b/apps/web/src/lib/documentActivity.tsnew file mode 100644index 00000000000..e7290a7e9bf--- /dev/null+++ b/apps/web/src/lib/documentActivity.ts@@ -0,0 +1,50 @@+export interface DocumentActivity {+ readonly visible: boolean;+ readonly focused: boolean;+}++const ALWAYS_ACTIVE: DocumentActivity = { visible: true, focused: true };++const listeners = new Set<() => void>();+let snapshot: DocumentActivity = ALWAYS_ACTIVE;++function readActivity(): DocumentActivity {+ if (typeof document === "undefined") return ALWAYS_ACTIVE;+ const visible = document.visibilityState === "visible";+ const focused = document.hasFocus();+ return snapshot.visible === visible && snapshot.focused === focused+ ? snapshot+ : { visible, focused };+}++function handleActivityEvent() {+ const next = readActivity();+ if (next === snapshot) return;+ snapshot = next;+ for (const listener of listeners) listener();+}++/** Whether the user is looking at this window: the tab is visible and the window has focus. */+export function getDocumentActivity(): DocumentActivity {+ // Without listeners the cached snapshot is not kept current.+ if (listeners.size === 0) snapshot = readActivity();+ return snapshot;+}++/** One visibilitychange/focus/blur listener set shared by every subscriber. */+export function subscribeDocumentActivity(listener: () => void): () => void {+ if (typeof document === "undefined") return () => {};+ if (listeners.size === 0) {+ snapshot = readActivity();+ document.addEventListener("visibilitychange", handleActivityEvent);+ window.addEventListener("focus", handleActivityEvent);+ window.addEventListener("blur", handleActivityEvent);+ }+ listeners.add(listener);+ return () => {+ if (!listeners.delete(listener) || listeners.size > 0) return;+ document.removeEventListener("visibilitychange", handleActivityEvent);+ window.removeEventListener("focus", handleActivityEvent);+ window.removeEventListener("blur", handleActivityEvent);+ };+}diff --git a/apps/web/src/lib/observeIntersection.test.ts b/apps/web/src/lib/observeIntersection.test.tsnew file mode 100644index 00000000000..c26409ef05c--- /dev/null+++ b/apps/web/src/lib/observeIntersection.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { observeIntersection } from "./observeIntersection";++class FakeIntersectionObserver {+ static instances: FakeIntersectionObserver[] = [];+ readonly observed = new Set<Element>();+ disconnected = false;+ constructor(+ readonly callback: (entries: IntersectionObserverEntry[]) => void,+ readonly options: IntersectionObserverInit,+ ) {+ FakeIntersectionObserver.instances.push(this);+ }+ observe(element: Element) {+ this.observed.add(element);+ }+ unobserve(element: Element) {+ this.observed.delete(element);+ }+ disconnect() {+ this.observed.clear();+ this.disconnected = true;+ }+ emit(target: Element, isIntersecting: boolean) {+ this.callback([{ target, isIntersecting } as IntersectionObserverEntry]);+ }+}++function setup() {+ FakeIntersectionObserver.instances = [];+ vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);+ return {+ [Symbol.dispose]: () => vi.unstubAllGlobals(),+ };+}++const element = (name: string) => ({ name }) as unknown as Element;++describe("observeIntersection", () => {+ it("shares one observer across elements with the same root and options", () => {+ using _globals = setup();+ const first = element("first");+ const second = element("second");+ const onFirst = vi.fn();+ const onSecond = vi.fn();++ const stopFirst = observeIntersection(first, onFirst, { rootMargin: "160px 0px" });+ const stopSecond = observeIntersection(second, onSecond, { rootMargin: "160px 0px" });+ observeIntersection(first, () => {}, { rootMargin: "600px" })();++ expect(FakeIntersectionObserver.instances).toHaveLength(2);+ const [shared] = FakeIntersectionObserver.instances;+ shared!.emit(second, true);+ expect(onFirst).not.toHaveBeenCalled();+ expect(onSecond).toHaveBeenCalledWith(expect.objectContaining({ isIntersecting: true }));++ stopFirst();+ expect(shared!.disconnected).toBe(false);+ stopSecond();+ expect(shared!.disconnected).toBe(true);+ });++ it("gives a late subscriber the current state without repeating it to earlier ones", () => {+ using _globals = setup();+ const target = element("row");+ const early = vi.fn();+ const late = vi.fn();+ observeIntersection(target, early);+ const [observer] = FakeIntersectionObserver.instances;+ observer!.emit(target, true);++ observeIntersection(target, late);+ // The browser answers a re-observe with the unchanged state.+ observer!.emit(target, true);++ expect(early).toHaveBeenCalledTimes(1);+ expect(late).toHaveBeenCalledTimes(1);++ observer!.emit(target, false);+ expect(early).toHaveBeenCalledTimes(2);+ expect(late).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/web/src/lib/observeIntersection.ts b/apps/web/src/lib/observeIntersection.tsnew file mode 100644index 00000000000..95eb3909ecf--- /dev/null+++ b/apps/web/src/lib/observeIntersection.ts@@ -0,0 +1,125 @@+type IntersectionCallback = (entry: IntersectionObserverEntry) => void;++export interface ObserveIntersectionOptions {+ /** A scroll container to intersect with instead of the viewport. */+ readonly root?: Element | null;+ readonly rootMargin?: string;+ readonly threshold?: number;+}++interface Subscription {+ readonly callback: IntersectionCallback;+ active: boolean;+}++interface Target {+ readonly subscriptions: Set<Subscription>;+ waiting: Set<Subscription> | null;+ last: IntersectionObserverEntry | null;+}++interface SharedObserver {+ readonly observer: IntersectionObserver;+ readonly targets: Map<Element, Target>;+}++// One observer per root and distinct option set.+const viewportObservers = new Map<string, SharedObserver>();+const elementRootObservers = new WeakMap<Element, Map<string, SharedObserver>>();++function deliver(shared: SharedObserver, entries: readonly IntersectionObserverEntry[]) {+ for (const entry of entries) {+ const target = shared.targets.get(entry.target);+ if (!target) continue;+ let recipients = target.subscriptions;+ if (target.waiting) {+ // Re-observing for a new subscriber redelivers an unchanged state to everyone else too.+ if (target.last?.isIntersecting === entry.isIntersecting) recipients = target.waiting;+ target.waiting = null;+ }+ target.last = entry;+ for (const subscription of recipients) {+ if (!subscription.active) continue;+ try {+ subscription.callback(entry);+ } catch (error) {+ queueMicrotask(() => {+ throw error;+ });+ }+ }+ }+}++function observersFor(root: Element): Map<string, SharedObserver> {+ let observers = elementRootObservers.get(root);+ if (!observers) {+ observers = new Map();+ elementRootObservers.set(root, observers);+ }+ return observers;+}++/**+ * Observes an element's intersection with the viewport, or with `root`, through+ * one shared IntersectionObserver per root and option set. Returns the unsubscribe, so it can be+ * returned from a ref callback.+ */+export function observeIntersection(+ element: Element,+ callback: IntersectionCallback,+ options: ObserveIntersectionOptions = {},+): () => void {+ if (typeof IntersectionObserver === "undefined") return () => {};+ const root = options.root ?? null;+ const key = `${options.rootMargin ?? ""}|${options.threshold ?? 0}`;+ const observersForRoot = root === null ? viewportObservers : observersFor(root);+ let shared = observersForRoot.get(key);+ if (!shared) {+ const targets = new Map<Element, Target>();+ const created: SharedObserver = {+ targets,+ observer: new IntersectionObserver((entries) => deliver(created, entries), {+ ...(root === null ? {} : { root }),+ ...(options.rootMargin === undefined ? {} : { rootMargin: options.rootMargin }),+ ...(options.threshold === undefined ? {} : { threshold: options.threshold }),+ }),+ };+ shared = created;+ observersForRoot.set(key, shared);+ }+ const owner = shared;+ const subscription: Subscription = { callback, active: true };+ const target = owner.targets.get(element);+ if (!target) {+ owner.targets.set(element, {+ subscriptions: new Set([subscription]),+ waiting: null,+ last: null,+ });+ owner.observer.observe(element);+ } else {+ target.subscriptions.add(subscription);+ if (target.last) {+ (target.waiting ??= new Set()).add(subscription);+ owner.observer.unobserve(element);+ owner.observer.observe(element);+ }+ }+ return () => {+ if (!subscription.active) return;+ subscription.active = false;+ const current = owner.targets.get(element);+ if (!current?.subscriptions.delete(subscription)) return;+ current.waiting?.delete(subscription);+ if (current.subscriptions.size > 0) return;+ owner.targets.delete(element);+ if (owner.targets.size > 0) {+ owner.observer.unobserve(element);+ return;+ }+ owner.observer.disconnect();+ observersForRoot.delete(key);+ if (root !== null && observersForRoot.size === 0) elementRootObservers.delete(root);+ };+}