Internalise RNTester examples referencing unexported APIs (#51019)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51019

Follows D72228547 and D73770609.

This diff internalises (moves files from fbsource+GitHub to fbsource only) a number of RNTester examples which referenced `'react-native/src/private/'` subpaths.

In future, new components/APIs should be exported from index as `unstable_`, or added to `RNTesterListFbInternal` if they are exported from `src/fb_internal/`.

Changelog: [Internal]

Reviewed By: cortinico

Differential Revision: D73777092

fbshipit-source-id: d9fb0833c56f2ae580b6db62ddbbbeae774a0004
This commit is contained in:
Alex Hunt authored and Facebook GitHub Bot committed 2025-05-01 09:58:30 -07:00
1 parent ba5acdba83
commit b731ea3d3f
14 files changed
+21 -1502

No files matched your search

@@ -18,7 +18,6 @@ import RNTesterText from '../../components/RNTesterText';
import ImageCapInsetsExample from './ImageCapInsetsExample';
import React from 'react';
import {Image, ImageBackground, StyleSheet, Text, View} from 'react-native';
import * as ReactNativeFeatureFlags from 'react-native/src/private/featureflags/ReactNativeFeatureFlags';
const IMAGE1 =
'https://www.facebook.com/assets/fb_lite_messaging/E2EE-settings@3x.png';
@@ -1,130 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
import type IntersectionObserverType from 'react-native/src/private/webapis/intersectionobserver/IntersectionObserver';
import {RNTesterThemeContext} from '../../components/RNTesterTheme';
import * as React from 'react';
import {
type ElementRef,
useContext,
useLayoutEffect,
useRef,
useState,
} from 'react';
import {Button, ScrollView, StyleSheet, Text, View} from 'react-native';
declare var IntersectionObserver: Class<IntersectionObserverType>;
export const name = 'IntersectionObserver Benchmark';
export const title = name;
export const description =
'Example of using IntersectionObserver to observe a large amount of UI elements';
export function render(): React.Node {
return <IntersectionObserverBenchark />;
}
const ROWS = 100;
const COLUMNS = 5;
function IntersectionObserverBenchark(): React.Node {
const [isObserving, setObserving] = useState(false);
return (
<>
<View style={styles.buttonContainer}>
<Button
title={isObserving ? 'Stop observing' : 'Start observing'}
onPress={() => setObserving(observing => !observing)}
/>
</View>
<ScrollView>
{Array(ROWS)
.fill(null)
.map((_, row) => (
<View style={styles.row} key={row}>
{Array(COLUMNS)
.fill(null)
.map((_2, column) => (
<Item
index={COLUMNS * row + column}
observe={isObserving}
key={column}
/>
))}
</View>
))}
</ScrollView>
</>
);
}
function Item({index, observe}: {index: number, observe: boolean}): React.Node {
const theme = useContext(RNTesterThemeContext);
const ref = useRef<?ElementRef<typeof View>>();
useLayoutEffect(() => {
const element = ref.current;
if (!observe || !element) {
return;
}
const observer = new IntersectionObserver(
entries => {
// You can inspect the actual entries here.
// We don't log them by default to avoid the logs themselves to degrade
// performance.
},
{
threshold: [0, 1],
},
);
// $FlowExpectedError
observer.observe(element);
return () => {
observer.disconnect();
};
}, [observe]);
return (
<View
ref={ref}
style={[
styles.item,
{backgroundColor: theme.SecondarySystemBackgroundColor},
]}>
<Text style={[styles.itemText, {color: theme.LabelColor}]}>
{index + 1}
</Text>
</View>
);
}
const styles = StyleSheet.create({
buttonContainer: {
padding: 10,
},
row: {
flexDirection: 'row',
},
item: {
flex: 1,
padding: 12,
margin: 5,
},
itemText: {
fontSize: 22,
textAlign: 'center',
},
});
@@ -1,27 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import * as IntersectionObserverBenchmark from './IntersectionObserverBenchmark';
import * as IntersectionObserverMDNExample from './IntersectionObserverMDNExample';
import * as IntersectionObserverRootThreshold from './IntersectionObserverRootThreshold';
export const framework = 'React';
export const title = 'IntersectionObserver';
export const category = 'UI';
export const documentationURL =
'https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API';
export const description =
'API to detect paint times for elements and changes in their intersections with other elements.';
export const showIndividualExamples = true;
export const examples = [
IntersectionObserverMDNExample,
IntersectionObserverBenchmark,
IntersectionObserverRootThreshold,
];
@@ -1,181 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
import type IntersectionObserverType from 'react-native/src/private/webapis/intersectionobserver/IntersectionObserver';
import {RNTesterThemeContext} from '../../components/RNTesterTheme';
import * as React from 'react';
import {
type ElementRef,
useContext,
useLayoutEffect,
useRef,
useState,
} from 'react';
import {Button, ScrollView, StyleSheet, Text, View} from 'react-native';
declare var IntersectionObserver: Class<IntersectionObserverType>;
export const name = 'IntersectionObserver MDN Example';
export const title = name;
export const description =
'Copy of the example in MDN about IntersectionObserver with different thresholds.';
export function render(): React.Node {
return <IntersectionObserverMDNExample />;
}
/**
* Similar to the example in MDN: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
*/
function IntersectionObserverMDNExample(): React.Node {
const theme = useContext(RNTesterThemeContext);
const [showMargin, setShowMargin] = useState(true);
return (
<ScrollView>
<Button
title={`Click to ${showMargin ? 'remove' : 'add'} margin`}
onPress={() => {
setShowMargin(show => !show);
}}
/>
<Text style={[styles.scrollDownText, {color: theme.LabelColor}]}>
↓↓ Scroll down ↓↓
</Text>
{showMargin ? <View style={styles.margin} /> : null}
<ListItem position={1} thresholds={buildThresholdList(100)} />
<ListItem position={2} thresholds={[0.5]} initialValue={0.49} />
<ListItem position={3} thresholds={buildThresholdList(10)} />
<ListItem position={4} thresholds={buildThresholdList(4)} />
</ScrollView>
);
}
function ListItem(props: {
position: number,
thresholds: Array<number>,
initialValue?: number,
}): React.Node {
const itemRef = useRef<?ElementRef<typeof View>>(null);
const intersectionRatioRef = useRef(0);
const [intersectionRatio, setIntersectionRatio] = useState(
props.initialValue ?? 0,
);
useLayoutEffect(() => {
const itemNode = itemRef.current;
if (itemNode == null) {
return;
}
const intersectionObserver = new IntersectionObserver(
entries => {
entries.forEach(entry => {
if (
intersectionRatioRef.current === 0 &&
entry.intersectionRatio > 0
) {
console.log(
`Card #${props.position} switched to intersecting (according to thresholds)`,
);
} else if (
intersectionRatioRef.current !== 0 &&
entry.intersectionRatio === 0
) {
console.log(
`Card #${props.position} switched to NOT intersecting (according to thresholds)`,
);
}
intersectionRatioRef.current = entry.intersectionRatio;
setIntersectionRatio(entry.intersectionRatio);
});
},
{threshold: props.thresholds},
);
// $FlowFixMe[incompatible-call]
intersectionObserver.observe(itemNode);
return () => {
intersectionObserver.disconnect();
};
}, [props.position, props.thresholds]);
return (
<View style={styles.item} ref={itemRef}>
<IntersectionRatioIndicator
value={intersectionRatio}
style={{left: 0, top: 0}}
/>
<IntersectionRatioIndicator
value={intersectionRatio}
style={{right: 0, top: 0}}
/>
<IntersectionRatioIndicator
value={intersectionRatio}
style={{left: 0, bottom: 0}}
/>
<IntersectionRatioIndicator
value={intersectionRatio}
style={{right: 0, bottom: 0}}
/>
</View>
);
}
function IntersectionRatioIndicator(props: {
value: number,
style: {top?: number, bottom?: number, left?: number, right?: number},
}): React.Node {
return (
<View style={[styles.intersectionRatioIndicator, props.style]}>
<Text>{`${Math.floor(props.value * 100)}%`}</Text>
</View>
);
}
function buildThresholdList(numSteps: number): Array<number> {
const thresholds = [];
for (let i = 1.0; i <= numSteps; i++) {
const ratio = i / numSteps;
thresholds.push(ratio);
}
thresholds.push(0);
return thresholds;
}
const styles = StyleSheet.create({
scrollDownText: {
textAlign: 'center',
fontSize: 20,
marginTop: 20,
},
margin: {
marginBottom: 700,
},
item: {
backgroundColor: 'rgb(245, 170, 140)',
borderColor: 'rgb(201, 126, 17)',
borderWidth: 2,
height: 500,
margin: 6,
},
intersectionRatioIndicator: {
position: 'absolute',
padding: 5,
backgroundColor: 'white',
opacity: 0.7,
borderWidth: 1,
borderColor: 'black',
},
});
@@ -1,224 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
import type IntersectionObserverType from 'react-native/src/private/webapis/intersectionobserver/IntersectionObserver';
import {RNTesterThemeContext} from '../../components/RNTesterTheme';
import * as React from 'react';
import {
type ElementRef,
useContext,
useLayoutEffect,
useRef,
useState,
} from 'react';
import {Button, ScrollView, StyleSheet, Text, View} from 'react-native';
declare const IntersectionObserver: Class<IntersectionObserverType>;
export const name = 'IntersectionObserver Root Threshold';
export const title = name;
export const description =
'Examples of setting threshold and rnRootThreshold. Views will change background color if they meet their threshold.';
export function render(): React.Node {
return <IntersectionObserverRootThreshold />;
}
/**
* Similar to the example in MDN: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
*/
function IntersectionObserverRootThreshold(): React.Node {
const theme = useContext(RNTesterThemeContext);
const [showMargin, setShowMargin] = useState(true);
return (
<ScrollView>
<Button
title={`Click to ${showMargin ? 'remove' : 'add'} margin`}
onPress={() => {
setShowMargin(show => !show);
}}
/>
<Text style={[styles.scrollDownText, {color: theme.LabelColor}]}>
↓↓ Scroll down ↓↓
</Text>
{showMargin ? <View style={styles.margin} /> : null}
<ListItem
position={1}
rootThreshold={0.5}
threshold={0.5}
description="Should intersect when item half visible and when item takes up half the viewport"
/>
<ListItem
position={2}
rootThreshold={0.5}
threshold={1}
description="Should intersect when view takes up half of viewport and when item is fully visible"
/>
<ListItem
position={3}
threshold={1}
rootThreshold={0}
description="This should intersect when any part is visible, even though `thresholds` is 1"
/>
<ListItem
position={4}
rootThreshold={1}
threshold={1}
description="Since this item is smaller than viewport, should only intersect when view is fully visible"
/>
<ListItem
position={1}
rootThreshold={1}
threshold={1}
style={{height: 1000}}
description="This list item is larger than viewport and should intersect when it takes up all of viewport. However, this is impossible because of clipping of the scrollview. However, if we set `root` to the scrollview, we can."
/>
</ScrollView>
);
}
function ListItem(props: {
position: number,
rootThreshold: number,
threshold: number,
initialValue?: number,
description: string,
style?: ?ViewStyleProp,
}): React.Node {
const itemRef = useRef<?ElementRef<typeof View>>(null);
const [intersectionRatio, setIntersectionRatio] = useState(
props.initialValue ?? 0,
);
const [intersectionRootRatio, setIntersectionRootRatio] = useState(
props.initialValue ?? 0,
);
useLayoutEffect(() => {
const itemNode = itemRef.current;
if (itemNode == null) {
return;
}
const intersectionObserver = new IntersectionObserver(
entries => {
entries.forEach(entry => {
setIntersectionRatio(entry.intersectionRatio);
// $FlowFixMe[prop-missing] - React Native specific entry property
setIntersectionRootRatio(entry.rnRootIntersectionRatio);
});
},
{threshold: props.threshold, rnRootThreshold: props.rootThreshold},
);
// $FlowFixMe[incompatible-call]
intersectionObserver.observe(itemNode);
return () => {
intersectionObserver.disconnect();
};
}, [props.position, props.threshold, props.rootThreshold]);
return (
<View
style={[
styles.item,
intersectionRatio >= props.threshold ? styles.intersecting : null,
intersectionRootRatio >= props.rootThreshold
? styles.rootIntersecting
: null,
props.style,
]}
ref={itemRef}>
<Text style={styles.description}>{props.description}</Text>
<Text>rnRootThreshold: {props.rootThreshold}</Text>
<Text>threshold: {props.threshold}</Text>
<IntersectionRatioIndicator
intersectionRatio={intersectionRatio}
intersectionRootRatio={intersectionRootRatio}
style={{left: 0, top: 0}}
/>
<IntersectionRatioIndicator
intersectionRatio={intersectionRatio}
intersectionRootRatio={intersectionRootRatio}
style={{right: 0, top: 0}}
/>
<IntersectionRatioIndicator
intersectionRatio={intersectionRatio}
intersectionRootRatio={intersectionRootRatio}
style={{left: 0, bottom: 0}}
/>
<IntersectionRatioIndicator
intersectionRatio={intersectionRatio}
intersectionRootRatio={intersectionRootRatio}
style={{right: 0, bottom: 0}}
/>
</View>
);
}
function IntersectionRatioIndicator(props: {
intersectionRatio: number,
intersectionRootRatio: number,
style: {top?: number, bottom?: number, left?: number, right?: number},
}): React.Node {
return (
<View style={[styles.intersectionRatioIndicator, props.style]}>
<Text>
target ratio: {`${Math.floor(props.intersectionRatio * 100)}%`}
</Text>
<Text>
root ratio: {`${Math.floor(props.intersectionRootRatio * 100)}%`}
</Text>
</View>
);
}
const styles = StyleSheet.create({
scrollDownText: {
textAlign: 'center',
fontSize: 20,
marginTop: 20,
},
intersecting: {
backgroundColor: 'rgb(226, 237, 166)',
},
rootIntersecting: {
backgroundColor: 'rgb(237, 90, 45)',
},
margin: {
marginBottom: 700,
},
item: {
backgroundColor: 'rgb(186, 186, 186)',
borderColor: 'rgb(201, 126, 17)',
borderWidth: 2,
height: 500,
margin: 6,
alignItems: 'center',
justifyContent: 'center',
},
intersectionRatioIndicator: {
position: 'absolute',
padding: 5,
backgroundColor: 'white',
opacity: 0.7,
borderWidth: 1,
borderColor: 'black',
},
description: {
margin: 20,
fontSize: 16,
},
});
@@ -1,205 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
import type ReadOnlyNode from 'react-native/src/private/webapis/dom/nodes/ReadOnlyNode';
import type NodeList from 'react-native/src/private/webapis/dom/oldstylecollections/NodeList';
import {RNTesterThemeContext} from '../../components/RNTesterTheme';
import * as React from 'react';
import {type ElementRef, useContext, useEffect, useRef, useState} from 'react';
import {Pressable, ScrollView, StyleSheet, Text, View} from 'react-native';
import ReadOnlyElement from 'react-native/src/private/webapis/dom/nodes/ReadOnlyElement';
import MutationObserver from 'react-native/src/private/webapis/mutationobserver/MutationObserver';
export const name = 'MutationObserver Example';
export const title = name;
export const description =
'- Tap on elements to append a child.\n- Long tap on elements to remove them.';
export function render(): React.Node {
return <MutationObserverExample />;
}
const nextIdByPrefix: Map<string, number> = new Map();
function generateId(prefix: string): string {
let nextId = nextIdByPrefix.get(prefix);
if (nextId == null) {
nextId = 1;
}
nextIdByPrefix.set(prefix, nextId + 1);
return prefix + nextId;
}
const rootId = generateId('example-item-');
function useTemporaryValue<T>(duration: number = 2000): [?T, (?T) => void] {
const [value, setValue] = useState<?T>(null);
useEffect(() => {
const timeoutId = setTimeout(() => {
setValue(null);
}, duration);
return () => clearTimeout(timeoutId);
// we need to set the timer every time the value changes
}, [duration, value]);
return [value, setValue];
}
function MutationObserverExample(): React.Node {
const parentViewRef = useRef<?ElementRef<typeof View>>(null);
const [showExample, setShowExample] = useState(true);
const theme = useContext(RNTesterThemeContext);
const [message, setMessage] = useTemporaryValue<string>();
useEffect(() => {
const parentNode = parentViewRef.current;
if (!parentNode) {
return;
}
const mutationObserver = new MutationObserver(records => {
const messages = [];
records.forEach(record => {
if (record.addedNodes.length > 0) {
console.log(
'MutationObserverExample: added nodes',
nodeListToString(record.addedNodes),
);
messages.push(`Added nodes: ${nodeListToString(record.addedNodes)}`);
}
if (record.removedNodes.length > 0) {
console.log(
'MutationObserverExample: removed nodes',
nodeListToString(record.removedNodes),
);
messages.push(
`Removed nodes: ${nodeListToString(record.removedNodes)}`,
);
}
});
setMessage(messages.join(',\n'));
});
// $FlowExpectedError[incompatible-call]
mutationObserver.observe(parentNode, {
subtree: true,
childList: true,
});
return () => {
console.log('MutationObserverExample: disconnecting mutation observer');
mutationObserver.disconnect();
nextIdByPrefix.clear();
};
}, [setMessage]);
const exampleId = showExample ? rootId : '';
return (
<>
<ScrollView id="scroll-view">
<View style={styles.parent} ref={parentViewRef} id="parent">
{showExample ? (
<ExampleItem
label={exampleId}
id={exampleId}
onRemove={() => setShowExample(false)}
/>
) : null}
</View>
</ScrollView>
<Text id="message" style={[styles.message, {color: theme.LabelColor}]}>
{message}
</Text>
</>
);
}
function ExampleItem(props: {
id: string,
label: string,
onRemove?: () => void,
}): React.Node {
const theme = useContext(RNTesterThemeContext);
const [children, setChildren] = useState<
$ReadOnlyArray<[string, React.Node]>,
>([]);
return (
<View id={props.id}>
<Pressable
testID={'pressable-' + props.id}
style={[styles.item]}
onLongPress={() => {
props.onRemove?.();
}}
onPress={() => {
const id = generateId(props.label + '-');
setChildren(prevChildren => [
...prevChildren,
[
id,
<ExampleItem
id={id}
key={id}
label={id}
onRemove={() => {
setChildren(prevChildren2 =>
prevChildren2.filter(pair => pair[0] !== id),
);
}}
/>,
],
]);
}}>
{props.label != null ? (
<Text
id={'text-' + props.id}
style={[styles.label, {color: theme.LabelColor}]}>
{props.label}
</Text>
) : null}
{children.map(([id, child]) => child)}
</Pressable>
</View>
);
}
function nodeListToString(nodeList: NodeList<ReadOnlyNode>): string {
return [...nodeList]
.map(
node => (node instanceof ReadOnlyElement && node.id) || '<unknown-node>',
)
.join(', ');
}
const styles = StyleSheet.create({
parent: {
flex: 1,
backgroundColor: 'white',
},
item: {
backgroundColor: 'rgba(0, 0, 0, 0.5)',
flex: 1,
gap: 16,
minHeight: 50,
padding: 40,
},
label: {
position: 'absolute',
top: 0,
right: 0,
fontSize: 10,
},
message: {
padding: 10,
},
});
@@ -1,28 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
import * as MutationObserverExample from './MutationObserverExample';
import * as VisualCompletionExample from './VisualCompletionExample/VisualCompletionExample';
export const framework = 'React';
export const title = 'MutationObserver';
export const category = 'UI';
export const documentationURL =
'https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver';
export const description = 'API to detect mutations in React Native nodes.';
export const showIndividualExamples = true;
export const examples: Array<RNTesterModuleExample> = [MutationObserverExample];
// $FlowExpectedError[cannot-resolve-name]
if (typeof IntersectionObserver !== 'undefined') {
examples.push(VisualCompletionExample);
}
@@ -1,68 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type VCTracker, {VisualElement} from './VCTrackerExample';
import * as React from 'react';
import {useEffect, useState} from 'react';
import {Dimensions, StyleSheet, View} from 'react-native';
const OVERLAY_SCALE = 0.25;
export default function VCOverlayExample(props: {
vcTracker: VCTracker,
}): React.Node {
const [visualElements, setVisualElements] = useState<
$ReadOnlyArray<VisualElement>,
>([]);
useEffect(() => {
setVisualElements(props.vcTracker.getVisualElements());
props.vcTracker.onUpdateVisualElements(elements => {
setVisualElements(elements);
});
}, [props.vcTracker]);
return (
<View style={styles.overlay}>
{visualElements.map((visualElement, index) => (
<View
key={index}
style={[
styles.overlayElement,
{
top: visualElement.rect.top * OVERLAY_SCALE,
left: visualElement.rect.left * OVERLAY_SCALE,
width: visualElement.rect.width * OVERLAY_SCALE,
height: visualElement.rect.height * OVERLAY_SCALE,
},
]}
/>
))}
</View>
);
}
const styles = StyleSheet.create({
overlay: {
position: 'absolute',
bottom: 60,
right: 10,
width: OVERLAY_SCALE * Dimensions.get('window').width,
height: OVERLAY_SCALE * Dimensions.get('window').height,
backgroundColor: 'gray',
opacity: 0.9,
},
overlayElement: {
position: 'absolute',
borderWidth: 1,
borderColor: 'black',
},
});
@@ -1,130 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type ReadOnlyNode from 'react-native/src/private/webapis/dom/nodes/ReadOnlyNode';
import type DOMRectReadOnly from 'react-native/src/private/webapis/geometry/DOMRectReadOnly';
import ReactNativeElement from 'react-native/src/private/webapis/dom/nodes/ReactNativeElement';
import IntersectionObserver from 'react-native/src/private/webapis/intersectionobserver/IntersectionObserver';
import MutationObserver from 'react-native/src/private/webapis/mutationobserver/MutationObserver';
export type VisualElement = {
time: number,
rect: DOMRectReadOnly,
};
function debug(...args: $ReadOnlyArray<mixed>): void {
console.debug('VCTrackerExample', args);
}
export default class VCTracker {
_navigationStartTime: number;
_intersectionObserver: IntersectionObserver;
_mutationObserver: MutationObserver;
_registeredCallback: ($ReadOnlyArray<VisualElement>) => void;
_visualElements: Map<ReadOnlyNode, VisualElement> = new Map();
_pendingMutations: WeakSet<ReadOnlyNode> = new WeakSet();
constructor(navigationStartTime: number) {
this._navigationStartTime = navigationStartTime;
// This should be guaranteed to run before painting RootView in native.
this._intersectionObserver = new IntersectionObserver(
(entries, observer) => {
// This will be executed after mount/paint.
for (const entry of entries) {
if (this._pendingMutations.has(entry.target)) {
this._registerVisualElement(entry.target, {
time: entry.time,
rect: entry.boundingClientRect,
});
this._pendingMutations.delete(entry.target);
this._intersectionObserver.unobserve(entry.target);
}
}
},
);
this._mutationObserver = new MutationObserver((entries, observer) => {
// This will be executed after layout effects, and before mount/paint.
for (const entry of entries) {
if (entry.addedNodes) {
for (const addedNode of entry.addedNodes) {
// To measure paint time for added nodes
this._pendingMutations.add(addedNode);
if (addedNode instanceof ReactNativeElement) {
this._intersectionObserver.observe(addedNode);
}
}
for (const removedNode of entry.removedNodes) {
// To measure paint time for added nodes
this._pendingMutations.delete(removedNode);
if (removedNode instanceof ReactNativeElement) {
this._unregisterVisualElement(removedNode);
}
}
}
}
});
}
_registerVisualElement(
target: ReadOnlyNode,
visualElement: VisualElement,
): void {
debug(
'registerVisualElement',
(target instanceof ReactNativeElement && target.id) ||
'<target-without-id>',
'. Painted in',
(visualElement.time - this._navigationStartTime).toFixed(2),
'ms (at ',
visualElement.time,
'), rect:',
visualElement.rect.toJSON(),
);
this._visualElements.set(target, visualElement);
this._registeredCallback?.([...this._visualElements.values()]);
}
_unregisterVisualElement(target: ReadOnlyNode): void {
this._visualElements.delete(target);
this._registeredCallback?.([...this._visualElements.values()]);
}
onUpdateVisualElements(
callback: ($ReadOnlyArray<VisualElement>) => void,
): void {
this._registeredCallback = callback;
}
addMutationRoot(rootNode: ReactNativeElement): void {
debug('addMutationRoot', rootNode.id);
// To observe new nodes added.
this._mutationObserver.observe(rootNode, {
subtree: true,
childList: true,
});
this._pendingMutations.add(rootNode);
// To measure initial paint.
this._intersectionObserver.observe(rootNode);
}
getVisualElements(): $ReadOnlyArray<VisualElement> {
return [...this._visualElements.values()];
}
disconnect(): void {
this._mutationObserver.disconnect();
this._intersectionObserver.disconnect();
}
}
@@ -1,188 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import {RNTesterThemeContext} from '../../../components/RNTesterTheme';
import VCOverlay from './VCOverlayExample';
import VCTracker from './VCTrackerExample';
import nullthrows from 'nullthrows';
import * as React from 'react';
import {useContext, useEffect} from 'react';
import {
ActivityIndicator,
ScrollView,
StyleSheet,
Text,
View,
} from 'react-native';
import ReactNativeElement from 'react-native/src/private/webapis/dom/nodes/ReactNativeElement';
export const name = 'Visual Completion Example';
export const title = name;
export const description =
'Example of use of MutationObserver and IntersectionObserver together to track rendering performance.';
export function render(): React.Node {
// We should use the time of the touch up event that lead to this navigation,
// but we don't have that set up.
const navigationStartTime = performance.now();
const vcTracker = new VCTracker(navigationStartTime);
return <VisualCompletionExample vcTracker={vcTracker} />;
}
/**
* We are going to track the visual completion of this component, which uses
* suspense and renders a complex tree in multiple steps.
*/
function VisualCompletionExample(props: {vcTracker: VCTracker}): React.Node {
useEffect(() => {
return () => props.vcTracker.disconnect();
}, [props.vcTracker]);
return (
<>
<VisualCompletionExampleScreen vcTracker={props.vcTracker} />
<VCOverlay vcTracker={props.vcTracker} />
</>
);
}
function VisualCompletionExampleScreen(props: {
vcTracker: VCTracker,
}): React.Node {
const theme = useContext(RNTesterThemeContext);
return (
<View
id="root-view"
style={styles.root}
ref={node => {
if (node != null) {
// $FlowExpectedError[incompatible-type]
const element: ReactNativeElement = node;
props.vcTracker.addMutationRoot(element);
}
}}>
<View id="header" style={styles.header}>
<Text style={styles.title} id="header-text">
Title
</Text>
</View>
<View id="body" style={styles.body}>
<React.Suspense
fallback={
<View id="fallback">
<ActivityIndicator />
</View>
}>
<ForceSuspense queryID={generateQueryID()} delay={500}>
<View id="scroll-view-root">
<ScrollView id="scroll-view">
<React.Suspense fallback={<ActivityIndicator />}>
<ForceSuspense queryID={generateQueryID()} delay={2500}>
<Text
style={[styles.heading, {color: theme.LabelColor}]}
id="scroll-view-heading">
Heading
</Text>
</ForceSuspense>
</React.Suspense>
<React.Suspense fallback={<ActivityIndicator />}>
<ForceSuspense queryID={generateQueryID()} delay={4500}>
<View style={styles.bodyContent} id="scroll-view-content" />
</ForceSuspense>
</React.Suspense>
<Text id="scroll-view-text" style={{color: theme.LabelColor}}>
{LONG_TEXT}
</Text>
</ScrollView>
</View>
</ForceSuspense>
</React.Suspense>
</View>
<View id="footer" style={styles.footer}>
<Text id="footer-text">Example copyright footer</Text>
</View>
</View>
);
}
function ForceSuspense(props: {
queryID: string,
delay: number,
children: React.Node,
}): React.Node {
useForceSuspense(props.queryID, props.delay);
return props.children;
}
let lastQueryID = 0;
function generateQueryID() {
lastQueryID++;
return 'query-id-' + lastQueryID;
}
const styles = StyleSheet.create({
root: {
flex: 1,
},
header: {
padding: 10,
backgroundColor: 'gray',
},
title: {
textAlign: 'center',
fontSize: 20,
},
body: {
flex: 1,
padding: 10,
},
heading: {
fontSize: 16,
},
bodyContent: {
width: 100,
height: 100,
backgroundColor: 'blue',
margin: 50,
},
footer: {
padding: 10,
backgroundColor: 'gray',
},
});
const store: Map<string, {promise: Promise<void>, resolved: boolean}> =
new Map();
function useForceSuspense(queryID: string, delay: number): void {
let entry = store.get(queryID);
if (!entry) {
entry = {
resolved: false,
promise: new Promise(resolve => {
setTimeout(() => {
nullthrows(entry).resolved = true;
resolve();
}, delay);
}),
};
store.set(queryID, entry);
}
if (!entry.resolved) {
throw entry.promise;
}
}
const LONG_TEXT =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas facilisis feugiat ipsum, non placerat nulla. Vestibulum tincidunt eu dui ut bibendum. Cras risus ex, rhoncus auctor velit ut, lobortis convallis turpis. Donec rutrum imperdiet ante, vitae accumsan velit convallis non. Suspendisse feugiat egestas lectus. In eget fringilla ligula, at vehicula orci. Cras laoreet hendrerit urna, sed tincidunt dolor consectetur dapibus.\n'.repeat(
10,
);
@@ -1,276 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
* @oncall react_native
*/
import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
import type MemoryInfo from 'react-native/src/private/webapis/performance/MemoryInfo';
import type ReactNativeStartupTiming from 'react-native/src/private/webapis/performance/ReactNativeStartupTiming';
import RNTesterText from '../../components/RNTesterText';
import * as React from 'react';
import {useEffect} from 'react';
import {Button, StyleSheet, View} from 'react-native';
import Performance from 'react-native/src/private/webapis/performance/Performance';
import {
type PerformanceEntry,
type PerformanceEventTiming,
PerformanceObserver,
} from 'react-native/src/private/webapis/performance/PerformanceObserver';
const {useState, useCallback} = React;
const performance = new Performance();
function MemoryExample(): React.Node {
// Memory API testing
const [memoryInfo, setMemoryInfo] = useState<?MemoryInfo>(null);
const onGetMemoryInfo = useCallback(() => {
// performance.memory is not included in bom.js yet.
// Once we release the change in flow this can be removed.
setMemoryInfo(performance.memory);
}, []);
return (
<View style={styles.container}>
<Button onPress={onGetMemoryInfo} title="Click to update memory info" />
<View>
<RNTesterText>
{`jsHeapSizeLimit: ${String(memoryInfo?.jsHeapSizeLimit)} bytes`}
</RNTesterText>
<RNTesterText>
{`totalJSHeapSize: ${String(memoryInfo?.totalJSHeapSize)} bytes`}
</RNTesterText>
<RNTesterText>
{`usedJSHeapSize: ${String(memoryInfo?.usedJSHeapSize)} bytes`}
</RNTesterText>
</View>
</View>
);
}
function StartupTimingExample(): React.Node {
// React Startup Timing API testing
const [startUpTiming, setStartUpTiming] =
useState<?ReactNativeStartupTiming>(null);
const onGetStartupTiming = useCallback(() => {
// performance.reactNativeStartupTiming is not included in bom.js yet.
// Once we release the change in flow this can be removed.
setStartUpTiming(performance.rnStartupTiming);
}, []);
return (
<View style={styles.container}>
<Button
onPress={onGetStartupTiming}
title="Click to update React startup timing"
/>
<View>
<RNTesterText>{`startTime: ${String(startUpTiming?.startTime)} ms`}</RNTesterText>
<RNTesterText>{`initializeRuntimeStart: ${String(
startUpTiming?.initializeRuntimeStart,
)} ms`}</RNTesterText>
<RNTesterText>
{`executeJavaScriptBundleEntryPointStart: ${String(
startUpTiming?.executeJavaScriptBundleEntryPointStart,
)} ms`}
</RNTesterText>
<RNTesterText>{`executeJavaScriptBundleEntryPointEnd: ${String(
startUpTiming?.executeJavaScriptBundleEntryPointEnd,
)} ms`}</RNTesterText>
<RNTesterText>{`initializeRuntimeEnd: ${String(
startUpTiming?.initializeRuntimeEnd,
)} ms`}</RNTesterText>
<RNTesterText>{`endTime: ${String(startUpTiming?.endTime)} ms`}</RNTesterText>
</View>
</View>
);
}
function PerformanceObserverUserTimingExample(): React.Node {
const [entries, setEntries] = useState<$ReadOnlyArray<PerformanceEntry>>([]);
useEffect(() => {
const observer = new PerformanceObserver(list => {
const newEntries = list
.getEntries()
.filter(entry => entry.name.startsWith('rntester-'));
if (newEntries.length > 0) {
setEntries(newEntries);
}
});
observer.observe({entryTypes: ['mark', 'measure']});
return () => observer.disconnect();
}, []);
const onPress = useCallback(() => {
performance.mark('rntester-mark1');
performance.mark('rntester-mark2');
performance.measure(
'rntester-measure1',
'rntester-mark1',
'rntester-mark2',
);
}, []);
return (
<View style={styles.container}>
<Button onPress={onPress} title="Click to log some marks and measures" />
<View>
{entries.map((entry, index) =>
entry.entryType === 'mark' ? (
<RNTesterText key={index}>
Mark {entry.name}: {entry.startTime.toFixed(2)}
</RNTesterText>
) : (
<RNTesterText key={index}>
Measure {entry.name}: {entry.startTime.toFixed(2)} -{' '}
{(entry.startTime + entry.duration).toFixed(2)} (
{entry.duration.toFixed(2)}ms)
</RNTesterText>
),
)}
</View>
</View>
);
}
function PerformanceObserverEventTimingExample(): React.Node {
const [count, setCount] = useState(0);
const [entries, setEntries] = useState<
$ReadOnlyArray<PerformanceEventTiming>,
>([]);
useEffect(() => {
const observer = new PerformanceObserver(list => {
const newEntries: $ReadOnlyArray<PerformanceEventTiming> =
// $FlowExpectedError[incompatible-type] This is guaranteed because we're only observing `event` entry types.
list.getEntries();
setEntries(newEntries);
});
observer.observe({type: 'event'});
return () => observer.disconnect();
}, []);
const onPress = useCallback(() => {
busyWait(500);
// Force a state update to show how/if we're reporting paint times as well.
setCount(currentCount => currentCount + 1);
}, []);
return (
<View style={styles.container}>
<Button
onPress={onPress}
title={`Click to force a slow event (clicked ${count} times)`}
/>
<View>
{entries.map((entry, index) => (
<RNTesterText key={index}>
Event: {entry.name}
{'\n'}
Start: {entry.startTime.toFixed(2)}
{'\n'}
End: {(entry.startTime + entry.duration).toFixed(2)}
{'\n'}
Duration: {entry.duration.toFixed(2)}ms{'\n'}
Processing start: {entry.processingStart.toFixed(2)} (delay:{' '}
{(entry.processingStart - entry.startTime).toFixed(2)}ms){'\n'}
Processing end: {entry.processingEnd.toFixed(2)} (duration:{' '}
{(entry.processingEnd - entry.processingStart).toFixed(2)}ms){'\n'}
</RNTesterText>
))}
</View>
</View>
);
}
function PerformanceObserverLongtaskExample(): React.Node {
const [entries, setEntries] = useState<$ReadOnlyArray<PerformanceEntry>>([]);
useEffect(() => {
const observer = new PerformanceObserver(list => {
setEntries(list.getEntries());
});
observer.observe({entryTypes: ['longtask']});
return () => observer.disconnect();
}, []);
const onPress = useCallback(() => {
// Wait 1s to force a long task
busyWait(1000);
}, []);
return (
<View style={styles.container}>
<Button onPress={onPress} title="Click to force a long task" />
<View>
{entries.map((entry, index) => (
<RNTesterText key={index}>
Long task {entry.name}: {entry.startTime} -{' '}
{entry.startTime + entry.duration} ({entry.duration}ms)
</RNTesterText>
))}
</View>
</View>
);
}
function busyWait(ms: number): void {
const end = performance.now() + ms;
while (performance.now() < end) {}
}
const styles = StyleSheet.create({
container: {
padding: 10,
},
});
export const title = 'Performance API Examples';
export const category = 'Basic';
export const description = 'Shows the performance API provided in React Native';
export const examples: Array<RNTesterModuleExample> = ([
{
title: 'performance.memory',
render: (): React.Node => {
return <MemoryExample />;
},
},
{
title: 'performance.reactNativeStartupTiming',
render: (): React.Node => {
return <StartupTimingExample />;
},
},
{
title: 'PerformanceObserver (marks and measures)',
render: (): React.Node => {
return <PerformanceObserverUserTimingExample />;
},
},
{
title: 'PerformanceObserver (events)',
render: (): React.Node => {
return <PerformanceObserverEventTimingExample />;
},
},
PerformanceObserver.supportedEntryTypes.includes('longtask')
? {
title: 'PerformanceObserver (long tasks)',
render: (): React.Node => {
return <PerformanceObserverLongtaskExample />;
},
}
: null,
]: Array<?RNTesterModuleExample>).filter(Boolean);
@@ -12,6 +12,7 @@
import type {RNTesterModule, RNTesterModuleInfo} from '../types/RNTesterTypes';
import * as RNTesterListFbInternal from './RNTesterListFbInternal';
import ReactNativeFeatureFlags from 'react-native/Libraries/ReactNative/ReactNativeFeatureFlags';
const Components: Array<RNTesterModuleInfo> = [
@@ -149,6 +150,7 @@ const Components: Array<RNTesterModuleInfo> = [
key: 'OSSLibraryExample',
module: require('../examples/OSSLibraryExample/OSSLibraryExample'),
},
...RNTesterListFbInternal.Components,
];
const APIs: Array<RNTesterModuleInfo> = ([
@@ -223,15 +225,6 @@ const APIs: Array<RNTesterModuleInfo> = ([
module: require('../examples/DisplayContents/DisplayContentsExample')
.default,
},
// Only show the link for the example if the API is available.
// $FlowExpectedError[cannot-resolve-name]
typeof IntersectionObserver === 'function'
? {
key: 'IntersectionObserver',
category: 'UI',
module: require('../examples/IntersectionObserver/IntersectionObserverIndex'),
}
: null,
{
key: 'InvalidPropsExample',
module: require('../examples/InvalidProps/InvalidPropsExample'),
@@ -261,14 +254,6 @@ const APIs: Array<RNTesterModuleInfo> = ([
category: 'UI',
module: require('../examples/Layout/LayoutExample'),
},
// $FlowExpectedError[cannot-resolve-name]
typeof MutationObserver === 'function'
? {
key: 'MutationObserver',
category: 'UI',
module: require('../examples/MutationObserver/MutationObserverIndex'),
}
: null,
{
key: 'NativeAnimationsExample',
category: 'UI',
@@ -378,11 +363,7 @@ const APIs: Array<RNTesterModuleInfo> = ([
category: 'Basic',
module: require('../examples/TurboModule/TurboCxxModuleExample'),
},
{
key: 'PerformanceApiExample',
category: 'Basic',
module: require('../examples/Performance/PerformanceApiExample'),
},
...RNTesterListFbInternal.APIs,
]: Array<?RNTesterModuleInfo>).filter(Boolean);
if (ReactNativeFeatureFlags.shouldEmitW3CPointerEvents()) {
@@ -12,6 +12,7 @@
import type {RNTesterModule, RNTesterModuleInfo} from '../types/RNTesterTypes';
import * as RNTesterListFbInternal from './RNTesterListFbInternal';
import ReactNativeFeatureFlags from 'react-native/Libraries/ReactNative/ReactNativeFeatureFlags';
const Components: Array<RNTesterModuleInfo> = [
@@ -154,6 +155,7 @@ const Components: Array<RNTesterModuleInfo> = [
key: 'OSSLibraryExample',
module: require('../examples/OSSLibraryExample/OSSLibraryExample'),
},
...RNTesterListFbInternal.Components,
];
const APIs: Array<RNTesterModuleInfo> = ([
@@ -227,15 +229,6 @@ const APIs: Array<RNTesterModuleInfo> = ([
module: require('../examples/DisplayContents/DisplayContentsExample')
.default,
},
// Only show the link for the example if the API is available.
// $FlowExpectedError[cannot-resolve-name]
typeof IntersectionObserver === 'function'
? {
key: 'IntersectionObserver',
category: 'UI',
module: require('../examples/IntersectionObserver/IntersectionObserverIndex'),
}
: null,
{
key: 'InvalidPropsExample',
module: require('../examples/InvalidProps/InvalidPropsExample'),
@@ -256,14 +249,6 @@ const APIs: Array<RNTesterModuleInfo> = ([
key: 'LinkingExample',
module: require('../examples/Linking/LinkingExample'),
},
// $FlowExpectedError[cannot-resolve-name]
typeof MutationObserver === 'function'
? {
key: 'MutationObserver',
category: 'UI',
module: require('../examples/MutationObserver/MutationObserverIndex'),
}
: null,
{
key: 'NativeAnimationsExample',
module: require('../examples/NativeAnimation/NativeAnimationsExample'),
@@ -354,11 +339,7 @@ const APIs: Array<RNTesterModuleInfo> = ([
key: 'XHRExample',
module: require('../examples/XHR/XHRExample'),
},
{
key: 'PerformanceApiExample',
category: 'Basic',
module: require('../examples/Performance/PerformanceApiExample'),
},
...RNTesterListFbInternal.APIs,
]: Array<?RNTesterModuleInfo>).filter(Boolean);
if (ReactNativeFeatureFlags.shouldEmitW3CPointerEvents()) {
@@ -0,0 +1,15 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/
import type {RNTesterModuleInfo} from '../types/RNTesterTypes';
export const Components: Array<RNTesterModuleInfo> = [];
export const APIs: Array<RNTesterModuleInfo> = [];