From 8c64679c5d54bce76997482a2eeefe71fc77db03 Mon Sep 17 00:00:00 2001 From: Zakk Date: Sun, 27 Sep 2026 02:49:07 +1000 Subject: [PATCH] fix(ui): keep the near-viewport observer across inline callbacks useNearViewport rebuilt its IntersectionObserver, and called onNear again, whenever the caller passed a new function. onNear now sits in a ref read when the observer fires, so the element ref stays stable. --- src/ui/hooks.test.ts | 73 ++++++++++++++++++++++++++++++++++++++++++++ src/ui/hooks.ts | 48 +++++++++++++++-------------- 2 files changed, 98 insertions(+), 23 deletions(-) create mode 100644 src/ui/hooks.test.ts diff --git a/src/ui/hooks.test.ts b/src/ui/hooks.test.ts new file mode 100644 index 00000000..c883c2b9 --- /dev/null +++ b/src/ui/hooks.test.ts @@ -0,0 +1,73 @@ +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +// A one-component stand-in for React: hook slots persist across `render` calls, and callbacks and layout effects +// follow their dependency lists, which is all `useNearViewport` needs. +const slots: Array<{value?: unknown; deps?: unknown[]}> = []; +let slot = 0; +const same = (a: unknown[] | undefined, b: unknown[]) => a !== undefined && a.length === b.length && a.every((v, i) => Object.is(v, b[i])); +vi.mock('react', () => ({ + useState(initial: T) { + const s = (slots[slot++] ??= {value: initial}); + return [s.value, (next: T) => (s.value = next)]; + }, + useRef(initial: T) { + return (slots[slot++] ??= {value: {current: initial}}).value as {current: T}; + }, + useCallback(fn: T, deps: unknown[]) { + const s = (slots[slot++] ??= {}); + if (!same(s.deps, deps)) Object.assign(s, {value: fn, deps}); + return s.value as T; + }, + useLayoutEffect(fn: () => void, deps: unknown[]) { + const s = (slots[slot++] ??= {}); + if (!same(s.deps, deps)) { + s.deps = deps; + fn(); + } + }, + useEffect() {} +})); + +const {useNearViewport} = await import('./hooks'); +const rewind = () => { + slot = 0; +}; +// Each call is one render of the same component. +const useRender = (onNear: () => void) => { + rewind(); + return useNearViewport(onNear); +}; + +describe('useNearViewport', () => { + const observers: Array<(entries: Array<{isIntersecting: boolean}>) => void> = []; + beforeEach(() => { + slots.length = 0; + observers.length = 0; + vi.stubGlobal('innerHeight', 800); + vi.stubGlobal( + 'IntersectionObserver', + class { + constructor(report: (entries: Array<{isIntersecting: boolean}>) => void) { + observers.push(report); + } + observe() {} + disconnect() {} + } + ); + }); + afterEach(() => vi.unstubAllGlobals()); + + it('keeps one observer for an inline onNear and calls the latest one', () => { + const first = vi.fn(); + const [ref] = useRender(first); + ref({getBoundingClientRect: () => ({top: 0, bottom: 100})} as unknown as HTMLElement); + expect(first).toHaveBeenCalledTimes(1); + const second = vi.fn(); + // The same ref means React keeps the element attached and builds no second observer. + expect(useRender(second)[0]).toBe(ref); + observers[0]([{isIntersecting: true}]); + expect(second).toHaveBeenCalledTimes(1); + expect(first).toHaveBeenCalledTimes(1); + expect(observers).toHaveLength(1); + }); +}); diff --git a/src/ui/hooks.ts b/src/ui/hooks.ts index 311cb9e4..aa6b7124 100644 --- a/src/ui/hooks.ts +++ b/src/ui/hooks.ts @@ -194,29 +194,31 @@ const nearMargin = 400; // Whether the element is within `nearMargin` of the viewport; `onNear` runs each time it comes near. export function useNearViewport(onNear?: () => void) { const [near, setNear] = useState(false); - const ref = useCallback( - (element: HTMLElement | null) => { - if (!element) return; - // An element that mounts on screen reads as near in the first frame; waiting for the observer's first report - // would paint the placeholder for a frame and make the page jump. - const box = element.getBoundingClientRect(); - if (box.top < innerHeight + nearMargin && box.bottom > -nearMargin) { - setNear(true); - onNear?.(); - } - const observer = new IntersectionObserver( - entries => { - const next = entries.at(-1)!.isIntersecting; - setNear(next); - if (next) onNear?.(); - }, - {rootMargin: `${nearMargin}px`} - ); - observer.observe(element); - return () => observer.disconnect(); - }, - [onNear] - ); + // Read when it fires, so an inline `onNear` keeps the same observer across renders. + const latest = useRef(onNear); + useLayoutEffect(() => { + latest.current = onNear; + }, [onNear]); + const ref = useCallback((element: HTMLElement | null) => { + if (!element) return; + // An element that mounts on screen reads as near in the first frame; waiting for the observer's first report + // would paint the placeholder for a frame and make the page jump. + const box = element.getBoundingClientRect(); + if (box.top < innerHeight + nearMargin && box.bottom > -nearMargin) { + setNear(true); + latest.current?.(); + } + const observer = new IntersectionObserver( + entries => { + const next = entries.at(-1)!.isIntersecting; + setNear(next); + if (next) latest.current?.(); + }, + {rootMargin: `${nearMargin}px`} + ); + observer.observe(element); + return () => observer.disconnect(); + }, []); return [ref, near] as const; }