From 64f72b4a1695f8d915cd4031648810b50aa7f202 Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Fri, 13 Nov 2026 14:19:48 -0600 Subject: [PATCH 1/5] feat: add useScrollAnchor with an interactive demo Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/safari-scroll-anchor.md | 5 + .../hooks/__tests__/useScrollAnchor.test.tsx | 107 ++++++++++++++++++ packages/react/src/hooks/index.ts | 2 + .../src/hooks/useScrollAnchor.hookDocs.json | 22 ++++ packages/react/src/hooks/useScrollAnchor.ts | 62 ++++++++++ packages/react/src/index.ts | 1 + .../stories/ScrollAnchor.stories.module.css | 45 ++++++++ .../src/stories/useScrollAnchor.stories.tsx | 64 +++++++++++ 8 files changed, 308 insertions(+) create mode 100644 .changeset/safari-scroll-anchor.md create mode 100644 packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx create mode 100644 packages/react/src/hooks/useScrollAnchor.hookDocs.json create mode 100644 packages/react/src/hooks/useScrollAnchor.ts create mode 100644 packages/react/src/stories/ScrollAnchor.stories.module.css create mode 100644 packages/react/src/stories/useScrollAnchor.stories.tsx diff --git a/.changeset/safari-scroll-anchor.md b/.changeset/safari-scroll-anchor.md new file mode 100644 index 00000000000..9b1cdb83dc4 --- /dev/null +++ b/.changeset/safari-scroll-anchor.md @@ -0,0 +1,5 @@ +--- +'@primer/react': minor +--- + +useScrollAnchor: Preserve an element's viewport position as its container content changes. diff --git a/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx b/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx new file mode 100644 index 00000000000..d5558d1a34c --- /dev/null +++ b/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx @@ -0,0 +1,107 @@ +import {act, render, waitFor} from '@testing-library/react' +import {useRef} from 'react' +import {expect, it, vi} from 'vitest' +import {useScrollAnchor} from '../../hooks/useScrollAnchor' + +function ScrollRegion({getAnchorTop, anchorVersion = 'initial'}: {getAnchorTop: () => number; anchorVersion?: string}) { + const containerRef = useRef(null) + const anchorRef = useRef(null) + + useScrollAnchor({containerRef, anchorRef}) + + return ( +
+
{ + anchorRef.current = node + if (node) { + vi.spyOn(node, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, getAnchorTop(), 100, 20)) + } + }} + data-testid="anchor" + /> +
+ ) +} + +it('preserves the anchor position when content changes above it', async () => { + const anchor = {top: 300} + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_x, y) => { + anchor.top -= y + }) + + const {container} = render( anchor.top} />) + + await act(async () => { + container.firstElementChild?.prepend(document.createElement('div')) + anchor.top += 48 + }) + + await waitFor(() => { + expect(scrollBy).toHaveBeenCalledWith(0, 48) + }) + expect(anchor.top).toBe(300) + + scrollBy.mockRestore() +}) + +it('uses the latest anchor position after the user scrolls', async () => { + const anchor = {top: 300} + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_x, y) => { + anchor.top -= y + }) + + const {container} = render( anchor.top} />) + + anchor.top = 240 + act(() => { + window.dispatchEvent(new Event('scroll')) + }) + + await act(async () => { + container.firstElementChild?.prepend(document.createElement('div')) + anchor.top += 20 + }) + + await waitFor(() => { + expect(scrollBy).toHaveBeenCalledWith(0, 20) + }) + expect(anchor.top).toBe(240) + + scrollBy.mockRestore() +}) + +it('does not adjust scroll when the anchor position is unchanged', async () => { + const scrollBy = vi.spyOn(window, 'scrollBy') + const {container} = render( 0} />) + + await act(async () => { + container.firstElementChild?.prepend(document.createElement('div')) + }) + + await waitFor(() => { + expect(container.firstElementChild?.children).toHaveLength(2) + }) + expect(scrollBy).not.toHaveBeenCalled() + + scrollBy.mockRestore() +}) + +it('preserves the position when the anchor element is replaced', async () => { + const anchor = {top: 300} + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_x, y) => { + anchor.top -= y + }) + + const {rerender} = render( anchor.top} />) + anchor.top += 32 + rerender( anchor.top} anchorVersion="updated" />) + + await waitFor(() => { + expect(scrollBy).toHaveBeenCalledWith(0, 32) + }) + expect(anchor.top).toBe(300) + + scrollBy.mockRestore() +}) diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.ts index eece539e4a4..1af5668d692 100644 --- a/packages/react/src/hooks/index.ts +++ b/packages/react/src/hooks/index.ts @@ -17,4 +17,6 @@ export {useRefObjectAsForwardedRef} from './useRefObjectAsForwardedRef' export {useId} from './useId' export {useIsMacOS} from './useIsMacOS' export {useMergedRefs} from './useMergedRefs' +export {useScrollAnchor} from './useScrollAnchor' +export type {UseScrollAnchorSettings} from './useScrollAnchor' export {useSlots} from './useSlots' diff --git a/packages/react/src/hooks/useScrollAnchor.hookDocs.json b/packages/react/src/hooks/useScrollAnchor.hookDocs.json new file mode 100644 index 00000000000..44fcba56869 --- /dev/null +++ b/packages/react/src/hooks/useScrollAnchor.hookDocs.json @@ -0,0 +1,22 @@ +{ + "name": "useScrollAnchor", + "importPath": "@primer/react", + "stories": [{"id": "hooks-usescrollanchor--scroll-anchor"}], + "parameters": [ + { + "name": "containerRef", + "type": "RefObject", + "required": true, + "description": "A ref to the container whose DOM changes should be observed." + }, + { + "name": "anchorRef", + "type": "RefObject", + "required": true, + "description": "A ref to the visible element whose viewport position should be preserved. Only window scrolling is adjusted." + } + ], + "returns": { + "type": "void" + } +} diff --git a/packages/react/src/hooks/useScrollAnchor.ts b/packages/react/src/hooks/useScrollAnchor.ts new file mode 100644 index 00000000000..82d0aabdc6b --- /dev/null +++ b/packages/react/src/hooks/useScrollAnchor.ts @@ -0,0 +1,62 @@ +import type {RefObject} from 'react' +import useIsomorphicLayoutEffect from '../utils/useIsomorphicLayoutEffect' + +export interface UseScrollAnchorSettings { + containerRef: RefObject + anchorRef: RefObject +} + +/** + * Preserves the viewport position of an anchor when content in its container changes. + * The anchor should be a visible element, and this hook only adjusts the window scroll position. + * + * @param containerRef A ref to the container whose DOM changes should be observed. + * @param anchorRef A ref to the visible element whose viewport position should be preserved. + */ +export function useScrollAnchor({containerRef, anchorRef}: UseScrollAnchorSettings): void { + useIsomorphicLayoutEffect(() => { + const container = containerRef.current + const initialAnchor = anchorRef.current + + if (!container || !initialAnchor || !container.contains(initialAnchor)) { + return + } + + let anchorTop = initialAnchor.getBoundingClientRect().top + + const updateAnchorTop = () => { + const anchor = anchorRef.current + if (anchor && container.contains(anchor)) { + anchorTop = anchor.getBoundingClientRect().top + } + } + + const observer = new MutationObserver(() => { + const anchor = anchorRef.current + if (!anchor || !container.contains(anchor)) { + return + } + + const currentTop = anchor.getBoundingClientRect().top + const offset = currentTop - anchorTop + + if (offset !== 0) { + window.scrollBy(0, offset) + anchorTop = currentTop - offset + } + }) + + observer.observe(container, { + attributes: true, + characterData: true, + childList: true, + subtree: true, + }) + window.addEventListener('scroll', updateAnchorTop, {passive: true}) + + return () => { + observer.disconnect() + window.removeEventListener('scroll', updateAnchorTop) + } + }, [anchorRef, containerRef]) +} diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 48750d9e583..bd8aca950de 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -53,6 +53,7 @@ export type {FocusZoneHookSettings} from './hooks/useFocusZone' export {useRefObjectAsForwardedRef} from './hooks/useRefObjectAsForwardedRef' export {useMergedRefs} from './hooks/useMergedRefs' export {useResizeObserver} from './hooks/useResizeObserver' +export {useScrollAnchor, type UseScrollAnchorSettings} from './hooks/useScrollAnchor' export {useResponsiveValue, type ResponsiveValue} from './hooks/useResponsiveValue' export {default as useIsomorphicLayoutEffect} from './utils/useIsomorphicLayoutEffect' export {useProvidedRefOrCreate} from './hooks/useProvidedRefOrCreate' diff --git a/packages/react/src/stories/ScrollAnchor.stories.module.css b/packages/react/src/stories/ScrollAnchor.stories.module.css new file mode 100644 index 00000000000..532c15bcbae --- /dev/null +++ b/packages/react/src/stories/ScrollAnchor.stories.module.css @@ -0,0 +1,45 @@ +.Root { + padding: var(--base-size-16); + color: var(--fgColor-default); +} + +.Instructions { + margin: 0 0 var(--base-size-16); +} + +.Controls { + position: sticky; + top: 0; + z-index: 1; + display: flex; + align-items: center; + gap: var(--base-size-8); + padding: var(--base-size-8); + border: var(--borderWidth-thin) solid var(--borderColor-default); + border-radius: var(--borderRadius-medium); + background: var(--bgColor-default); +} + +.Status { + margin-left: auto; +} + +.Timeline { + margin-top: var(--base-size-16); + border: var(--borderWidth-thin) solid var(--borderColor-default); + border-radius: var(--borderRadius-medium); +} + +.Item { + min-height: 5rem; + padding: var(--base-size-16); + border-bottom: var(--borderWidth-thin) solid var(--borderColor-muted); +} + +.Item:last-child { + border-bottom: 0; +} + +.Anchor { + background: var(--bgColor-attention-muted); +} diff --git a/packages/react/src/stories/useScrollAnchor.stories.tsx b/packages/react/src/stories/useScrollAnchor.stories.tsx new file mode 100644 index 00000000000..95035b70c69 --- /dev/null +++ b/packages/react/src/stories/useScrollAnchor.stories.tsx @@ -0,0 +1,64 @@ +import React, {useRef, useState} from 'react' +import type {Meta} from '@storybook/react-vite' +import {Button} from '../Button' +import {useScrollAnchor} from '../hooks/useScrollAnchor' +import classes from './ScrollAnchor.stories.module.css' + +export default { + title: 'Hooks/useScrollAnchor', +} as Meta + +export const ScrollAnchor = () => { + const [enabled, setEnabled] = useState(true) + const [loadedPages, setLoadedPages] = useState(0) + const containerRef = useRef(null) + const anchorRef = useRef(null) + const disabledAnchorRef = useRef(null) + + useScrollAnchor({containerRef, anchorRef: enabled ? anchorRef : disabledAnchorRef}) + + const olderComments = Array.from({length: loadedPages * 3}, (_, index) => `Earlier comment ${index + 1}`) + + return ( + <> + +
+

+ Scroll until the highlighted comment is in view, then load earlier comments. Toggle the hook to compare how + the comment moves. Native browser scroll anchoring is disabled in this story so the hook's effect is visible + in every browser. +

+

+ {'useScrollAnchor({containerRef, anchorRef})'} watches the timeline container and preserves the + highlighted comment's viewport position. It adjusts window scrolling only. +

+
+ + + Hook is {enabled ? 'on' : 'off'} +
+
+ {olderComments.map(comment => ( +
+ {comment} +
+ ))} + {['Comment 1', 'Comment 2', 'Comment 3'].map(comment => ( +
+ {comment} +
+ ))} +
+ You're reading this comment +

Keep this comment at the same viewport position while content is added above it.

+
+ {Array.from({length: 12}, (_, index) => ( +
+ Comment {index + 4} +
+ ))} +
+
+ + ) +} From dd1192ce47ca81aea16390da435c9418f5f535c8 Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Fri, 13 Nov 2026 16:11:57 -0600 Subject: [PATCH 2/5] fix: resolve scroll anchor CI failures Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/__tests__/__snapshots__/exports.test.ts.snap | 2 ++ .../react/src/hooks/__tests__/useScrollAnchor.test.tsx | 2 +- packages/react/src/hooks/useScrollAnchor.ts | 3 ++- packages/react/src/stories/useScrollAnchor.stories.tsx | 8 ++++---- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/react/src/__tests__/__snapshots__/exports.test.ts.snap b/packages/react/src/__tests__/__snapshots__/exports.test.ts.snap index ee096520739..faddf3c3548 100644 --- a/packages/react/src/__tests__/__snapshots__/exports.test.ts.snap +++ b/packages/react/src/__tests__/__snapshots__/exports.test.ts.snap @@ -254,6 +254,8 @@ exports[`@primer/react > should not update exports without a semver change 1`] = "useResponsiveValue", "useRovingTabIndex", "useSafeTimeout", + "useScrollAnchor", + "UseScrollAnchorSettings", "useSlots", "useSyncedState", "useTheme", diff --git a/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx b/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx index d5558d1a34c..1d66b12860e 100644 --- a/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx +++ b/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx @@ -5,7 +5,7 @@ import {useScrollAnchor} from '../../hooks/useScrollAnchor' function ScrollRegion({getAnchorTop, anchorVersion = 'initial'}: {getAnchorTop: () => number; anchorVersion?: string}) { const containerRef = useRef(null) - const anchorRef = useRef(null) + const anchorRef = useRef(null) useScrollAnchor({containerRef, anchorRef}) diff --git a/packages/react/src/hooks/useScrollAnchor.ts b/packages/react/src/hooks/useScrollAnchor.ts index 82d0aabdc6b..e6313b18bda 100644 --- a/packages/react/src/hooks/useScrollAnchor.ts +++ b/packages/react/src/hooks/useScrollAnchor.ts @@ -52,7 +52,8 @@ export function useScrollAnchor({containerRef, anchorRef}: UseScrollAnchorSettin childList: true, subtree: true, }) - window.addEventListener('scroll', updateAnchorTop, {passive: true}) + // eslint-disable-next-line github/prefer-observers -- Track every scroll position to preserve the anchor's current viewport position. + window.addEventListener('scroll', updateAnchorTop) return () => { observer.disconnect() diff --git a/packages/react/src/stories/useScrollAnchor.stories.tsx b/packages/react/src/stories/useScrollAnchor.stories.tsx index 95035b70c69..52c9e3c62ec 100644 --- a/packages/react/src/stories/useScrollAnchor.stories.tsx +++ b/packages/react/src/stories/useScrollAnchor.stories.tsx @@ -25,12 +25,12 @@ export const ScrollAnchor = () => {

