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/__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 new file mode 100644 index 00000000000..d7cb36d418b --- /dev/null +++ b/packages/react/src/hooks/__tests__/useScrollAnchor.test.tsx @@ -0,0 +1,329 @@ +import {act, render, waitFor} from '@testing-library/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', + 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({container, anchor, anchorKey}) + + 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(() => { + anchor.top = 300 + }) + + const {container} = render( anchor.top} />) + + await act(async () => { + container.firstElementChild?.prepend(document.createElement('div')) + anchor.top += 48 + }) + + await waitFor(() => { + 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(() => { + anchor.top = 240 + }) + 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({top: 20, behavior: 'instant'}) + }) + 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')) + }) + expect(scrollBy).not.toHaveBeenCalled() + scrollBy.mockRestore() +}) + +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 + }) + 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() +}) + +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(() => { + 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 + }) + + 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() + + await waitFor(() => { + 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/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..31ea0e84449 --- /dev/null +++ b/packages/react/src/hooks/useScrollAnchor.hookDocs.json @@ -0,0 +1,28 @@ +{ + "name": "useScrollAnchor", + "importPath": "@primer/react", + "stories": [{"id": "hooks-usescrollanchor--scroll-anchor"}], + "parameters": [ + { + "name": "container", + "type": "HTMLElement | null", + "required": true, + "description": "The container to observe. Use a callback ref backed by state to track when it mounts or changes." + }, + { + "name": "anchor", + "type": "HTMLElement | null", + "required": true, + "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": { + "type": "void" + } +} diff --git a/packages/react/src/hooks/useScrollAnchor.ts b/packages/react/src/hooks/useScrollAnchor.ts new file mode 100644 index 00000000000..278416bd3ea --- /dev/null +++ b/packages/react/src/hooks/useScrollAnchor.ts @@ -0,0 +1,135 @@ +import {useRef} from 'react' +import useIsomorphicLayoutEffect from '../utils/useIsomorphicLayoutEffect' + +export interface UseScrollAnchorSettings { + container: HTMLElement | null + anchor: HTMLElement | null + anchorKey?: string | number +} + +/** + * Preserves an anchor's viewport position when content in its container changes. + * The anchor should be visible. Only window scrolling is adjusted. + * + * 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({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(() => { + selection.current = {anchor, anchorKey} + }) + + useIsomorphicLayoutEffect(() => { + if (!container) { + return + } + + const root = container + 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.current + 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) + } + } + } + + function synchronizeSelection() { + const {anchor: nextAnchor, anchorKey: nextKey} = selection.current + if (!nextAnchor) { + const hadAnchor = trackedAnchor.current !== null + trackedAnchor.current = null + trackedKey.current = null + anchorTop.current = null + if (hadAnchor) observeLayout() + return false + } + if (!root.contains(nextAnchor)) { + return false + } + + const key = nextKey ?? nextAnchor + if (key !== trackedKey.current) { + anchorTop.current = nextAnchor.getBoundingClientRect().top + } + if (nextAnchor !== trackedAnchor.current || key !== trackedKey.current) { + trackedAnchor.current = nextAnchor + trackedKey.current = key + observeLayout() + } + return true + } + + function correctPosition() { + if (!synchronizeSelection() || !trackedAnchor.current || anchorTop.current === null) return + + const offset = trackedAnchor.current.getBoundingClientRect().top - anchorTop.current + if (offset !== 0) { + window.scrollBy({top: offset, behavior: 'instant'}) + anchorTop.current = trackedAnchor.current.getBoundingClientRect().top + } + } + + function capturePosition() { + if (synchronizeSelection() && trackedAnchor.current) { + anchorTop.current = trackedAnchor.current.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', capturePosition) + + return () => { + updateSelection.current = null + mutationObserver.disconnect() + resizeObserver.disconnect() + window.removeEventListener('scroll', capturePosition) + } + }, [container]) + + useIsomorphicLayoutEffect(() => { + updateSelection.current?.() + }, [container, anchor, anchorKey]) +} 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..3e89ea7c5e8 --- /dev/null +++ b/packages/react/src/stories/useScrollAnchor.stories.tsx @@ -0,0 +1,65 @@ +import React, {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 [container, setContainer] = useState(null) + const [anchor, setAnchor] = useState(null) + + useScrollAnchor({container, anchor: enabled ? anchor : null}) + + 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({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} +
+ ))} + {['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} +
+ ))} +
+
+ + ) +}