@samitouri / QOS-React / commits / 3434ff4f4b

Add scrollIntoView to fragment instances (#32814)

This adds `experimental_scrollIntoView(alignToTop)`. It doesn't yet support `scrollIntoView(options)`. Cases: - No host children: Without host children, we represent the virtual space of the Fragment by attempting to scroll to the nearest edge by using its siblings. If the preferred sibling is not found, we'll try the other side, and then the parent. - 1 or more host children: In order to handle the case of children spread between multiple scroll containers, we scroll to each child in reverse order based on the `alignToTop` flag. Due to the complexity of multiple scroll containers and dealing with portals, I've added this under a separate feature flag with an experimental prefix. We may stabilize it along with the other APIs, but this allows us to not block the whole feature on it. This PR was previously implementing a much more complex approach to handling multiple scroll containers and portals. We're going to start with the simple loop and see if we can find any concrete use cases where that doesn't suffice. 01f31d43013ba7f6f54fd8a36990bbafc3c3cc68 is the diff between approaches here.

Jack Pope committed Aug 27, 2025 at 18:05 UTC 3434ff4f4b89ad9388c6109312ef95c14652ae21
21 files changed +755 -47
fixtures/dom/src/components/fixtures/fragment-refs/FocusCase.js
+1 -1
@@ -3,7 +3,7 @@ import Fixture from '../../Fixture';
3
4 const React = window.React;
5
6 -const {Fragment, useEffect, useRef, useState} = React;
6 +const {Fragment, useRef} = React;
7
8 export default function FocusCase() {
9 const fragmentRef = useRef(null);
fixtures/dom/src/components/fixtures/fragment-refs/GetClientRectsCase.js
+1 -1
@@ -2,7 +2,7 @@ import TestCase from '../../TestCase';
2 import Fixture from '../../Fixture';
3
4 const React = window.React;
5 -const {Fragment, useEffect, useRef, useState} = React;
5 +const {Fragment, useRef, useState} = React;
6
7 export default function GetClientRectsCase() {
8 const fragmentRef = useRef(null);
fixtures/dom/src/components/fixtures/fragment-refs/ScrollIntoViewCase.js new
+184
@@ -0,0 +1,184 @@
1 +import TestCase from '../../TestCase';
2 +import Fixture from '../../Fixture';
3 +import ScrollIntoViewCaseComplex from './ScrollIntoViewCaseComplex';
4 +import ScrollIntoViewCaseSimple from './ScrollIntoViewCaseSimple';
5 +import ScrollIntoViewTargetElement from './ScrollIntoViewTargetElement';
6 +
7 +const React = window.React;
8 +const {Fragment, useRef, useState, useEffect} = React;
9 +const ReactDOM = window.ReactDOM;
10 +
11 +function Controls({
12 + alignToTop,
13 + setAlignToTop,
14 + scrollVertical,
15 + exampleType,
16 + setExampleType,
17 +}) {
18 + return (
19 + <div>
20 + <label>
21 + Example Type:
22 + <select
23 + value={exampleType}
24 + onChange={e => setExampleType(e.target.value)}>
25 + <option value="simple">Simple</option>
26 + <option value="multiple">Multiple Scroll Containers</option>
27 + <option value="horizontal">Horizontal</option>
28 + <option value="empty">Empty Fragment</option>
29 + </select>
30 + </label>
31 + <div>
32 + <label>
33 + Align to Top:
34 + <input
35 + type="checkbox"
36 + checked={alignToTop}
37 + onChange={e => setAlignToTop(e.target.checked)}
38 + />
39 + </label>
40 + </div>
41 + <div>
42 + <button onClick={scrollVertical}>scrollIntoView()</button>
43 + </div>
44 + </div>
45 + );
46 +}
47 +
48 +export default function ScrollIntoViewCase() {
49 + const [exampleType, setExampleType] = useState('simple');
50 + const [alignToTop, setAlignToTop] = useState(true);
51 + const [caseInViewport, setCaseInViewport] = useState(false);
52 + const fragmentRef = useRef(null);
53 + const testCaseRef = useRef(null);
54 + const noChildRef = useRef(null);
55 + const scrollContainerRef = useRef(null);
56 +
57 + const scrollVertical = () => {
58 + fragmentRef.current.experimental_scrollIntoView(alignToTop);
59 + };
60 +
61 + const scrollVerticalNoChildren = () => {
62 + noChildRef.current.experimental_scrollIntoView(alignToTop);
63 + };
64 +
65 + useEffect(() => {
66 + const observer = new IntersectionObserver(entries => {
67 + entries.forEach(entry => {
68 + if (entry.isIntersecting) {
69 + setCaseInViewport(true);
70 + } else {
71 + setCaseInViewport(false);
72 + }
73 + });
74 + });
75 + testCaseRef.current.observeUsing(observer);
76 +
77 + const lastRef = testCaseRef.current;
78 + return () => {
79 + lastRef.unobserveUsing(observer);
80 + observer.disconnect();
81 + };
82 + });
83 +
84 + return (
85 + <Fragment ref={testCaseRef}>
86 + <TestCase title="ScrollIntoView">
87 + <TestCase.Steps>
88 + <li>Toggle alignToTop and click the buttons to scroll</li>
89 + </TestCase.Steps>
90 + <TestCase.ExpectedResult>
91 + <p>When the Fragment has children:</p>
92 + <p>
93 + In order to handle the case where children are split between
94 + multiple scroll containers, we call scrollIntoView on each child in
95 + reverse order.
96 + </p>
97 + <p>When the Fragment does not have children:</p>
98 + <p>
99 + The Fragment still represents a virtual space. We can scroll to the
100 + nearest edge by selecting the host sibling before if
101 + alignToTop=false, or after if alignToTop=true|undefined. We'll fall
102 + back to the other sibling or parent in the case that the preferred
103 + sibling target doesn't exist.
104 + </p>
105 + </TestCase.ExpectedResult>
106 + <Fixture>
107 + <Fixture.Controls>
108 + <Controls
109 + alignToTop={alignToTop}
110 + setAlignToTop={setAlignToTop}
111 + scrollVertical={scrollVertical}
112 + exampleType={exampleType}
113 + setExampleType={setExampleType}
114 + />
115 + </Fixture.Controls>
116 + {exampleType === 'simple' && (
117 + <Fragment ref={fragmentRef}>
118 + <ScrollIntoViewCaseSimple />
119 + </Fragment>
120 + )}
121 + {exampleType === 'horizontal' && (
122 + <div
123 + style={{
124 + display: 'flex',
125 + overflowX: 'auto',
126 + flexDirection: 'row',
127 + border: '1px solid #ccc',
128 + padding: '1rem 10rem',
129 + marginBottom: '1rem',
130 + width: '100%',
131 + whiteSpace: 'nowrap',
132 + justifyContent: 'space-between',
133 + }}>
134 + <Fragment ref={fragmentRef}>
135 + <ScrollIntoViewCaseSimple />
136 + </Fragment>
137 + </div>
138 + )}
139 + {exampleType === 'multiple' && (
140 + <Fragment>
141 + <div
142 + style={{
143 + height: '50vh',
144 + overflowY: 'auto',
145 + border: '1px solid black',
146 + marginBottom: '1rem',
147 + }}
148 + ref={scrollContainerRef}
149 + />
150 + <Fragment ref={fragmentRef}>
151 + <ScrollIntoViewCaseComplex
152 + caseInViewport={caseInViewport}
153 + scrollContainerRef={scrollContainerRef}
154 + />
155 + </Fragment>
156 + </Fragment>
157 + )}
158 + {exampleType === 'empty' && (
159 + <Fragment>
160 + <ScrollIntoViewTargetElement
161 + color="lightyellow"
162 + id="ABOVE EMPTY FRAGMENT"
163 + />
164 + <Fragment ref={fragmentRef}></Fragment>
165 + <ScrollIntoViewTargetElement
166 + color="lightblue"
167 + id="BELOW EMPTY FRAGMENT"
168 + />
169 + </Fragment>
170 + )}
171 + <Fixture.Controls>
172 + <Controls
173 + alignToTop={alignToTop}
174 + setAlignToTop={setAlignToTop}
175 + scrollVertical={scrollVertical}
176 + exampleType={exampleType}
177 + setExampleType={setExampleType}
178 + />
179 + </Fixture.Controls>
180 + </Fixture>
181 + </TestCase>
182 + </Fragment>
183 + );
184 +}
fixtures/dom/src/components/fixtures/fragment-refs/ScrollIntoViewCaseComplex.js new
+50
@@ -0,0 +1,50 @@
1 +import ScrollIntoViewTargetElement from './ScrollIntoViewTargetElement';
2 +
3 +const React = window.React;
4 +const {Fragment, useRef, useState, useEffect} = React;
5 +const ReactDOM = window.ReactDOM;
6 +
7 +export default function ScrollIntoViewCaseComplex({
8 + caseInViewport,
9 + scrollContainerRef,
10 +}) {
11 + const [didMount, setDidMount] = useState(false);
12 + // Hack to portal child into the scroll container
13 + // after the first render. This is to simulate a case where
14 + // an item is portaled into another scroll container.
15 + useEffect(() => {
16 + if (!didMount) {
17 + setDidMount(true);
18 + }
19 + }, []);
20 + return (
21 + <Fragment>
22 + {caseInViewport && (
23 + <div
24 + style={{position: 'fixed', top: 0, backgroundColor: 'red'}}
25 + id="header">
26 + Fixed header
27 + </div>
28 + )}
29 + {didMount &&
30 + ReactDOM.createPortal(
31 + <ScrollIntoViewTargetElement color="red" id="FROM_PORTAL" />,
32 + scrollContainerRef.current
33 + )}
34 + <ScrollIntoViewTargetElement color="lightgreen" id="A" />
35 + <ScrollIntoViewTargetElement color="lightcoral" id="B" />
36 + <ScrollIntoViewTargetElement color="lightblue" id="C" />
37 + {caseInViewport && (
38 + <div
39 + style={{
40 + position: 'fixed',
41 + bottom: 0,
42 + backgroundColor: 'purple',
43 + }}
44 + id="footer">
45 + Fixed footer
46 + </div>
47 + )}
48 + </Fragment>
49 + );
50 +}
fixtures/dom/src/components/fixtures/fragment-refs/ScrollIntoViewCaseSimple.js new
+14
@@ -0,0 +1,14 @@
1 +import ScrollIntoViewTargetElement from './ScrollIntoViewTargetElement';
2 +
3 +const React = window.React;
4 +const {Fragment} = React;
5 +
6 +export default function ScrollIntoViewCaseSimple() {
7 + return (
8 + <Fragment>
9 + <ScrollIntoViewTargetElement color="lightyellow" id="SCROLLABLE-1" />
10 + <ScrollIntoViewTargetElement color="lightpink" id="SCROLLABLE-2" />
11 + <ScrollIntoViewTargetElement color="lightcyan" id="SCROLLABLE-3" />
12 + </Fragment>
13 + );
14 +}
fixtures/dom/src/components/fixtures/fragment-refs/ScrollIntoViewTargetElement.js new
+18
@@ -0,0 +1,18 @@
1 +const React = window.React;
2 +
3 +export default function ScrollIntoViewTargetElement({color, id, top}) {
4 + return (
5 + <div
6 + id={id}
7 + style={{
8 + height: 500,
9 + minWidth: 300,
10 + backgroundColor: color,
11 + marginTop: top ? '50vh' : 0,
12 + marginBottom: 100,
13 + flexShrink: 0,
14 + }}>
15 + {id}
16 + </div>
17 + );
18 +}
fixtures/dom/src/components/fixtures/fragment-refs/index.js
+2
@@ -5,6 +5,7 @@ import IntersectionObserverCase from './IntersectionObserverCase';
5 import ResizeObserverCase from './ResizeObserverCase';
6 import FocusCase from './FocusCase';
7 import GetClientRectsCase from './GetClientRectsCase';
8 +import ScrollIntoViewCase from './ScrollIntoViewCase';
9
10 const React = window.React;
11
@@ -17,6 +18,7 @@ export default function FragmentRefsPage() {
18 <ResizeObserverCase />
19 <FocusCase />
20 <GetClientRectsCase />
21 + <ScrollIntoViewCase />
22 </FixtureSet>
23 );
24 }
fixtures/dom/src/index.js
+12 -3
@@ -2,14 +2,23 @@ import './polyfills';
2 import loadReact, {isLocal} from './react-loader';
3
4 if (isLocal()) {
5 - Promise.all([import('react'), import('react-dom/client')])
6 - .then(([React, ReactDOMClient]) => {
7 - if (React === undefined || ReactDOMClient === undefined) {
5 + Promise.all([
6 + import('react'),
7 + import('react-dom'),
8 + import('react-dom/client'),
9 + ])
10 + .then(([React, ReactDOM, ReactDOMClient]) => {
11 + if (
12 + React === undefined ||
13 + ReactDOM === undefined ||
14 + ReactDOMClient === undefined
15 + ) {
16 throw new Error(
17 'Unable to load React. Build experimental and then run `yarn dev` again'
18 );
19 }
20 window.React = React;
21 + window.ReactDOM = ReactDOM;
22 window.ReactDOMClient = ReactDOMClient;
23 })
24 .then(() => import('./components/App'))
packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js
+93 -41
@@ -37,17 +37,6 @@ import {runWithFiberInDEV} from 'react-reconciler/src/ReactCurrentFiber';
37 import hasOwnProperty from 'shared/hasOwnProperty';
38 import {checkAttributeStringCoercion} from 'shared/CheckStringCoercion';
39 import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
40 -import {
41 - isFiberContainedByFragment,
42 - isFiberFollowing,
43 - isFiberPreceding,
44 - isFragmentContainedByFiber,
45 - traverseFragmentInstance,
46 - getFragmentParentHostFiber,
47 - getInstanceFromHostFiber,
48 - traverseFragmentInstanceDeeply,
49 - fiberIsPortaledIntoHost,
50 -} from 'react-reconciler/src/ReactFiberTreeReflection';
40
41 export {
42 setCurrentUpdatePriority,
@@ -69,6 +58,18 @@ import {
58 markNodeAsHoistable,
59 isOwnedInstance,
60 } from './ReactDOMComponentTree';
61 +import {
62 + traverseFragmentInstance,
63 + getFragmentParentHostFiber,
64 + getInstanceFromHostFiber,
65 + isFiberFollowing,
66 + isFiberPreceding,
67 + getFragmentInstanceSiblings,
68 + traverseFragmentInstanceDeeply,
69 + fiberIsPortaledIntoHost,
70 + isFiberContainedByFragment,
71 + isFragmentContainedByFiber,
72 +} from 'react-reconciler/src/ReactFiberTreeReflection';
73 import {compareDocumentPositionForEmptyFragment} from 'shared/ReactDOMFragmentRefShared';
74
75 export {detachDeletedInstance};
@@ -123,6 +124,7 @@ import {
124 enableSrcObject,
125 enableViewTransition,
126 enableHydrationChangeEvent,
127 + enableFragmentRefsScrollIntoView,
128 } from 'shared/ReactFeatureFlags';
129 import {
130 HostComponent,
@@ -2813,6 +2815,7 @@ export type FragmentInstanceType = {
2815 composed: boolean,
2816 }): Document | ShadowRoot | FragmentInstanceType,
2817 compareDocumentPosition(otherNode: Instance): number,
2818 + scrollIntoView(alignToTop?: boolean): void,
2819 };
2820
2821 function FragmentInstance(this: FragmentInstanceType, fragmentFiber: Fiber) {
@@ -2899,6 +2902,38 @@ function removeEventListenerFromChild(
2902 instance.removeEventListener(type, listener, optionsOrUseCapture);
2903 return false;
2904 }
2905 +function normalizeListenerOptions(
2906 + opts: ?EventListenerOptionsOrUseCapture,
2907 +): string {
2908 + if (opts == null) {
2909 + return '0';
2910 + }
2911 +
2912 + if (typeof opts === 'boolean') {
2913 + return `c=${opts ? '1' : '0'}`;
2914 + }
2915 +
2916 + return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
2917 +}
2918 +function indexOfEventListener(
2919 + eventListeners: Array<StoredEventListener>,
2920 + type: string,
2921 + listener: EventListener,
2922 + optionsOrUseCapture: void | EventListenerOptionsOrUseCapture,
2923 +): number {
2924 + for (let i = 0; i < eventListeners.length; i++) {
2925 + const item = eventListeners[i];
2926 + if (
2927 + item.type === type &&
2928 + item.listener === listener &&
2929 + normalizeListenerOptions(item.optionsOrUseCapture) ===
2930 + normalizeListenerOptions(optionsOrUseCapture)
2931 + ) {
2932 + return i;
2933 + }
2934 + }
2935 + return -1;
2936 +}
2937 // $FlowFixMe[prop-missing]
2938 FragmentInstance.prototype.dispatchEvent = function (
2939 this: FragmentInstanceType,
@@ -3214,38 +3249,55 @@ function validateDocumentPositionWithFiberTree(
3249 return false;
3250 }
3251
3217 -function normalizeListenerOptions(
3218 - opts: ?EventListenerOptionsOrUseCapture,
3219 -): string {
3220 - if (opts == null) {
3221 - return '0';
3222 - }
3223 -
3224 - if (typeof opts === 'boolean') {
3225 - return `c=${opts ? '1' : '0'}`;
3226 - }
3227 -
3228 - return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3229 -}
3252 +if (enableFragmentRefsScrollIntoView) {
3253 + // $FlowFixMe[prop-missing]
3254 + FragmentInstance.prototype.experimental_scrollIntoView = function (
3255 + this: FragmentInstanceType,
3256 + alignToTop?: boolean,
3257 + ): void {
3258 + if (typeof alignToTop === 'object') {
3259 + throw new Error(
3260 + 'FragmentInstance.experimental_scrollIntoView() does not support ' +
3261 + 'scrollIntoViewOptions. Use the alignToTop boolean instead.',
3262 + );
3263 + }
3264 + // First, get the children nodes
3265 + const children: Array<Fiber> = [];
3266 + traverseFragmentInstance(this._fragmentFiber, collectChildren, children);
3267 +
3268 + const resolvedAlignToTop = alignToTop !== false;
3269 +
3270 + // If there are no children, we can use the parent and siblings to determine a position
3271 + if (children.length === 0) {
3272 + const hostSiblings = getFragmentInstanceSiblings(this._fragmentFiber);
3273 + const targetFiber = resolvedAlignToTop
3274 + ? hostSiblings[1] ||
3275 + hostSiblings[0] ||
3276 + getFragmentParentHostFiber(this._fragmentFiber)
3277 + : hostSiblings[0] || hostSiblings[1];
3278 +
3279 + if (targetFiber === null) {
3280 + if (__DEV__) {
3281 + console.warn(
3282 + 'You are attempting to scroll a FragmentInstance that has no ' +
3283 + 'children, siblings, or parent. No scroll was performed.',
3284 + );
3285 + }
3286 + return;
3287 + }
3288 + const target = getInstanceFromHostFiber<Instance>(targetFiber);
3289 + target.scrollIntoView(alignToTop);
3290 + return;
3291 + }
3292
3231 -function indexOfEventListener(
3232 - eventListeners: Array<StoredEventListener>,
3233 - type: string,
3234 - listener: EventListener,
3235 - optionsOrUseCapture: void | EventListenerOptionsOrUseCapture,
3236 -): number {
3237 - for (let i = 0; i < eventListeners.length; i++) {
3238 - const item = eventListeners[i];
3239 - if (
3240 - item.type === type &&
3241 - item.listener === listener &&
3242 - normalizeListenerOptions(item.optionsOrUseCapture) ===
3243 - normalizeListenerOptions(optionsOrUseCapture)
3244 - ) {
3245 - return i;
3293 + let i = resolvedAlignToTop ? children.length - 1 : 0;
3294 + while (i !== (resolvedAlignToTop ? -1 : children.length)) {
3295 + const child = children[i];
3296 + const instance = getInstanceFromHostFiber<Instance>(child);
3297 + instance.scrollIntoView(alignToTop);
3298 + i += resolvedAlignToTop ? -1 : 1;
3299 }
3247 - }
3248 - return -1;
3300 + };
3301 }
3302
3303 export function createFragmentInstance(
packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js
+319
@@ -1836,4 +1836,323 @@ describe('FragmentRefs', () => {
1836 });
1837 });
1838 });
1839 +
1840 + describe('scrollIntoView', () => {
1841 + function expectLast(arr, test) {
1842 + expect(arr[arr.length - 1]).toBe(test);
1843 + }
1844 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
1845 + it('does not yet support options', async () => {
1846 + const fragmentRef = React.createRef();
1847 + const root = ReactDOMClient.createRoot(container);
1848 + await act(() => {
1849 + root.render(<Fragment ref={fragmentRef} />);
1850 + });
1851 +
1852 + expect(() => {
1853 + fragmentRef.current.experimental_scrollIntoView({block: 'start'});
1854 + }).toThrowError(
1855 + 'FragmentInstance.experimental_scrollIntoView() does not support ' +
1856 + 'scrollIntoViewOptions. Use the alignToTop boolean instead.',
1857 + );
1858 + });
1859 +
1860 + describe('with children', () => {
1861 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
1862 + it('settles scroll on the first child by default, or if alignToTop=true', async () => {
1863 + const fragmentRef = React.createRef();
1864 + const childARef = React.createRef();
1865 + const childBRef = React.createRef();
1866 + const root = ReactDOMClient.createRoot(container);
1867 + await act(() => {
1868 + root.render(
1869 + <React.Fragment ref={fragmentRef}>
1870 + <div ref={childARef} id="a">
1871 + A
1872 + </div>
1873 + <div ref={childBRef} id="b">
1874 + B
1875 + </div>
1876 + </React.Fragment>,
1877 + );
1878 + });
1879 +
1880 + let logs = [];
1881 + childARef.current.scrollIntoView = jest.fn().mockImplementation(() => {
1882 + logs.push('childA');
1883 + });
1884 + childBRef.current.scrollIntoView = jest.fn().mockImplementation(() => {
1885 + logs.push('childB');
1886 + });
1887 +
1888 + // Default call
1889 + fragmentRef.current.experimental_scrollIntoView();
1890 + expectLast(logs, 'childA');
1891 + logs = [];
1892 + // alignToTop=true
1893 + fragmentRef.current.experimental_scrollIntoView(true);
1894 + expectLast(logs, 'childA');
1895 + });
1896 +
1897 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
1898 + it('calls scrollIntoView on the last child if alignToTop is false', async () => {
1899 + const fragmentRef = React.createRef();
1900 + const childARef = React.createRef();
1901 + const childBRef = React.createRef();
1902 + const root = ReactDOMClient.createRoot(container);
1903 + await act(() => {
1904 + root.render(
1905 + <Fragment ref={fragmentRef}>
1906 + <div ref={childARef}>A</div>
1907 + <div ref={childBRef}>B</div>
1908 + </Fragment>,
1909 + );
1910 + });
1911 +
1912 + const logs = [];
1913 + childARef.current.scrollIntoView = jest.fn().mockImplementation(() => {
1914 + logs.push('childA');
1915 + });
1916 + childBRef.current.scrollIntoView = jest.fn().mockImplementation(() => {
1917 + logs.push('childB');
1918 + });
1919 +
1920 + fragmentRef.current.experimental_scrollIntoView(false);
1921 + expectLast(logs, 'childB');
1922 + });
1923 +
1924 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
1925 + it('handles portaled elements -- same scroll container', async () => {
1926 + const fragmentRef = React.createRef();
1927 + const childARef = React.createRef();
1928 + const childBRef = React.createRef();
1929 + const root = ReactDOMClient.createRoot(container);
1930 +
1931 + function Test() {
1932 + return (
1933 + <Fragment ref={fragmentRef}>
1934 + {createPortal(
1935 + <div ref={childARef} id="child-a">
1936 + A
1937 + </div>,
1938 + document.body,
1939 + )}
1940 +
1941 + <div ref={childBRef} id="child-b">
1942 + B
1943 + </div>
1944 + </Fragment>
1945 + );
1946 + }
1947 +
1948 + await act(() => {
1949 + root.render(<Test />);
1950 + });
1951 +
1952 + const logs = [];
1953 + childARef.current.scrollIntoView = jest.fn().mockImplementation(() => {
1954 + logs.push('childA');
1955 + });
1956 + childBRef.current.scrollIntoView = jest.fn().mockImplementation(() => {
1957 + logs.push('childB');
1958 + });
1959 +
1960 + // Default call
1961 + fragmentRef.current.experimental_scrollIntoView();
1962 + expectLast(logs, 'childA');
1963 + });
1964 +
1965 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
1966 + it('handles portaled elements -- different scroll container', async () => {
1967 + const fragmentRef = React.createRef();
1968 + const headerChildRef = React.createRef();
1969 + const childARef = React.createRef();
1970 + const childBRef = React.createRef();
1971 + const childCRef = React.createRef();
1972 + const scrollContainerRef = React.createRef();
1973 + const scrollContainerNestedRef = React.createRef();
1974 + const root = ReactDOMClient.createRoot(container);
1975 +
1976 + function Test({mountFragment}) {
1977 + return (
1978 + <>
1979 + <div id="header" style={{position: 'fixed'}}>
1980 + <div id="parent-a" />
1981 + </div>
1982 + <div id="parent-b" />
1983 + <div
1984 + id="scroll-container"
1985 + ref={scrollContainerRef}
1986 + style={{overflow: 'scroll'}}>
1987 + <div id="parent-c" />
1988 + <div
1989 + id="scroll-container-nested"
1990 + ref={scrollContainerNestedRef}
1991 + style={{overflow: 'scroll'}}>
1992 + <div id="parent-d" />
1993 + </div>
1994 + </div>
1995 + {mountFragment && (
1996 + <Fragment ref={fragmentRef}>
1997 + {createPortal(
1998 + <div ref={headerChildRef} id="header-content">
1999 + Header
2000 + </div>,
2001 + document.querySelector('#parent-a'),
2002 + )}
2003 + {createPortal(
2004 + <div ref={childARef} id="child-a">
2005 + A
2006 + </div>,
2007 + document.querySelector('#parent-b'),
2008 + )}
2009 + {createPortal(
2010 + <div ref={childBRef} id="child-b">
2011 + B
2012 + </div>,
2013 + document.querySelector('#parent-b'),
2014 + )}
2015 + {createPortal(
2016 + <div ref={childCRef} id="child-c">
2017 + C
2018 + </div>,
2019 + document.querySelector('#parent-c'),
2020 + )}
2021 + </Fragment>
2022 + )}
2023 + </>
2024 + );
2025 + }
2026 +
2027 + await act(() => {
2028 + root.render(<Test mountFragment={false} />);
2029 + });
2030 + // Now that the portal locations exist, mount the fragment
2031 + await act(() => {
2032 + root.render(<Test mountFragment={true} />);
2033 + });
2034 +
2035 + let logs = [];
2036 + headerChildRef.current.scrollIntoView = jest.fn(() => {
2037 + logs.push('header');
2038 + });
2039 + childARef.current.scrollIntoView = jest.fn(() => {
2040 + logs.push('A');
2041 + });
2042 + childBRef.current.scrollIntoView = jest.fn(() => {
2043 + logs.push('B');
2044 + });
2045 + childCRef.current.scrollIntoView = jest.fn(() => {
2046 + logs.push('C');
2047 + });
2048 +
2049 + // Default call
2050 + fragmentRef.current.experimental_scrollIntoView();
2051 + expectLast(logs, 'header');
2052 +
2053 + childARef.current.scrollIntoView.mockClear();
2054 + childBRef.current.scrollIntoView.mockClear();
2055 + childCRef.current.scrollIntoView.mockClear();
2056 +
2057 + logs = [];
2058 +
2059 + // // alignToTop=false
2060 + fragmentRef.current.experimental_scrollIntoView(false);
2061 + expectLast(logs, 'C');
2062 + });
2063 + });
2064 +
2065 + describe('without children', () => {
2066 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
2067 + it('calls scrollIntoView on the next sibling by default, or if alignToTop=true', async () => {
2068 + const fragmentRef = React.createRef();
2069 + const siblingARef = React.createRef();
2070 + const siblingBRef = React.createRef();
2071 + const root = ReactDOMClient.createRoot(container);
2072 + await act(() => {
2073 + root.render(
2074 + <div>
2075 + <Wrapper>
2076 + <div ref={siblingARef} />
2077 + </Wrapper>
2078 + <Fragment ref={fragmentRef} />
2079 + <div ref={siblingBRef} />
2080 + </div>,
2081 + );
2082 + });
2083 +
2084 + siblingARef.current.scrollIntoView = jest.fn();
2085 + siblingBRef.current.scrollIntoView = jest.fn();
2086 +
2087 + // Default call
2088 + fragmentRef.current.experimental_scrollIntoView();
2089 + expect(siblingARef.current.scrollIntoView).toHaveBeenCalledTimes(0);
2090 + expect(siblingBRef.current.scrollIntoView).toHaveBeenCalledTimes(1);
2091 +
2092 + siblingBRef.current.scrollIntoView.mockClear();
2093 +
2094 + // alignToTop=true
2095 + fragmentRef.current.experimental_scrollIntoView(true);
2096 + expect(siblingARef.current.scrollIntoView).toHaveBeenCalledTimes(0);
2097 + expect(siblingBRef.current.scrollIntoView).toHaveBeenCalledTimes(1);
2098 + });
2099 +
2100 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
2101 + it('calls scrollIntoView on the prev sibling if alignToTop is false', async () => {
2102 + const fragmentRef = React.createRef();
2103 + const siblingARef = React.createRef();
2104 + const siblingBRef = React.createRef();
2105 + const root = ReactDOMClient.createRoot(container);
2106 + function C() {
2107 + return (
2108 + <Wrapper>
2109 + <div id="C" ref={siblingARef} />
2110 + </Wrapper>
2111 + );
2112 + }
2113 + function Test() {
2114 + return (
2115 + <div id="A">
2116 + <div id="B" />
2117 + <C />
2118 + <Fragment ref={fragmentRef} />
2119 + <div id="D" ref={siblingBRef} />
2120 + <div id="E" />
2121 + </div>
2122 + );
2123 + }
2124 + await act(() => {
2125 + root.render(<Test />);
2126 + });
2127 +
2128 + siblingARef.current.scrollIntoView = jest.fn();
2129 + siblingBRef.current.scrollIntoView = jest.fn();
2130 +
2131 + // alignToTop=false
2132 + fragmentRef.current.experimental_scrollIntoView(false);
2133 + expect(siblingARef.current.scrollIntoView).toHaveBeenCalledTimes(1);
2134 + expect(siblingBRef.current.scrollIntoView).toHaveBeenCalledTimes(0);
2135 + });
2136 +
2137 + // @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
2138 + it('calls scrollIntoView on the parent if there are no siblings', async () => {
2139 + const fragmentRef = React.createRef();
2140 + const parentRef = React.createRef();
2141 + const root = ReactDOMClient.createRoot(container);
2142 + await act(() => {
2143 + root.render(
2144 + <div ref={parentRef}>
2145 + <Wrapper>
2146 + <Fragment ref={fragmentRef} />
2147 + </Wrapper>
2148 + </div>,
2149 + );
2150 + });
2151 +
2152 + parentRef.current.scrollIntoView = jest.fn();
2153 + fragmentRef.current.experimental_scrollIntoView();
2154 + expect(parentRef.current.scrollIntoView).toHaveBeenCalledTimes(1);
2155 + });
2156 + });
2157 + });
2158 });
packages/react-reconciler/src/ReactFiberTreeReflection.js
+50
@@ -421,6 +421,56 @@ export function fiberIsPortaledIntoHost(fiber: Fiber): boolean {
421 return foundPortalParent;
422 }
423
424 +export function getFragmentInstanceSiblings(
425 + fiber: Fiber,
426 +): [Fiber | null, Fiber | null] {
427 + const result: [Fiber | null, Fiber | null] = [null, null];
428 + const parentHostFiber = getFragmentParentHostFiber(fiber);
429 + if (parentHostFiber === null) {
430 + return result;
431 + }
432 +
433 + findFragmentInstanceSiblings(result, fiber, parentHostFiber.child);
434 + return result;
435 +}
436 +
437 +function findFragmentInstanceSiblings(
438 + result: [Fiber | null, Fiber | null],
439 + self: Fiber,
440 + child: null | Fiber,
441 + foundSelf: boolean = false,
442 +): boolean {
443 + while (child !== null) {
444 + if (child === self) {
445 + foundSelf = true;
446 + if (child.sibling) {
447 + child = child.sibling;
448 + } else {
449 + return true;
450 + }
451 + }
452 + if (child.tag === HostComponent) {
453 + if (foundSelf) {
454 + result[1] = child;
455 + return true;
456 + } else {
457 + result[0] = child;
458 + }
459 + } else if (
460 + child.tag === OffscreenComponent &&
461 + child.memoizedState !== null
462 + ) {
463 + // Skip hidden subtrees
464 + } else {
465 + if (findFragmentInstanceSiblings(result, self, child.child, foundSelf)) {
466 + return true;
467 + }
468 + }
469 + child = child.sibling;
470 + }
471 + return false;
472 +}
473 +
474 export function getInstanceFromHostFiber<I>(fiber: Fiber): I {
475 switch (fiber.tag) {
476 case HostComponent:
packages/shared/ReactFeatureFlags.js
+1
@@ -152,6 +152,7 @@ export const transitionLaneExpirationMs = 5000;
152 export const enableInfiniteRenderLoopDetection: boolean = false;
153
154 export const enableFragmentRefs = __EXPERIMENTAL__;
155 +export const enableFragmentRefsScrollIntoView = __EXPERIMENTAL__;
156
157 // -----------------------------------------------------------------------------
158 // Ready for next major.
packages/shared/forks/ReactFeatureFlags.native-fb-dynamic.js
+1
@@ -25,4 +25,5 @@ export const enableEagerAlternateStateNodeCleanup = __VARIANT__;
25 export const passChildrenWhenCloningPersistedNodes = __VARIANT__;
26 export const renameElementSymbol = __VARIANT__;
27 export const enableFragmentRefs = __VARIANT__;
28 +export const enableFragmentRefsScrollIntoView = __VARIANT__;
29 export const enableComponentPerformanceTrack = __VARIANT__;
packages/shared/forks/ReactFeatureFlags.native-fb.js
+1
@@ -27,6 +27,7 @@ export const {
27 passChildrenWhenCloningPersistedNodes,
28 renameElementSymbol,
29 enableFragmentRefs,
30 + enableFragmentRefsScrollIntoView,
31 } = dynamicFlags;
32
33 // The rest of the flags are static for better dead code elimination.
packages/shared/forks/ReactFeatureFlags.native-oss.js
+1
@@ -73,6 +73,7 @@ export const enableDefaultTransitionIndicator: boolean = false;
73 export const ownerStackLimit = 1e4;
74
75 export const enableFragmentRefs: boolean = false;
76 +export const enableFragmentRefsScrollIntoView: boolean = false;
77
78 // Profiling Only
79 export const enableProfilerTimer: boolean = __PROFILE__;
packages/shared/forks/ReactFeatureFlags.test-renderer.js
+1
@@ -75,6 +75,7 @@ export const enableDefaultTransitionIndicator: boolean = false;
75 export const ownerStackLimit = 1e4;
76
77 export const enableFragmentRefs: boolean = false;
78 +export const enableFragmentRefsScrollIntoView: boolean = false;
79
80 // TODO: This must be in sync with the main ReactFeatureFlags file because
81 // the Test Renderer's value must be the same as the one used by the
packages/shared/forks/ReactFeatureFlags.test-renderer.native-fb.js
+1
@@ -68,6 +68,7 @@ export const enableSrcObject = false;
68 export const enableHydrationChangeEvent = false;
69 export const enableDefaultTransitionIndicator = false;
70 export const enableFragmentRefs = false;
71 +export const enableFragmentRefsScrollIntoView = false;
72 export const ownerStackLimit = 1e4;
73
74 // Flow magic to verify the exports of this file match the original version.
packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
+1
@@ -82,6 +82,7 @@ export const enableHydrationChangeEvent: boolean = false;
82 export const enableDefaultTransitionIndicator: boolean = false;
83
84 export const enableFragmentRefs: boolean = false;
85 +export const enableFragmentRefsScrollIntoView: boolean = false;
86 export const ownerStackLimit = 1e4;
87
88 // Flow magic to verify the exports of this file match the original version.
packages/shared/forks/ReactFeatureFlags.www-dynamic.js
+1
@@ -35,6 +35,7 @@ export const enableViewTransition: boolean = __VARIANT__;
35 export const enableComponentPerformanceTrack: boolean = __VARIANT__;
36 export const enableScrollEndPolyfill: boolean = __VARIANT__;
37 export const enableFragmentRefs: boolean = __VARIANT__;
38 +export const enableFragmentRefsScrollIntoView: boolean = __VARIANT__;
39
40 // TODO: These flags are hard-coded to the default values used in open source.
41 // Update the tests so that they pass in either mode, then set these
packages/shared/forks/ReactFeatureFlags.www.js
+1
@@ -33,6 +33,7 @@ export const {
33 enableComponentPerformanceTrack,
34 enableScrollEndPolyfill,
35 enableFragmentRefs,
36 + enableFragmentRefsScrollIntoView,
37 } = dynamicFeatureFlags;
38
39 // On WWW, __EXPERIMENTAL__ is used for a new modern build.
scripts/error-codes/codes.json
+2 -1
@@ -550,5 +550,6 @@
550 "562": "The render was aborted due to a fatal error.",
551 "563": "This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources.",
552 "564": "Unknown command. The debugChannel was not wired up properly.",
553 - "565": "resolveDebugMessage/closeDebugChannel should not be called for a Request that wasn't kept alive. This is a bug in React."
553 + "565": "resolveDebugMessage/closeDebugChannel should not be called for a Request that wasn't kept alive. This is a bug in React.",
554 + "566": "FragmentInstance.experimental_scrollIntoView() does not support scrollIntoViewOptions. Use the alignToTop boolean instead."
555 }