mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Create example for MutationObserver in RNTester (disabled by feature flag) (#56622)
Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/56622 Changelog: [internal] Adds examples for MutationObserver if the API is available (which isn't normally as it's gated). Reviewed By: fabriziocucci Differential Revision: D102593725 fbshipit-source-id: cdcfe613b485bf9b015a342cb51003ce43455096
This commit is contained in:
1 parent
9ac9edc61e
commit
b396df7606
7 files changed
+622
No files matched your search
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* 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 * as React from 'react';
|
||||
import {type ElementRef, useContext, useEffect, useRef, useState} from 'react';
|
||||
import {Pressable, ScrollView, StyleSheet, Text, View} from 'react-native';
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
component MutationObserverExample() {
|
||||
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-type]
|
||||
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<Node>): string {
|
||||
return [...nodeList]
|
||||
.map(node => (node instanceof Element && 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,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 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];
|
||||
|
||||
if (typeof IntersectionObserver !== 'undefined') {
|
||||
examples.push(VisualCompletionExample);
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* 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',
|
||||
},
|
||||
});
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
export type VisualElement = {
|
||||
time: number,
|
||||
rect: DOMRectReadOnly,
|
||||
};
|
||||
|
||||
function debug(...args: ReadonlyArray<unknown>): void {
|
||||
console.debug('VCTrackerExample', args);
|
||||
}
|
||||
|
||||
export default class VCTracker {
|
||||
_navigationStartTime: number;
|
||||
_intersectionObserver: IntersectionObserver;
|
||||
_mutationObserver: MutationObserver;
|
||||
_registeredCallback: (ReadonlyArray<VisualElement>) => void;
|
||||
_visualElements: Map<Element, VisualElement> = new Map();
|
||||
_pendingMutations: WeakSet<Node> = 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 Element) {
|
||||
this._intersectionObserver.observe(addedNode);
|
||||
}
|
||||
}
|
||||
for (const removedNode of entry.removedNodes) {
|
||||
// To measure paint time for added nodes
|
||||
this._pendingMutations.delete(removedNode);
|
||||
if (removedNode instanceof Element) {
|
||||
this._unregisterVisualElement(removedNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_registerVisualElement(target: Element, visualElement: VisualElement): void {
|
||||
debug(
|
||||
'registerVisualElement',
|
||||
(target instanceof Element && target.id) || '<target-without-id>',
|
||||
'. Painted in',
|
||||
(visualElement.time - this._navigationStartTime).toFixed(2),
|
||||
'ms (at ',
|
||||
visualElement.time,
|
||||
'), rect:',
|
||||
// $FlowExpectedError[prop-missing] - DOMRectReadOnly isn't typed correctly.
|
||||
visualElement.rect.toJSON(),
|
||||
);
|
||||
|
||||
this._visualElements.set(target, visualElement);
|
||||
this._registeredCallback?.([...this._visualElements.values()]);
|
||||
}
|
||||
|
||||
_unregisterVisualElement(target: Element): void {
|
||||
this._visualElements.delete(target);
|
||||
this._registeredCallback?.([...this._visualElements.values()]);
|
||||
}
|
||||
|
||||
onUpdateVisualElements(
|
||||
callback: (ReadonlyArray<VisualElement>) => void,
|
||||
): void {
|
||||
this._registeredCallback = callback;
|
||||
}
|
||||
|
||||
addMutationRoot(rootNode: Element): 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();
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* 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';
|
||||
|
||||
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.
|
||||
*/
|
||||
component VisualCompletionExample(vcTracker: VCTracker) {
|
||||
useEffect(() => {
|
||||
return () => vcTracker.disconnect();
|
||||
}, [vcTracker]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<VisualCompletionExampleScreen vcTracker={vcTracker} />
|
||||
<VCOverlay vcTracker={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: Element = 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,
|
||||
);
|
||||
@@ -391,6 +391,17 @@ const APIs: Array<RNTesterModuleInfo> = (
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Basic check to detect the availability of the MutationObserver API.
|
||||
// $FlowExpectedError[cannot-resolve-name]
|
||||
...(typeof MutationObserver === 'function'
|
||||
? [
|
||||
{
|
||||
key: 'MutationObserver',
|
||||
category: 'UI',
|
||||
module: require('../examples/MutationObserver/MutationObserverIndex'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Basic check to detect the availability of the modern Performance API.
|
||||
...(typeof performance.getEntries === 'function'
|
||||
? [
|
||||
|
||||
@@ -359,6 +359,17 @@ const APIs: Array<RNTesterModuleInfo> = (
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Basic check to detect the availability of the MutationObserver API.
|
||||
// $FlowExpectedError[cannot-resolve-name]
|
||||
...(typeof MutationObserver === 'function'
|
||||
? [
|
||||
{
|
||||
key: 'MutationObserver',
|
||||
category: 'UI',
|
||||
module: require('../examples/MutationObserver/MutationObserverIndex'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Basic check to detect the availability of the modern Performance API.
|
||||
...(typeof performance.getEntries === 'function'
|
||||
? [
|
||||
|
||||
Reference in new issue
Block a user