Scroll until the highlighted comment is in view, then load earlier comments. Toggle the hook to compare how - the comment moves. Native browser scroll anchoring is disabled in this story so the hook's effect is visible - in every browser. + the comment moves. Native browser scroll anchoring is disabled in this story so the hook's effect is + visible in every browser.

{'useScrollAnchor({containerRef, anchorRef})'} watches the timeline container and preserves the - highlighted comment's viewport position. It adjusts window scrolling only. + highlighted comment's viewport position. It adjusts window scrolling only.

@@ -49,7 +49,7 @@ export const ScrollAnchor = () => {
))}
- You're reading this comment + You're reading this comment

Keep this comment at the same viewport position while content is added above it.

{Array.from({length: 12}, (_, index) => ( From 4c9d245a795136ee8b90c4827b043b097a74f8fd Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Tue, 17 Nov 2026 13:55:05 -0600 Subject: [PATCH 3/5] fix: preserve scroll anchors across layout changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../hooks/__tests__/useScrollAnchor.test.tsx | 294 +++++++++++++++--- .../src/hooks/useScrollAnchor.hookDocs.json | 18 +- packages/react/src/hooks/useScrollAnchor.ts | 129 ++++++-- .../src/stories/useScrollAnchor.stories.tsx | 19 +- 4 files changed, 379 insertions(+), 81 deletions(-) diff --git a/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx b/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx index 1d66b12860e..d7cb36d418b 100644 --- a/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx +++ b/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx @@ -1,34 +1,47 @@ import {act, render, waitFor} from '@testing-library/react' -import {useRef} from 'react' +import {useCallback, useState} from 'react' import {expect, it, vi} from 'vitest' +import {page, userEvent} from 'vitest/browser' import {useScrollAnchor} from '../../hooks/useScrollAnchor' -function ScrollRegion({getAnchorTop, anchorVersion = 'initial'}: {getAnchorTop: () => number; anchorVersion?: string}) { - const containerRef = useRef(null) - const anchorRef = useRef(null) +function ScrollRegion({ + getAnchorTop, + anchorVersion = 'initial', + mounted = true, + anchorKey, + containerVersion = 'initial', +}: { + getAnchorTop: () => number + anchorVersion?: string + mounted?: boolean + anchorKey?: string + containerVersion?: string +}) { + const [container, setContainer] = useState(null) + const [anchor, setAnchor] = useState(null) + const anchorRef = useCallback( + (node: HTMLDivElement | null) => { + if (node) { + vi.spyOn(node, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, getAnchorTop(), 100, 20)) + } + setAnchor(node) + }, + [getAnchorTop], + ) - useScrollAnchor({containerRef, anchorRef}) + useScrollAnchor({container, anchor, anchorKey}) - return ( -
-
{ - anchorRef.current = node - if (node) { - vi.spyOn(node, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, getAnchorTop(), 100, 20)) - } - }} - data-testid="anchor" - /> + return mounted ? ( +
+
- ) + ) : null } it('preserves the anchor position when content changes above it', async () => { const anchor = {top: 300} - const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_x, y) => { - anchor.top -= y + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => { + anchor.top = 300 }) const {container} = render( anchor.top} />) @@ -39,19 +52,17 @@ it('preserves the anchor position when content changes above it', async () => { }) await waitFor(() => { - expect(scrollBy).toHaveBeenCalledWith(0, 48) + expect(scrollBy).toHaveBeenCalledWith({top: 48, behavior: 'instant'}) }) expect(anchor.top).toBe(300) - scrollBy.mockRestore() }) it('uses the latest anchor position after the user scrolls', async () => { const anchor = {top: 300} - const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_x, y) => { - anchor.top -= y + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => { + anchor.top = 240 }) - const {container} = render( anchor.top} />) anchor.top = 240 @@ -65,10 +76,9 @@ it('uses the latest anchor position after the user scrolls', async () => { }) await waitFor(() => { - expect(scrollBy).toHaveBeenCalledWith(0, 20) + expect(scrollBy).toHaveBeenCalledWith({top: 20, behavior: 'instant'}) }) expect(anchor.top).toBe(240) - scrollBy.mockRestore() }) @@ -79,29 +89,241 @@ it('does not adjust scroll when the anchor position is unchanged', async () => { await act(async () => { container.firstElementChild?.prepend(document.createElement('div')) }) + expect(scrollBy).not.toHaveBeenCalled() + scrollBy.mockRestore() +}) - await waitFor(() => { - expect(container.firstElementChild?.children).toHaveLength(2) +it('starts observing when the container and anchor mount later and when the container changes', async () => { + const anchor = {top: 300} + const getAnchorTop = () => anchor.top + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => { + anchor.top = 300 }) - expect(scrollBy).not.toHaveBeenCalled() + const {container, rerender} = render() + rerender() + + await act(async () => { + container.firstElementChild?.prepend(document.createElement('div')) + anchor.top += 20 + }) + expect(scrollBy).toHaveBeenCalledWith({top: 20, behavior: 'instant'}) + scrollBy.mockClear() + rerender() + await act(async () => { + container.firstElementChild?.prepend(document.createElement('div')) + anchor.top += 30 + }) + expect(scrollBy).toHaveBeenCalledWith({top: 30, behavior: 'instant'}) scrollBy.mockRestore() }) -it('preserves the position when the anchor element is replaced', async () => { +function NestedMount({getAnchorTop}: {getAnchorTop: () => number}) { + const [container, setContainer] = useState(null) + const [anchor, setAnchor] = useState(null) + const anchorRef = useCallback( + (node: HTMLDivElement | null) => { + if (node) { + vi.spyOn(node, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, getAnchorTop(), 100, 20)) + } + setAnchor(node) + }, + [getAnchorTop], + ) + useScrollAnchor({container, anchor}) + return +} + +function NestedMountContent({ + containerRef, + anchorRef, +}: { + containerRef: (element: HTMLDivElement | null) => void + anchorRef: (element: HTMLDivElement | null) => void +}) { + const [stage, setStage] = useState(0) + return ( + <> + + {stage > 0 && ( +
+ {stage > 1 &&
} +
+ )} + + ) +} + +it('observes nodes mounted by a child after the hook first renders', async () => { const anchor = {top: 300} - const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_x, y) => { - anchor.top -= y + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => { + anchor.top = 300 + }) + const {getByTestId} = render( anchor.top} />) + + await userEvent.click(page.getByRole('button', {name: 'Mount timeline'})) + await userEvent.click(page.getByRole('button', {name: 'Mount anchor'})) + await act(async () => { + getByTestId('late-container').prepend(document.createElement('div')) + anchor.top += 25 }) - const {rerender} = render( anchor.top} />) + expect(scrollBy).toHaveBeenCalledWith({top: 25, behavior: 'instant'}) + scrollBy.mockRestore() +}) + +it('preserves the position when the same keyed anchor element is replaced', async () => { + const anchor = {top: 300} + const getAnchorTop = () => anchor.top + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => { + anchor.top = 300 + }) + const {rerender} = render() + anchor.top += 32 - rerender( anchor.top} anchorVersion="updated" />) + rerender() await waitFor(() => { - expect(scrollBy).toHaveBeenCalledWith(0, 32) + expect(scrollBy).toHaveBeenCalledWith({top: 32, behavior: 'instant'}) }) expect(anchor.top).toBe(300) + scrollBy.mockRestore() +}) + +function SelectableAnchors({selected}: {selected: 'first' | 'second'}) { + const [container, setContainer] = useState(null) + const [first, setFirst] = useState(null) + const [second, setSecond] = useState(null) + useScrollAnchor({container, anchor: selected === 'first' ? first : second}) + return ( +
+
+
+
+ ) +} + +it('starts a new baseline when selecting another mounted anchor', async () => { + const scrollBy = vi.spyOn(window, 'scrollBy') + const {container, rerender} = render() + rerender() + + await act(async () => { + container.firstElementChild?.setAttribute('data-updated', 'true') + }) + expect(scrollBy).not.toHaveBeenCalled() + scrollBy.mockRestore() +}) + +it('starts a new baseline when an element is reused for a different anchor key', async () => { + const anchor = {top: 100} + const getAnchorTop = () => anchor.top + const scrollBy = vi.spyOn(window, 'scrollBy') + const {container, rerender} = render() + + anchor.top = 300 + rerender() + await act(async () => { + container.firstElementChild?.setAttribute('data-updated', 'true') + }) + + expect(scrollBy).not.toHaveBeenCalled() scrollBy.mockRestore() }) + +function RealScrollRegion() { + const [container, setContainer] = useState(null) + const [anchor, setAnchor] = useState(null) + useScrollAnchor({container, anchor}) + return ( +
+
+
+ Anchor +
+
+
+ ) +} + +it('does not double-correct when the browser provides native scroll anchoring', async () => { + const previousAnchor = document.documentElement.style.overflowAnchor + document.documentElement.style.overflowAnchor = 'auto' + try { + const {getByTestId} = render() + const anchor = getByTestId('anchor') + await new Promise(resolve => { + // eslint-disable-next-line github/prefer-observers -- Wait until the hook has captured the programmatic scroll. + window.addEventListener('scroll', () => resolve(), {once: true}) + window.scrollTo({top: 400, behavior: 'instant'}) + }) + const top = anchor.getBoundingClientRect().top + + getByTestId('growing-content').style.height = '700px' + await expect.poll(() => window.scrollY).toBe(500) + expect(Math.abs(anchor.getBoundingClientRect().top - top)).toBeLessThan(1) + } finally { + document.documentElement.style.overflowAnchor = previousAnchor + window.scrollTo({top: 0, behavior: 'instant'}) + } +}) + +it('preserves position after layout-only growth, using instant scrolling even with smooth scrolling enabled', async () => { + const previousAnchor = document.documentElement.style.overflowAnchor + const previousBehavior = document.documentElement.style.scrollBehavior + document.documentElement.style.overflowAnchor = 'none' + document.documentElement.style.scrollBehavior = 'smooth' + const scrollBy = vi.spyOn(window, 'scrollBy') + const stylesheet = document.createElement('style') + + try { + const {getByTestId} = render() + const anchor = getByTestId('anchor') + await new Promise(resolve => { + // eslint-disable-next-line github/prefer-observers -- Wait until the hook has captured the programmatic scroll. + window.addEventListener('scroll', () => resolve(), {once: true}) + window.scrollTo({top: 400, behavior: 'instant'}) + }) + const top = anchor.getBoundingClientRect().top + + stylesheet.textContent = '[data-testid="growing-content"] { height: 700px !important; }' + document.head.append(stylesheet) + await expect.poll(() => Math.abs(anchor.getBoundingClientRect().top - top)).toBeLessThan(1) + expect(scrollBy).toHaveBeenCalledWith({top: 100, behavior: 'instant'}) + } finally { + stylesheet.remove() + scrollBy.mockRestore() + document.documentElement.style.overflowAnchor = previousAnchor + document.documentElement.style.scrollBehavior = previousBehavior + window.scrollTo({top: 0, behavior: 'instant'}) + } +}) + +it('updates the baseline when a correction is clamped at the top of the page', async () => { + const previousAnchor = document.documentElement.style.overflowAnchor + document.documentElement.style.overflowAnchor = 'none' + window.scrollTo({top: 0, behavior: 'instant'}) + const scrollBy = vi.spyOn(window, 'scrollBy') + + try { + const {getByTestId} = render() + const anchor = getByTestId('anchor') + const content = getByTestId('growing-content') + + content.style.height = '500px' + await expect.poll(() => scrollBy.mock.calls.length).toBeGreaterThan(0) + expect(window.scrollY).toBe(0) + const top = anchor.getBoundingClientRect().top + + content.style.height = '600px' + await expect.poll(() => Math.abs(anchor.getBoundingClientRect().top - top)).toBeLessThan(1) + expect(window.scrollY).toBe(100) + } finally { + scrollBy.mockRestore() + document.documentElement.style.overflowAnchor = previousAnchor + window.scrollTo({top: 0, behavior: 'instant'}) + } +}) diff --git a/packages/react/src/hooks/useScrollAnchor.hookDocs.json b/packages/react/src/hooks/useScrollAnchor.hookDocs.json index 44fcba56869..31ea0e84449 100644 --- a/packages/react/src/hooks/useScrollAnchor.hookDocs.json +++ b/packages/react/src/hooks/useScrollAnchor.hookDocs.json @@ -4,16 +4,22 @@ "stories": [{"id": "hooks-usescrollanchor--scroll-anchor"}], "parameters": [ { - "name": "containerRef", - "type": "RefObject", + "name": "container", + "type": "HTMLElement | null", "required": true, - "description": "A ref to the container whose DOM changes should be observed." + "description": "The container to observe. Use a callback ref backed by state to track when it mounts or changes." }, { - "name": "anchorRef", - "type": "RefObject", + "name": "anchor", + "type": "HTMLElement | null", "required": true, - "description": "A ref to the visible element whose viewport position should be preserved. Only window scrolling is adjusted." + "description": "The visible element whose viewport position should be preserved. Use a callback ref backed by state. Only window scrolling is adjusted." + }, + { + "name": "anchorKey", + "type": "string | number", + "required": false, + "description": "A stable identity for the anchor, used to preserve its position if its DOM element is replaced. Changing the key starts a new baseline." } ], "returns": { diff --git a/packages/react/src/hooks/useScrollAnchor.ts b/packages/react/src/hooks/useScrollAnchor.ts index e6313b18bda..d3298ee7016 100644 --- a/packages/react/src/hooks/useScrollAnchor.ts +++ b/packages/react/src/hooks/useScrollAnchor.ts @@ -1,63 +1,132 @@ -import type {RefObject} from 'react' +import {useRef} from 'react' import useIsomorphicLayoutEffect from '../utils/useIsomorphicLayoutEffect' export interface UseScrollAnchorSettings { - containerRef: RefObject - anchorRef: RefObject + container: HTMLElement | null + anchor: HTMLElement | null + anchorKey?: string | number } /** - * Preserves the viewport position of an anchor when content in its container changes. - * The anchor should be a visible element, and this hook only adjusts the window scroll position. + * Preserves an anchor's viewport position when content in its container changes. + * The anchor should be visible. Only window scrolling is adjusted. * - * @param containerRef A ref to the container whose DOM changes should be observed. - * @param anchorRef A ref to the visible element whose viewport position should be preserved. + * Pass reactive elements, for example from callback refs backed by state. Provide + * the same anchorKey when the same logical anchor may be rendered as a new element. + * Without a key, a different element starts a new baseline. Passing a null anchor + * also resets the baseline. */ -export function useScrollAnchor({containerRef, anchorRef}: UseScrollAnchorSettings): void { +export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorSettings): void { + const selection = useRef({anchor, anchorKey}) + const updateSelection = useRef<(() => void) | null>(null) + useIsomorphicLayoutEffect(() => { - const container = containerRef.current - const initialAnchor = anchorRef.current + selection.current = {anchor, anchorKey} + }) - if (!container || !initialAnchor || !container.contains(initialAnchor)) { + useIsomorphicLayoutEffect(() => { + if (!container) { return } - let anchorTop = initialAnchor.getBoundingClientRect().top + const root = container + let trackedAnchor: HTMLElement | null = null + let trackedKey: HTMLElement | string | number | null = null + let anchorTop: number | null = null + const observed = new Set() + const resizeObserver = new ResizeObserver(() => correctPosition()) - const updateAnchorTop = () => { - const anchor = anchorRef.current - if (anchor && container.contains(anchor)) { - anchorTop = anchor.getBoundingClientRect().top + function observeLayout() { + const elements = new Set([root]) + let element: Element | null = trackedAnchor + while (element && element !== root) { + const parent: Element | null = element.parentElement + if (!parent || !root.contains(parent)) break + for (const child of parent.children) elements.add(child) + element = parent + } + + for (const element of observed) { + if (!elements.has(element)) { + resizeObserver.unobserve(element) + observed.delete(element) + } + } + for (const element of elements) { + if (!observed.has(element)) { + resizeObserver.observe(element) + observed.add(element) + } } } - const observer = new MutationObserver(() => { - const anchor = anchorRef.current - if (!anchor || !container.contains(anchor)) { - return + function synchronizeSelection() { + const {anchor: nextAnchor, anchorKey: nextKey} = selection.current + if (!nextAnchor) { + const hadAnchor = trackedAnchor !== null + trackedAnchor = null + trackedKey = null + anchorTop = null + if (hadAnchor) observeLayout() + return false + } + if (!root.contains(nextAnchor)) { + return false + } + + const key = nextKey ?? nextAnchor + if (key !== trackedKey) { + anchorTop = nextAnchor.getBoundingClientRect().top + } + if (nextAnchor !== trackedAnchor || key !== trackedKey) { + trackedAnchor = nextAnchor + trackedKey = key + observeLayout() } + return true + } - const currentTop = anchor.getBoundingClientRect().top - const offset = currentTop - anchorTop + function correctPosition() { + if (!synchronizeSelection() || !trackedAnchor || anchorTop === null) return + const offset = trackedAnchor.getBoundingClientRect().top - anchorTop if (offset !== 0) { - window.scrollBy(0, offset) - anchorTop = currentTop - offset + window.scrollBy({top: offset, behavior: 'instant'}) + anchorTop = trackedAnchor.getBoundingClientRect().top } - }) + } - observer.observe(container, { + function capturePosition() { + if (synchronizeSelection() && trackedAnchor) { + anchorTop = trackedAnchor.getBoundingClientRect().top + } + } + + const mutationObserver = new MutationObserver(() => { + observeLayout() + correctPosition() + }) + mutationObserver.observe(root, { attributes: true, characterData: true, childList: true, subtree: true, }) + observeLayout() + updateSelection.current = correctPosition + correctPosition() // eslint-disable-next-line github/prefer-observers -- Track every scroll position to preserve the anchor's current viewport position. - window.addEventListener('scroll', updateAnchorTop) + window.addEventListener('scroll', capturePosition) return () => { - observer.disconnect() - window.removeEventListener('scroll', updateAnchorTop) + updateSelection.current = null + mutationObserver.disconnect() + resizeObserver.disconnect() + window.removeEventListener('scroll', capturePosition) } - }, [anchorRef, containerRef]) + }, [container]) + + useIsomorphicLayoutEffect(() => { + updateSelection.current?.() + }, [container, anchor, anchorKey]) } diff --git a/packages/react/src/stories/useScrollAnchor.stories.tsx b/packages/react/src/stories/useScrollAnchor.stories.tsx index 52c9e3c62ec..3e89ea7c5e8 100644 --- a/packages/react/src/stories/useScrollAnchor.stories.tsx +++ b/packages/react/src/stories/useScrollAnchor.stories.tsx @@ -1,4 +1,4 @@ -import React, {useRef, useState} from 'react' +import React, {useState} from 'react' import type {Meta} from '@storybook/react-vite' import {Button} from '../Button' import {useScrollAnchor} from '../hooks/useScrollAnchor' @@ -11,11 +11,10 @@ export default { export const ScrollAnchor = () => { const [enabled, setEnabled] = useState(true) const [loadedPages, setLoadedPages] = useState(0) - const containerRef = useRef(null) - const anchorRef = useRef(null) - const disabledAnchorRef = useRef(null) + const [container, setContainer] = useState(null) + const [anchor, setAnchor] = useState(null) - useScrollAnchor({containerRef, anchorRef: enabled ? anchorRef : disabledAnchorRef}) + useScrollAnchor({container, anchor: enabled ? anchor : null}) const olderComments = Array.from({length: loadedPages * 3}, (_, index) => `Earlier comment ${index + 1}`) @@ -29,15 +28,17 @@ export const ScrollAnchor = () => { visible in every browser.

- {'useScrollAnchor({containerRef, anchorRef})'} watches the timeline container and preserves the - highlighted comment's viewport position. It adjusts window scrolling only. + {'useScrollAnchor({container, anchor})'} watches the timeline container and preserves the + highlighted comment's viewport position. Use callback refs to keep the elements current. It adjusts + window scrolling only. If the anchor element can be replaced, pass an anchorKey that identifies + the same comment across renders.

Hook is {enabled ? 'on' : 'off'}
-
+
{olderComments.map(comment => (
{comment} @@ -48,7 +49,7 @@ export const ScrollAnchor = () => { {comment}
))} -
+
You're reading this comment

Keep this comment at the same viewport position while content is added above it.

From d7216b2ba961850bb2721ab0ca145f8bc911dd4b Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Thu, 19 Nov 2026 14:57:45 -0600 Subject: [PATCH 4/5] fix: satisfy React Compiler in useScrollAnchor Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/react/src/hooks/useScrollAnchor.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/react/src/hooks/useScrollAnchor.ts b/packages/react/src/hooks/useScrollAnchor.ts index d3298ee7016..36485b3f9d7 100644 --- a/packages/react/src/hooks/useScrollAnchor.ts +++ b/packages/react/src/hooks/useScrollAnchor.ts @@ -19,6 +19,7 @@ export interface UseScrollAnchorSettings { export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorSettings): void { const selection = useRef({anchor, anchorKey}) const updateSelection = useRef<(() => void) | null>(null) + const anchorTop = useRef(null) useIsomorphicLayoutEffect(() => { selection.current = {anchor, anchorKey} @@ -32,7 +33,6 @@ export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorS const root = container let trackedAnchor: HTMLElement | null = null let trackedKey: HTMLElement | string | number | null = null - let anchorTop: number | null = null const observed = new Set() const resizeObserver = new ResizeObserver(() => correctPosition()) @@ -66,7 +66,7 @@ export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorS const hadAnchor = trackedAnchor !== null trackedAnchor = null trackedKey = null - anchorTop = null + anchorTop.current = null if (hadAnchor) observeLayout() return false } @@ -76,7 +76,7 @@ export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorS const key = nextKey ?? nextAnchor if (key !== trackedKey) { - anchorTop = nextAnchor.getBoundingClientRect().top + anchorTop.current = nextAnchor.getBoundingClientRect().top } if (nextAnchor !== trackedAnchor || key !== trackedKey) { trackedAnchor = nextAnchor @@ -87,18 +87,18 @@ export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorS } function correctPosition() { - if (!synchronizeSelection() || !trackedAnchor || anchorTop === null) return + if (!synchronizeSelection() || !trackedAnchor || anchorTop.current === null) return - const offset = trackedAnchor.getBoundingClientRect().top - anchorTop + const offset = trackedAnchor.getBoundingClientRect().top - anchorTop.current if (offset !== 0) { window.scrollBy({top: offset, behavior: 'instant'}) - anchorTop = trackedAnchor.getBoundingClientRect().top + anchorTop.current = trackedAnchor.getBoundingClientRect().top } } function capturePosition() { if (synchronizeSelection() && trackedAnchor) { - anchorTop = trackedAnchor.getBoundingClientRect().top + anchorTop.current = trackedAnchor.getBoundingClientRect().top } } From 0d5889bd0104d630908a7d1f681dddec04e64203 Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Thu, 19 Nov 2026 15:03:55 -0600 Subject: [PATCH 5/5] fix: keep scroll anchor state in refs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/react/src/hooks/useScrollAnchor.ts | 33 +++++++++++---------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/react/src/hooks/useScrollAnchor.ts b/packages/react/src/hooks/useScrollAnchor.ts index 36485b3f9d7..278416bd3ea 100644 --- a/packages/react/src/hooks/useScrollAnchor.ts +++ b/packages/react/src/hooks/useScrollAnchor.ts @@ -19,6 +19,8 @@ export interface UseScrollAnchorSettings { export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorSettings): void { const selection = useRef({anchor, anchorKey}) const updateSelection = useRef<(() => void) | null>(null) + const trackedAnchor = useRef(null) + const trackedKey = useRef(null) const anchorTop = useRef(null) useIsomorphicLayoutEffect(() => { @@ -31,14 +33,15 @@ export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorS } const root = container - let trackedAnchor: HTMLElement | null = null - let trackedKey: HTMLElement | string | number | null = null + trackedAnchor.current = null + trackedKey.current = null + anchorTop.current = null const observed = new Set() const resizeObserver = new ResizeObserver(() => correctPosition()) function observeLayout() { const elements = new Set([root]) - let element: Element | null = trackedAnchor + let element: Element | null = trackedAnchor.current while (element && element !== root) { const parent: Element | null = element.parentElement if (!parent || !root.contains(parent)) break @@ -63,9 +66,9 @@ export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorS function synchronizeSelection() { const {anchor: nextAnchor, anchorKey: nextKey} = selection.current if (!nextAnchor) { - const hadAnchor = trackedAnchor !== null - trackedAnchor = null - trackedKey = null + const hadAnchor = trackedAnchor.current !== null + trackedAnchor.current = null + trackedKey.current = null anchorTop.current = null if (hadAnchor) observeLayout() return false @@ -75,30 +78,30 @@ export function useScrollAnchor({container, anchor, anchorKey}: UseScrollAnchorS } const key = nextKey ?? nextAnchor - if (key !== trackedKey) { + if (key !== trackedKey.current) { anchorTop.current = nextAnchor.getBoundingClientRect().top } - if (nextAnchor !== trackedAnchor || key !== trackedKey) { - trackedAnchor = nextAnchor - trackedKey = key + if (nextAnchor !== trackedAnchor.current || key !== trackedKey.current) { + trackedAnchor.current = nextAnchor + trackedKey.current = key observeLayout() } return true } function correctPosition() { - if (!synchronizeSelection() || !trackedAnchor || anchorTop.current === null) return + if (!synchronizeSelection() || !trackedAnchor.current || anchorTop.current === null) return - const offset = trackedAnchor.getBoundingClientRect().top - anchorTop.current + const offset = trackedAnchor.current.getBoundingClientRect().top - anchorTop.current if (offset !== 0) { window.scrollBy({top: offset, behavior: 'instant'}) - anchorTop.current = trackedAnchor.getBoundingClientRect().top + anchorTop.current = trackedAnchor.current.getBoundingClientRect().top } } function capturePosition() { - if (synchronizeSelection() && trackedAnchor) { - anchorTop.current = trackedAnchor.getBoundingClientRect().top + if (synchronizeSelection() && trackedAnchor.current) { + anchorTop.current = trackedAnchor.current.getBoundingClientRect().top } }