Add text node support to FragmentInstance operations (#35630)

This PR adds text node support to FragmentInstance operations, allowing
fragment refs to properly handle fragments that contain text nodes
(either mixed with elements or text-only).

Not currently adding/removing new text nodes as we don't need to track
them for events or observers in DOM. Will follow up on this and with
Fabric support.

## Support through parent element
- `dispatchEvent`
- `compareDocumentPosition`
- `getRootNode`

## Support through Range API
- `getClientRects`: Uses Range to calculate bounding rects for text
nodes
- `scrollIntoView`: Uses Range to scroll to text node positions directly

## No support
- `focus`/`focusLast`/`blur`: Noop for text-only fragments
- `observeUsing`:  Warns for text-only fragments in DEV
- `addEventListener`/`removeEventListener`: Ignores text nodes, but
still works on Fragment level through `dispatchEvent`
This commit is contained in:
Jack Pope authored and GitHub committed 2026-01-28 14:45:17 -05:00
1 parent d4d099f05b
commit 875b06489f
17 files changed
+777 -76

No files matched your search

@@ -1,17 +1,10 @@
import TestCase from '../../TestCase';
import Fixture from '../../Fixture';
import PrintRectsFragmentContainer from './PrintRectsFragmentContainer';
const React = window.React;
const {Fragment, useRef, useState} = React;
export default function GetClientRectsCase() {
const fragmentRef = useRef(null);
const [rects, setRects] = useState([]);
const getRects = () => {
const rects = fragmentRef.current.getClientRects();
setRects(rects);
};
return (
<TestCase title="getClientRects">
<TestCase.Steps>
@@ -26,74 +19,35 @@ export default function GetClientRectsCase() {
</TestCase.ExpectedResult>
<Fixture>
<Fixture.Controls>
<button onClick={getRects}>Print Rects</button>
<div style={{display: 'flex'}}>
<PrintRectsFragmentContainer>
<span
style={{
width: '300px',
height: '250px',
backgroundColor: 'lightblue',
fontSize: 20,
border: '1px solid black',
marginBottom: '10px',
}}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</span>
<div
style={{
position: 'relative',
width: '30vw',
height: '30vh',
width: '150px',
height: '100px',
backgroundColor: 'lightgreen',
border: '1px solid black',
}}>
{rects.map(({x, y, width, height}, index) => {
const scale = 0.3;
return (
<div
key={index}
style={{
position: 'absolute',
top: y * scale,
left: x * scale,
width: width * scale,
height: height * scale,
border: '1px solid red',
boxSizing: 'border-box',
}}></div>
);
})}
</div>
<div>
{rects.map(({x, y, width, height}, index) => {
return (
<div>
{index} :: {`{`}x: {x}, y: {y}, width: {width}, height:{' '}
{height}
{`}`}
</div>
);
})}
</div>
</div>
}}></div>
<div
style={{
width: '500px',
height: '50px',
backgroundColor: 'lightpink',
border: '1px solid black',
}}></div>
</PrintRectsFragmentContainer>
</Fixture.Controls>
<Fragment ref={fragmentRef}>
<span
style={{
width: '300px',
height: '250px',
backgroundColor: 'lightblue',
fontSize: 20,
border: '1px solid black',
marginBottom: '10px',
}}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</span>
<div
style={{
width: '150px',
height: '100px',
backgroundColor: 'lightgreen',
border: '1px solid black',
}}></div>
<div
style={{
width: '500px',
height: '50px',
backgroundColor: 'lightpink',
border: '1px solid black',
}}></div>
</Fragment>
</Fixture>
</TestCase>
);
@@ -0,0 +1,126 @@
const React = window.React;
const {Fragment, useRef, useState} = React;
const colors = [
'#e74c3c',
'#3498db',
'#2ecc71',
'#9b59b6',
'#f39c12',
'#1abc9c',
];
export default function PrintRectsFragmentContainer({children}) {
const fragmentRef = useRef(null);
const [rects, setRects] = useState([]);
const getRects = () => {
const rectsResult = fragmentRef.current.getClientRects();
setRects(Array.from(rectsResult));
};
const getColor = index => colors[index % colors.length];
return (
<Fragment>
<div style={{marginBottom: '16px'}}>
<button
onClick={getRects}
style={{
padding: '8px 16px',
fontSize: '14px',
fontWeight: 'bold',
cursor: 'pointer',
}}>
Print Rects
</button>
{rects.length > 0 && (
<span style={{marginLeft: '12px', color: '#666'}}>
Found {rects.length} rect{rects.length !== 1 ? 's' : ''}
</span>
)}
</div>
<div style={{display: 'flex', gap: '20px', marginBottom: '16px'}}>
<div
style={{
position: 'relative',
width: '30vw',
height: '30vh',
border: '1px solid #ccc',
backgroundColor: '#fafafa',
borderRadius: '4px',
overflow: 'hidden',
}}>
{rects.length === 0 && (
<div
style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
color: '#999',
fontSize: '14px',
}}>
Click button to visualize rects
</div>
)}
{rects.map(({x, y, width, height}, index) => {
const scale = 0.3;
const color = getColor(index);
return (
<div
key={index}
style={{
position: 'absolute',
top: y * scale,
left: x * scale,
width: width * scale,
height: height * scale,
border: `2px solid ${color}`,
backgroundColor: `${color}22`,
boxSizing: 'border-box',
borderRadius: '2px',
}}
/>
);
})}
</div>
<div style={{flex: 1, fontSize: '13px', fontFamily: 'monospace'}}>
{rects.map(({x, y, width, height}, index) => {
const color = getColor(index);
return (
<div
key={index}
style={{
padding: '6px 10px',
marginBottom: '4px',
backgroundColor: '#f5f5f5',
borderLeft: `3px solid ${color}`,
borderRadius: '2px',
}}>
<span style={{color: '#666'}}>#{index}</span>{' '}
<span style={{color: '#333'}}>
x: {Math.round(x)}, y: {Math.round(y)}, w: {Math.round(width)}
, h: {Math.round(height)}
</span>
</div>
);
})}
</div>
</div>
<div
style={{
padding: '12px',
border: '1px dashed #ccc',
borderRadius: '4px',
backgroundColor: '#fff',
}}>
<Fragment ref={fragmentRef}>{children}</Fragment>
</div>
</Fragment>
);
}
@@ -0,0 +1,319 @@
import TestCase from '../../TestCase';
import Fixture from '../../Fixture';
import PrintRectsFragmentContainer from './PrintRectsFragmentContainer';
const React = window.React;
const {Fragment, useRef, useState} = React;
function GetClientRectsTextOnly() {
return (
<TestCase title="getClientRects - Text Only">
<TestCase.Steps>
<li>Click the "Print Rects" button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The fragment contains only text nodes. getClientRects should return
bounding rectangles for the text content using the Range API.
</TestCase.ExpectedResult>
<Fixture>
<Fixture.Controls>
<PrintRectsFragmentContainer>
This is text content inside a fragment with no element children.
</PrintRectsFragmentContainer>
</Fixture.Controls>
</Fixture>
</TestCase>
);
}
function GetClientRectsMixed() {
return (
<TestCase title="getClientRects - Mixed Content">
<TestCase.Steps>
<li>Click the "Print Rects" button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The fragment contains both text nodes and elements. getClientRects
should return bounding rectangles for both text content (via Range API)
and elements.
</TestCase.ExpectedResult>
<Fixture>
<Fixture.Controls>
<PrintRectsFragmentContainer>
Text before the span.
<span
style={{
display: 'inline-block',
padding: '5px 10px',
backgroundColor: 'lightblue',
border: '1px solid blue',
margin: '0 5px',
}}>
Element
</span>
Text after the span.
<div
style={{
width: '500px',
height: '50px',
backgroundColor: 'lightpink',
border: '1px solid black',
}}></div>
More text at the end.
</PrintRectsFragmentContainer>
</Fixture.Controls>
</Fixture>
</TestCase>
);
}
function FocusTextOnlyNoop() {
const fragmentRef = useRef(null);
const [message, setMessage] = useState('');
const tryFocus = () => {
fragmentRef.current.focus();
setMessage('Called focus() - no-op for text-only fragments');
};
const tryFocusLast = () => {
fragmentRef.current.focusLast();
setMessage('Called focusLast() - no-op for text-only fragments');
};
return (
<TestCase title="focus/focusLast - Text Only (No-op)">
<TestCase.Steps>
<li>Click either focus button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
Calling focus() or focusLast() on a fragment with only text children is
a no-op. Nothing happens and no warning is logged. This is because text
nodes cannot receive focus.
</TestCase.ExpectedResult>
<Fixture>
<Fixture.Controls>
<button onClick={tryFocus}>focus()</button>
<button onClick={tryFocusLast}>focusLast()</button>
{message && (
<div style={{marginTop: '10px', color: '#666'}}>{message}</div>
)}
</Fixture.Controls>
<div
style={{
padding: '20px',
backgroundColor: '#f5f5f5',
border: '1px solid #ddd',
}}>
<Fragment ref={fragmentRef}>
This fragment contains only text. Text nodes are not focusable.
</Fragment>
</div>
</Fixture>
</TestCase>
);
}
function ScrollIntoViewTextOnly() {
const fragmentRef = useRef(null);
const [message, setMessage] = useState('');
const tryScrollIntoView = alignToTop => {
fragmentRef.current.scrollIntoView(alignToTop);
setMessage(
`Called scrollIntoView(${alignToTop}) - page should scroll to text`
);
};
return (
<TestCase title="scrollIntoView - Text Only">
<TestCase.Steps>
<li>Scroll down the page so the text fragment is not visible</li>
<li>Click one of the scrollIntoView buttons</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The page should scroll to bring the text content into view. With
alignToTop=true, the text should appear at the top of the viewport. With
alignToTop=false, it should appear at the bottom. This uses the Range
API to calculate text node positions.
</TestCase.ExpectedResult>
<Fixture>
<Fixture.Controls>
<button onClick={() => tryScrollIntoView(true)}>
scrollIntoView(true)
</button>
<button onClick={() => tryScrollIntoView(false)}>
scrollIntoView(false)
</button>
{message && (
<div style={{marginTop: '10px', color: 'green'}}>{message}</div>
)}
</Fixture.Controls>
<div
style={{
marginTop: '100vh',
marginBottom: '100vh',
padding: '20px',
backgroundColor: '#f0fff0',
border: '1px solid #cfc',
}}>
<Fragment ref={fragmentRef}>
This fragment contains only text. The scrollIntoView method uses the
Range API to calculate the text position and scroll to it.
</Fragment>
</div>
</Fixture>
</TestCase>
);
}
function ScrollIntoViewMixed() {
const fragmentRef = useRef(null);
const [message, setMessage] = useState('');
const tryScrollIntoView = alignToTop => {
fragmentRef.current.scrollIntoView(alignToTop);
setMessage(
`Called scrollIntoView(${alignToTop}) - page should scroll to fragment`
);
};
const targetStyle = {
height: 300,
marginBottom: 50,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '24px',
fontWeight: 'bold',
};
return (
<TestCase title="scrollIntoView - Mixed Content">
<TestCase.Steps>
<li>Scroll down the page so the fragment is not visible</li>
<li>Click one of the scrollIntoView buttons</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The fragment contains raw text nodes (not wrapped in elements) and
elements in alternating order. With alignToTop=true, scroll starts from
the last child and works backwards, ending with the first text node at
the top. With alignToTop=false, scroll starts from the first child and
works forward, ending with the last text node at the bottom. Text nodes
use the Range API for scrolling.
</TestCase.ExpectedResult>
<Fixture>
<Fixture.Controls>
<button onClick={() => tryScrollIntoView(true)}>
scrollIntoView(true)
</button>
<button onClick={() => tryScrollIntoView(false)}>
scrollIntoView(false)
</button>
{message && (
<div style={{marginTop: '10px', color: 'green'}}>{message}</div>
)}
</Fixture.Controls>
<div
style={{
marginTop: '100vh',
marginBottom: '100vh',
whiteSpace: 'pre-wrap',
lineHeight: '2',
}}>
<Fragment ref={fragmentRef}>
TEXT NODE 1 - This is a raw text node at the start of the fragment
<div style={{...targetStyle, backgroundColor: 'lightyellow'}}>
ELEMENT 1
</div>
TEXT NODE 2 - This is a raw text node between elements
<div style={{...targetStyle, backgroundColor: 'lightpink'}}>
ELEMENT 2
</div>
TEXT NODE 3 - This is a raw text node between elements
<div style={{...targetStyle, backgroundColor: 'lightcyan'}}>
ELEMENT 3
</div>
TEXT NODE 4 - This is a raw text node at the end of the fragment
</Fragment>
</div>
</Fixture>
</TestCase>
);
}
function ObserveTextOnlyWarning() {
const fragmentRef = useRef(null);
const [message, setMessage] = useState('');
const tryObserve = () => {
setMessage('Called observeUsing() - check console for warning');
const observer = new IntersectionObserver(() => {});
fragmentRef.current.observeUsing(observer);
};
return (
<TestCase title="observeUsing - Text Only Warning">
<TestCase.Steps>
<li>Open the browser console</li>
<li>Click the observeUsing button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
A warning should appear in the console because IntersectionObserver
cannot observe text nodes. The warning message should indicate that
observeUsing() was called on a FragmentInstance with only text children.
</TestCase.ExpectedResult>
<Fixture>
<Fixture.Controls>
<button onClick={tryObserve}>
observeUsing(IntersectionObserver)
</button>
{message && (
<div style={{marginTop: '10px', color: 'orange'}}>{message}</div>
)}
</Fixture.Controls>
<div
style={{
padding: '20px',
backgroundColor: '#fff0f0',
border: '1px solid #fcc',
}}>
<Fragment ref={fragmentRef}>
This fragment contains only text. Text nodes cannot be observed.
</Fragment>
</div>
</Fixture>
</TestCase>
);
}
export default function TextNodesCase() {
return (
<TestCase title="Text Node Support">
<TestCase.ExpectedResult>
<p>
This section demonstrates how various FragmentInstance methods work
with text nodes.
</p>
<p>
<strong>Supported:</strong> getClientRects, compareDocumentPosition,
scrollIntoView
</p>
<p>
<strong>No-op (silent):</strong> focus, focusLast (text nodes cannot
receive focus)
</p>
<p>
<strong>Not supported (warns):</strong> observeUsing (observers cannot
observe text nodes)
</p>
</TestCase.ExpectedResult>
<GetClientRectsTextOnly />
<GetClientRectsMixed />
<FocusTextOnlyNoop />
<ScrollIntoViewTextOnly />
<ScrollIntoViewMixed />
<ObserveTextOnlyWarning />
</TestCase>
);
}
@@ -6,6 +6,7 @@ import ResizeObserverCase from './ResizeObserverCase';
import FocusCase from './FocusCase';
import GetClientRectsCase from './GetClientRectsCase';
import ScrollIntoViewCase from './ScrollIntoViewCase';
import TextNodesCase from './TextNodesCase';
const React = window.React;
@@ -19,6 +20,7 @@ export default function FragmentRefsPage() {
<FocusCase />
<GetClientRectsCase />
<ScrollIntoViewCase />
<TextNodesCase />
</FixtureSet>
);
}
@@ -127,6 +127,7 @@ import {
enableFragmentRefsScrollIntoView,
enableProfilerTimer,
enableFragmentRefsInstanceHandles,
enableFragmentRefsTextNodes,
} from 'shared/ReactFeatureFlags';
import {
HostComponent,
@@ -2956,6 +2957,7 @@ function FragmentInstance(this: FragmentInstanceType, fragmentFiber: Fiber) {
this._eventListeners = null;
this._observers = null;
}
// $FlowFixMe[prop-missing]
FragmentInstance.prototype.addEventListener = function (
this: FragmentInstanceType,
@@ -3119,6 +3121,12 @@ function setFocusOnFiberIfFocusable(
fiber: Fiber,
focusOptions?: FocusOptions,
): boolean {
if (enableFragmentRefsTextNodes) {
// Skip text nodes - they are not focusable
if (fiber.tag === HostText) {
return false;
}
}
const instance = getInstanceFromHostFiber<Instance>(fiber);
return setFocusIfFocusable(instance, focusOptions);
}
@@ -3169,6 +3177,28 @@ FragmentInstance.prototype.observeUsing = function (
this: FragmentInstanceType,
observer: IntersectionObserver | ResizeObserver,
): void {
if (__DEV__) {
if (enableFragmentRefsTextNodes) {
let hasText = false;
let hasElement = false;
traverseFragmentInstance(this._fragmentFiber, (child: Fiber) => {
if (child.tag === HostText) {
hasText = true;
} else {
// Stop traversal, found element
hasElement = true;
return true;
}
return false;
});
if (hasText && !hasElement) {
console.error(
'observeUsing() was called on a FragmentInstance with only text children. ' +
'Observers do not work on text nodes.',
);
}
}
}
if (this._observers === null) {
this._observers = new Set();
}
@@ -3179,6 +3209,12 @@ function observeChild(
child: Fiber,
observer: IntersectionObserver | ResizeObserver,
) {
if (enableFragmentRefsTextNodes) {
// Skip text nodes - observers don't work on them
if (child.tag === HostText) {
return false;
}
}
const instance = getInstanceFromHostFiber<Instance>(child);
observer.observe(instance);
return false;
@@ -3205,6 +3241,12 @@ function unobserveChild(
child: Fiber,
observer: IntersectionObserver | ResizeObserver,
) {
if (enableFragmentRefsTextNodes) {
// Skip text nodes - they were never observed
if (child.tag === HostText) {
return false;
}
}
const instance = getInstanceFromHostFiber<Instance>(child);
observer.unobserve(instance);
return false;
@@ -3218,9 +3260,17 @@ FragmentInstance.prototype.getClientRects = function (
return rects;
};
function collectClientRects(child: Fiber, rects: Array<DOMRect>): boolean {
const instance = getInstanceFromHostFiber<Instance>(child);
// $FlowFixMe[method-unbinding]
rects.push.apply(rects, instance.getClientRects());
if (enableFragmentRefsTextNodes && child.tag === HostText) {
const textNode: Text = child.stateNode;
const range = textNode.ownerDocument.createRange();
range.selectNodeContents(textNode);
// $FlowFixMe[method-unbinding]
rects.push.apply(rects, range.getClientRects());
} else {
const instance = getInstanceFromHostFiber<Instance>(child);
// $FlowFixMe[method-unbinding]
rects.push.apply(rects, instance.getClientRects());
}
return false;
}
// $FlowFixMe[prop-missing]
@@ -3426,6 +3476,19 @@ if (enableFragmentRefsScrollIntoView) {
let i = resolvedAlignToTop ? children.length - 1 : 0;
while (i !== (resolvedAlignToTop ? -1 : children.length)) {
const child = children[i];
// For text nodes, use Range API to scroll to their position
if (enableFragmentRefsTextNodes && child.tag === HostText) {
const textNode: Text = child.stateNode;
const range = textNode.ownerDocument.createRange();
range.selectNodeContents(textNode);
const rect = range.getBoundingClientRect();
const scrollY = resolvedAlignToTop
? window.scrollY + rect.top
: window.scrollY + rect.bottom - window.innerHeight;
window.scrollTo(window.scrollX + rect.left, scrollY);
i += resolvedAlignToTop ? -1 : 1;
continue;
}
const instance = getInstanceFromHostFiber<Instance>(child);
instance.scrollIntoView(alignToTop);
i += resolvedAlignToTop ? -1 : 1;
@@ -20,6 +20,7 @@ let Activity;
let mockIntersectionObserver;
let simulateIntersection;
let setClientRects;
let mockRangeClientRects;
let assertConsoleErrorDev;
function Wrapper({children}) {
@@ -40,6 +41,7 @@ describe('FragmentRefs', () => {
mockIntersectionObserver = IntersectionMocks.mockIntersectionObserver;
simulateIntersection = IntersectionMocks.simulateIntersection;
setClientRects = IntersectionMocks.setClientRects;
mockRangeClientRects = IntersectionMocks.mockRangeClientRects;
assertConsoleErrorDev =
require('internal-test-utils').assertConsoleErrorDev;
@@ -2426,4 +2428,169 @@ describe('FragmentRefs', () => {
});
});
});
describe('with text nodes', () => {
// @gate enableFragmentRefs && enableFragmentRefsTextNodes
it('getClientRects includes text node bounds', async () => {
const restoreRange = mockRangeClientRects([
{x: 0, y: 0, width: 80, height: 16},
]);
const fragmentRef = React.createRef();
const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<div>
<Fragment ref={fragmentRef}>Hello World</Fragment>
</div>,
),
);
const rects = fragmentRef.current.getClientRects();
expect(rects.length).toBe(1);
expect(rects[0].width).toBe(80);
restoreRange();
});
// @gate enableFragmentRefs && enableFragmentRefsTextNodes
it('getClientRects includes both text and element bounds', async () => {
const restoreRange = mockRangeClientRects([
{x: 0, y: 0, width: 60, height: 16},
]);
const fragmentRef = React.createRef();
const childRef = React.createRef();
const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<div>
<Fragment ref={fragmentRef}>
Text before
<div ref={childRef}>Element</div>
Text after
</Fragment>
</div>,
),
);
setClientRects(childRef.current, [
{x: 10, y: 10, width: 100, height: 20},
]);
const rects = fragmentRef.current.getClientRects();
// Should have rects from 2 text nodes + 1 element = 3 total
expect(rects.length).toBe(3);
restoreRange();
});
// @gate enableFragmentRefs
it('compareDocumentPosition works with text children', async () => {
const fragmentRef = React.createRef();
const beforeRef = React.createRef();
const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<div>
<div ref={beforeRef} />
<Fragment ref={fragmentRef}>Text content</Fragment>
</div>,
),
);
const position = fragmentRef.current.compareDocumentPosition(
beforeRef.current,
);
expect(position & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
});
// @gate enableFragmentRefs
it('focus is a no-op on text-only fragment', async () => {
const fragmentRef = React.createRef();
const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<div>
<Fragment ref={fragmentRef}>Text only content</Fragment>
</div>,
),
);
// Should not throw or warn - just a silent no-op
fragmentRef.current.focus();
// Test passes if no error is thrown
});
// @gate enableFragmentRefs
it('focusLast is a no-op on text-only fragment', async () => {
const fragmentRef = React.createRef();
const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<div>
<Fragment ref={fragmentRef}>Text only content</Fragment>
</div>,
),
);
// Should not throw or warn - just a silent no-op
fragmentRef.current.focusLast();
});
// @gate enableFragmentRefs && enableFragmentRefsTextNodes
it('warns when observeUsing is called on text-only fragment', async () => {
mockIntersectionObserver();
const fragmentRef = React.createRef();
const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<div>
<Fragment ref={fragmentRef}>Text only content</Fragment>
</div>,
),
);
const observer = new IntersectionObserver(() => {});
fragmentRef.current.observeUsing(observer);
assertConsoleErrorDev(
[
'observeUsing() was called on a FragmentInstance with only text children. ' +
'Observers do not work on text nodes.',
],
{withoutStack: true},
);
});
// @gate enableFragmentRefs && enableFragmentRefsScrollIntoView
it('scrollIntoView works on text-only fragment using Range API', async () => {
const restoreRange = mockRangeClientRects([
{x: 100, y: 200, width: 80, height: 16},
]);
const fragmentRef = React.createRef();
const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<div>
<Fragment ref={fragmentRef}>Text content</Fragment>
</div>,
),
);
// Mock window.scrollTo to verify it was called
const originalScrollTo = window.scrollTo;
const scrollToMock = jest.fn();
window.scrollTo = scrollToMock;
fragmentRef.current.scrollIntoView();
// Should have called window.scrollTo for the text node
expect(scrollToMock).toHaveBeenCalled();
window.scrollTo = originalScrollTo;
restoreRange();
});
});
});
@@ -93,3 +93,58 @@ export function setClientRects(target, rects) {
}));
};
}
/**
* Mock Range.prototype.getClientRects and getBoundingClientRect since jsdom doesn't implement them.
* Call this in beforeEach to set up the mock.
*/
export function mockRangeClientRects(
rects = [{x: 0, y: 0, width: 100, height: 20}],
) {
const originalCreateRange = document.createRange;
document.createRange = function () {
const range = originalCreateRange.call(document);
range.getClientRects = function () {
return rects.map(({x, y, width, height}) => ({
width,
height,
left: x,
right: x + width,
top: y,
bottom: y + height,
x,
y,
}));
};
range.getBoundingClientRect = function () {
// Return the bounding rect that encompasses all rects
if (rects.length === 0) {
return {
width: 0,
height: 0,
left: 0,
right: 0,
top: 0,
bottom: 0,
x: 0,
y: 0,
};
}
const first = rects[0];
return {
width: first.width,
height: first.height,
left: first.x,
right: first.x + first.width,
top: first.y,
bottom: first.y + first.height,
x: first.x,
y: first.y,
};
};
return range;
};
return function restore() {
document.createRange = originalCreateRange;
};
}
+6 -1
View File
@@ -29,6 +29,7 @@ import {
Fragment,
} from './ReactWorkTags';
import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
import {enableFragmentRefsTextNodes} from 'shared/ReactFeatureFlags';
export function getNearestMountedFiber(fiber: Fiber): null | Fiber {
let node = fiber;
@@ -373,7 +374,10 @@ function traverseVisibleHostChildren<A, B, C>(
c: C,
): boolean {
while (child !== null) {
if (child.tag === HostComponent && fn(child, a, b, c)) {
const isHostNode =
child.tag === HostComponent ||
(enableFragmentRefsTextNodes && child.tag === HostText);
if (isHostNode && fn(child, a, b, c)) {
return true;
} else if (
child.tag === OffscreenComponent &&
@@ -473,6 +477,7 @@ function findFragmentInstanceSiblings(
export function getInstanceFromHostFiber<I>(fiber: Fiber): I {
switch (fiber.tag) {
case HostComponent:
case HostText:
return fiber.stateNode;
case HostRoot:
return fiber.stateNode.containerInfo;
+1
View File
@@ -144,6 +144,7 @@ export const enableInfiniteRenderLoopDetection: boolean = false;
export const enableFragmentRefs: boolean = true;
export const enableFragmentRefsScrollIntoView: boolean = true;
export const enableFragmentRefsInstanceHandles: boolean = false;
export const enableFragmentRefsTextNodes: boolean = true;
export const enableInternalInstanceMap: boolean = false;
@@ -25,3 +25,4 @@ export const passChildrenWhenCloningPersistedNodes = __VARIANT__;
export const enableFragmentRefs = __VARIANT__;
export const enableFragmentRefsScrollIntoView = __VARIANT__;
export const enableFragmentRefsInstanceHandles = __VARIANT__;
export const enableFragmentRefsTextNodes = __VARIANT__;
@@ -27,6 +27,7 @@ export const {
enableFragmentRefs,
enableFragmentRefsScrollIntoView,
enableFragmentRefsInstanceHandles,
enableFragmentRefsTextNodes,
} = dynamicFlags;
// The rest of the flags are static for better dead code elimination.
@@ -72,6 +72,7 @@ export const ownerStackLimit = 1e4;
export const enableFragmentRefs: boolean = true;
export const enableFragmentRefsScrollIntoView: boolean = false;
export const enableFragmentRefsInstanceHandles: boolean = false;
export const enableFragmentRefsTextNodes: boolean = false;
export const enableInternalInstanceMap: boolean = false;
@@ -73,6 +73,7 @@ export const ownerStackLimit = 1e4;
export const enableFragmentRefs: boolean = true;
export const enableFragmentRefsScrollIntoView: boolean = true;
export const enableFragmentRefsInstanceHandles: boolean = false;
export const enableFragmentRefsTextNodes: boolean = true;
export const enableInternalInstanceMap: boolean = false;
@@ -65,6 +65,8 @@ export const enableHydrationChangeEvent = false;
export const enableDefaultTransitionIndicator = true;
export const enableFragmentRefs = false;
export const enableFragmentRefsScrollIntoView = false;
export const enableFragmentRefsInstanceHandles = false;
export const enableFragmentRefsTextNodes = false;
export const ownerStackLimit = 1e4;
export const enableOptimisticKey = false;
@@ -78,6 +78,7 @@ export const enableDefaultTransitionIndicator: boolean = true;
export const enableFragmentRefs: boolean = false;
export const enableFragmentRefsScrollIntoView: boolean = false;
export const enableFragmentRefsInstanceHandles: boolean = false;
export const enableFragmentRefsTextNodes: boolean = false;
export const ownerStackLimit = 1e4;
export const enableInternalInstanceMap: boolean = false;
@@ -34,6 +34,7 @@ export const enableViewTransition: boolean = __VARIANT__;
export const enableScrollEndPolyfill: boolean = __VARIANT__;
export const enableFragmentRefs: boolean = __VARIANT__;
export const enableFragmentRefsScrollIntoView: boolean = __VARIANT__;
export const enableFragmentRefsTextNodes: boolean = __VARIANT__;
export const enableAsyncDebugInfo: boolean = __VARIANT__;
export const enableInternalInstanceMap: boolean = __VARIANT__;
export const enableTrustedTypesIntegration: boolean = __VARIANT__;
@@ -32,6 +32,7 @@ export const {
enableScrollEndPolyfill,
enableFragmentRefs,
enableFragmentRefsScrollIntoView,
enableFragmentRefsTextNodes,
enableAsyncDebugInfo,
enableInternalInstanceMap,
} = dynamicFeatureFlags;