import * as React from 'react';
import {Fragment} from 'react';
import {createPortal} from 'react-dom';

export default function Iframe(): React.Node {
  return (
    <Fragment>

Iframe

        <Frame>
          <Greeting />
        </Frame>

    </Fragment>
  );
}

const iframeStyle = {border: '2px solid #eee', height: 80};

// $FlowFixMe[missing-local-annot]
function Frame(props) {
  const [element, setElement] = React.useState(null);

  const ref = React.useRef();

ment = iframe.contentDocument;

      document.open();
      document.write(html);
      document.close();

      setElement(document.getElementById('root'));
    }
  }, []);

  return (
    <Fragment>
      <iframe title="Test Iframe" ref={ref} style={ifr

React.useLayoutEffect(function () {
    const iframe = ref.current;

    if (iframe) {
      const html = `
    <!DOCTYPE html>

    `;

      const docu


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {Fragment} from 'react';

function wrapWithHoc(Component: () => any, index: number) {
  function HOC() {
    return <Component />;
  }

  const displayName = (Component: any).displayName || Component.name;

  HOC.displayName = `withHoc${index}(${displayName})`;
  return HOC;
}

function wrapWithNested(Component: () => any, times: number)

= wrapWithHoc(Component, i);
  }

  return Component;
}

function Nested() {
  return
Deeply nested div
;
}

const DeeplyNested = wrapWithNested(Nested, 100);

export default function DeeplyNestedComponents(): React.Node {
  return (
    <Fragme

 {
  for (let i = 0; i < times; i++) {
    Component


ight (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
 */

import * as React from 'react';
import {Fragment, useState} from 'react';
import {Button, Text, View} from 'react-native-web';

export default function ReactNativeWeb(): React.Node {
  const [backgroundColor, setBackgroundColor] = useState('purple');
  const toggleColor = () =>
    setBackgroundColor(backgroundColor ==

4\u063A\u0629 \u0627\u0644\u0639\u0631\u0628\u064A\u0629 auto (default) - arabic RTL'
          }
        </Text>
        <Text style={{textAlign: 'left'}}>
          left left left left left left left left left left left left left left
          left

= 'purple' ? 'green' : 'purple');
  return (
    <Fragment>

ReactNativeWeb

      <View>
        <Text>auto (default) - english LTR</Text>
        <Text>
          {
            '\u0623\u062D\u0628 \u0627\u0644\u064


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {Fragment, useCallback, useState} from 'react';
import ListItem from './ListItem';
import styles from './List.css';

export type Item = {
  id: number,
  isComplete: boolean,
  text: string,
};

type Props = {};

export default function List(props: Props): React.Node {
  const [newItemText, setNewItemText] = useState<s

D] = useState<number>(4);

  const handleClick = useCallback(() => {
    if (newItemText !== '') {
      setItems([
        ...items,
        {
          id: uid,
          isComplete: false,
          text: newItemText,
        },
      ]);
      setUID(u

tring>('');
  const [items, setItems] = useState<Array<Item>>([
    {id: 1, isComplete: true, text: 'First'},
    {id: 2, isComplete: true, text: 'Second'},
    {id: 3, isComplete: false, text: 'Third'},
  ]);
  const [uid, setUI


 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
 */

import * as React from 'react';
import {memo, useCallback} from 'react';
import styles from './ListItem.css';

import type {Item} from './List';

type Props = {
  item: Item,
  removeItem: (item: Item) => void,
  toggleItem: (item: Item) => void,
};

function ListItem({item, removeItem, toggleItem}: Props) {
  co

     <button className={styles.IconButton} onClick={handleDelete}>
        🗑
      </button>
      <label className={styles.Label}>
        <input
          className={styles.Input}
          checked={item.isComplete}
          onChange={handleToggle}

nst handleDelete = useCallback(() => {
    removeItem(item);
  }, [item, removeItem]);

  const handleToggle = useCallback(() => {
    toggleItem(item);
  }, [item, toggleItem]);

  return (
    <li className={styles.ListItem}>


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {ReactContext} from 'shared/ReactTypes';
import * as React from 'react';
import {
  createContext,
  Component,
  forwardRef,
  Fragment,
  memo,
  useCallback,
  useDebugValue,
  useEffect,
  useReducer,
  useState,
} from 'react';

const initialData = {foo: 'FOO', bar: 'BAR'};

// $FlowFixMe[missing-local-annot]
function reducer(state, action: {type: string}) {
  switch (action.type) {
    cas

Count] = useState(0);
  const debouncedCount = useDebounce(count, 1000);
  const handleUpdateCountClick = useCallback(
    () => updateCount(count + 1),
    [count],
  );

  const [data, dispatch] = useReducer(reducer, initialData);
  const handleUpdateRed

e 'swap':
      return {foo: state.bar, bar: state.foo};
    default:
      throw new Error();
  }
}

type StatefulFunctionProps = {name: string};

function StatefulFunction({name}: StatefulFunctionProps) {
  const [count, update


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {Fragment, useDebugValue, useState} from 'react';

const div = document.createElement('div');
const exampleFunction = () => {};
const typedArray = new Uint8Array(3);
typedArray[0] = 1;
typedArray[1] = 2;
typedArray[2] = 3;

const arrayOfArrays = [
  [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['h', 'i', 'j'],
  ],
  [
    ['k', 'l', 'm'],
    ['n', 'o', 'p'],
    [

  },
  qux: {},
  quux: {
    k: undefined,
    l: null,
  },
};

function useOuterFoo() {
  useDebugValue({
    debugA: {
      debugB: {
        debugC: 'abc',
      },
    },
  });
  useState({
    valueA: {
      valueB: {
        valueC: 'abc',


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {useRef, useState} from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (

Count: {count}

      <button onClick={() => setCount(c => c + 1)}>Increment</button>

  );
};

function DialogComponent() {
  const dialogRef = useRef(null);

  const openDia

n: '10px 0'}}>
      <button onClick={openDialog}>Open Dialog</button>
      <dialog ref={dialogRef} style={{padding: '20px'}}>

Dialog Content

        <Counter />
        <button onClick={closeDialog}>Close</button>
      </dialog>
    </d

log = () => {
    if (dialogRef.current) {
      dialogRef.current.showModal();
    }
  };

  const closeDialog = () => {
    if (dialogRef.current) {
      dialogRef.current.close();
    }
  };

  return (
    <div style={{margi


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';

function deferred<T>(
  timeoutMS: number,
  resolvedValue: T,
  displayName: string,
): Promise<T> {
  const promise = new Promise<T>(resolve => {
    setTimeout(() => resolve(resolvedValue), timeoutMS);
  });
  (promise as any).displayName = displayName;

  return promise;
}

const title = deferred(100, 'Segmented Page Tit

tent}

  );
}

function InnerSegment({children}: {children: React.Node}): React.Node {
  return (
    <>

Inner Segment

      <React.Suspense name="InnerSegment" fallback={
Loading...
}>

{children}</sec

le', 'title');
const content = deferred(
  400,
  'This is the content of a segmented page. It loads in multiple parts.',
  'content',
);
function Page(): React.Node {
  return (

{title}

{con


 * 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
 */

import * as React from 'react';
import {useRef, useState} from 'react';

export default function App(): React.Node {
  return <List />;
}

function List() {
  const [items, setItems] = useState(['one', 'two', 'three']);
  const inputRef = useRef(null);

  const addItem = () => {
    const input = ((inputRef.cu

  <button data-testname="AddItemButton" onClick={addItem}>
        Add Item
      </button>
      <ul data-testname="List">
        {items.map((label, index) => (
          <ListItem key={index} label={label} />
        ))}
      </ul>
    </>
  );
}

// $

rrent: any): HTMLInputElement);
    const text = input.value;
    input.value = '';

    if (text) {
      setItems([...items, text]);
    }
  };

  return (
    <>
      <input ref={inputRef} data-testname="AddItemInput" />


ight (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
 */

import * as React from 'react';

export default function App(): React.Node {
  return <List />;
}

class List extends React.Component {
  constructor(props: any) {
    super(props);
    this.state = {
      items: ['one', 'two', 'three'],
    };
  }

  addItem = () => {
    if (this.inputRef && this.inputRef.value) {

={this.state.text}
          onChange={this.onInputChange}
          ref={c => (this.inputRef = c)}
        />
        <button data-testname="AddItemButton" onClick={this.addItem}>
          Add Item
        </button>
        <ul data-testname="List">

     this.setState({items: [...this.state.items, this.inputRef.value]});
      this.inputRef.value = '';
    }
  };

  render(): any {
    return (
      <div>
        <input
          data-testname="AddItemInput"
          value


eact';
import {createRoot} from 'react-dom/client';
import {
  activate as activateBackend,
  initialize as initializeBackend,
} from 'react-devtools-inline/backend';
import {initialize as createDevTools} from 'react-devtools-inline/frontend';

// This is a pretty gross hack to make the runtime loaded named-hooks-code work.
// TODO (Webpack 5) Hoepfully we can remove this once we upgrade to Webpack 5.
__webpack_public_path__ = '/dist/'; // eslint-disable-line no-undef

// TODO (Webpack 5) Hopefully we can r

teElement('script');
  script.src = sourcePath;

  ((contentDocument.body: any): HTMLBodyElement).appendChild(script);
}

function init(
  appSource: string,
  appIframe: HTMLIFrameElement,
  devtoolsContainer: HTMLElement,
  loadDevToolsButton: HTMLButton

emove this prop after the Webpack 5 migration.
function hookNamesModuleLoaderFunction() {
  return import('react-devtools-inline/hookNames');
}

function inject(contentDocument, sourcePath) {
  const script = contentDocument.crea


ight (c) Meta Platforms, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';

function generateArray(size: number) {
  return Array.from({length: size}, () => Math.floor(Math.random() * size));
}

const arr = generateArray(50000);

export default function LargeSubtree(): React.Node {
  const [showList, setShowList] = React.useState(false);
  const toggleList

nce.now();
      console.log(
        `Time spent on ${showList ? 'unmounting' : 'mounting'} the subtree: ${
          afterRenderTime - startTime
        }ms`,
      );
    });
  };
  return (

Mount/Unmount a large subtree

      <

= () => {
    const startTime = performance.now();
    setShowList(!showList);
    // requestAnimationFrame should happen after render+commit is done
    window.requestAnimationFrame(() => {
      const afterRenderTime = performa


 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.
 *
 * @noflow
 */

import * as React from 'react';
import * as ReactDOMClient from 'react-dom/client';
import {
  activate as activateBackend,
  initialize as initializeBackend,
} from 'react-devtools-inline/backend';
import {initialize as createDevTools} from 'react-devtools-inline/frontend';

// This is a pretty gross hack to make the runtime loa

after the Webpack 5 migration.
function hookNamesModuleLoaderFunction() {
  return import('react-devtools-inline/hookNames');
}

function inject(contentDocument, sourcePath, callback) {
  const script = contentDocument.createElement('script');
  script.onl

ded named-hooks-code work.
// TODO (Webpack 5) Hoepfully we can remove this once we upgrade to Webpack 5.
__webpack_public_path__ = '/dist/'; // eslint-disable-line no-undef

// TODO (Webpack 5) Hopefully we can remove this prop


import type {CommitDataFrontend} from './types';

import * as React from 'react';
import {useEffect, useMemo, useRef, useState} from 'react';
import AutoSizer from 'react-virtualized-auto-sizer';
import {FixedSizeList} from 'react-window';
import SnapshotCommitListItem from './SnapshotCommitListItem';
import {minBarWidth} from './constants';
import {formatDuration, formatTime} from './utils';
import Tooltip from './Tooltip';

import styles from './SnapshotCommitList.css';

export type ItemData = {
  commitT

mitIndex: (index: number) => void,
  startCommitDrag: (newDragState: DragState) => void,
  totalDurations: Array<number>,
};

type Props = {
  commitData: $ReadOnlyArray<CommitDataFrontend>,
  commitTimes: Array<number>,
  filteredCommitIndices: Array<numb

imes: Array<number>,
  filteredCommitIndices: Array<number>,
  maxDuration: number,
  selectedCommitIndex: number | null,
  selectedFilteredCommitIndex: number | null,
  selectCommitIndex: (index: number) => void,
  setHoveredCom


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {memo} from 'react';
import {areEqual} from 'react-window';
import {getGradientColor} from './utils';

import styles from './SnapshotCommitListItem.css';

import type {ItemData} from './SnapshotCommitList';

type Props = {
  data: ItemData,
  index: number,
  style: Object,
  ...
};

function SnapshotCommitListItem({da

dex = filteredCommitIndices[index];

  const totalDuration = totalDurations[index];

  // Use natural cbrt for bar height.
  // This prevents one (or a few) outliers from squishing the majority of other commits.
  // So rather than e.g. _█_ we get somethin

ta: itemData, index, style}: Props) {
  const {
    filteredCommitIndices,
    maxDuration,
    selectedCommitIndex,
    selectCommitIndex,
    setHoveredCommitIndex,
    startCommitDrag,
    totalDurations,
  } = itemData;

  in


ltip.css';
import typeof {SyntheticMouseEvent} from 'react-dom-bindings/src/events/SyntheticEvent';

const initialTooltipState = {height: 0, mouseX: 0, mouseY: 0, width: 0};

export default function Tooltip({
  children,
  className,
  label,
  style,
}: any): React.Node {
  const containerRef = useRef(null);
  const tooltipRef = useRef(null);

  // update the position of the tooltip based on current mouse position
  const updateTooltipPosition = (event: SyntheticMouseEvent) => {
    const element = tooltip

 {left, top} = getTooltipPosition(element, mousePosition);
      // update tooltip position
      element.style.left = left;
      element.style.top = top;
    }
  };

  const onMouseMove = (event: SyntheticMouseEvent) => {
    updateTooltipPosition(event)

Ref.current;
    if (element != null) {
      // first find the mouse position
      const mousePosition = getMousePosition(containerRef.current, event);
      // use the mouse position to find the position of tooltip
      const


ight (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
 */

import * as React from 'react';
import {Fragment, useCallback, useContext} from 'react';
import {ProfilerContext} from './ProfilerContext';

import styles from './RootSelector.css';

export default function RootSelector(_: {}): React.Node {
  const {profilingData, rootID, setRootID} = useContext(ProfilerContext);

  co

 );
    });
  }

  const handleChange = useCallback(
    ({currentTarget}: $FlowFixMe) => {
      setRootID(parseInt(currentTarget.value, 10));
    },
    [setRootID],
  );

  if (profilingData === null || profilingData.dataForRoots.size <= 1) {
    // Don

nst options = [];
  if (profilingData !== null) {
    profilingData.dataForRoots.forEach((dataForRoot, id) => {
      options.push(
        <option key={id} value={id}>
          {dataForRoot.displayName}
        </option>,


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {useContext} from 'react';

import {ProfilerContext} from './ProfilerContext';
import {StoreContext} from '../context';

import styles from './WhatChanged.css';
import HookChangeSummary from './HookChangeSummary';

type Props = {
  fiberID: number,
  displayMode?: 'detailed' | 'compact',
};

export default function WhatChanged({
  fiberID,
  displayMode = 'detailed',
}

ion filter update.
  // If the commit index is null, suspending for data below would throw an error.
  // TODO (ProfilerContext) This check should not be necessary.
  if (selectedCommitIndex === null) {
    return null;
  }

  const {changeDescriptions} =

: Props): React.Node {
  const {profilerStore} = useContext(StoreContext);
  const {rootID, selectedCommitIndex} = useContext(ProfilerContext);

  // TRICKY
  // Handle edge case where no commit is selected because of a min-durat


import {useCallback, useMemo, useState} from 'react';
import {useLocalStorage} from '../hooks';

import type {CommitDataFrontend} from './types';

export type CommitFilteringAndNavigation = {
  isCommitFilterEnabled: boolean,
  setIsCommitFilterEnabled: (value: boolean) => void,
  minCommitDuration: number,
  setMinCommitDuration: (value: number) => void,

  // Selection state
  selectedCommitIndex: number | null,
  selectCommitIndex: (value: number | null) => void,

  // Filtered data
  filteredCommitIndic

CommitDataFrontend>,
): CommitFilteringAndNavigation {
  // Filter settings persisted to localStorage
  const [isCommitFilterEnabled, setIsCommitFilterEnabledValue] =
    useLocalStorage<boolean>('React::DevTools::isCommitFilterEnabled', false);
  const [m

es: Array<number>,
  selectedFilteredCommitIndex: number | null,

  // Navigation
  selectNextCommitIndex: () => void,
  selectPrevCommitIndex: () => void,
};

export function useCommitFilteringAndNavigation(
  commitData: Array<


om 'react-devtools-shared/src/backend/types';
import type {
  ProfilingDataExport,
  ProfilingDataForRootExport,
  ProfilingDataForRootFrontend,
  ProfilingDataFrontend,
  SnapshotNode,
} from './types';
import type {
  TimelineData,
  TimelineDataExport,
} from 'react-devtools-timeline/src/types';

const commitGradient = [
  'var(--color-commit-gradient-0)',
  'var(--color-commit-gradient-1)',
  'var(--color-commit-gradient-2)',
  'var(--color-commit-gradient-3)',
  'var(--color-commit-gradient-4)',
  'var

erer interfaces (backend) into the format required by the Profiler UI.
// This format can then be quickly exported (and re-imported).
export function prepareProfilingDataFrontendFromBackendAndStore(
  dataBackends: Array<ProfilingDataBackend>,
  operations

(--color-commit-gradient-5)',
  'var(--color-commit-gradient-6)',
  'var(--color-commit-gradient-7)',
  'var(--color-commit-gradient-8)',
  'var(--color-commit-gradient-9)',
];

// Combines info from the Store (frontend) and rend


 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
 */

import * as React from 'react';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import styles from './shared.css';

type Props = {
  callStack: string | null,
  children: React$Node,
  componentStack: string | null,
  dismissError: Function | null,
  errorMessage: string | null,
};

export default function E

            Uncaught Error: {errorMessage || ''}

          {dismissError !== null && (
            <Button className={styles.CloseButton} onClick={di

rrorView({
  callStack,
  children,
  componentStack,
  dismissError = null,
  errorMessage,
}: Props): React.Node {
  return (

      {children}


 * 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
 */

import * as React from 'react';
import {findGitHubIssue} from './cache';
import UpdateExistingIssue from './UpdateExistingIssue';
import ReportNewIssue from './ReportNewIssue';
import WorkplaceGroup from './WorkplaceGroup';

type Props = {
  callStack: string | null,
  componentStack: string | null,
  errorMes

  let GitHubUI;
  if (maybeItem != null) {
    GitHubUI = <UpdateExistingIssue gitHubIssue={maybeItem} />;
  } else {
    GitHubUI = (
      <ReportNewIssue
        callStack={callStack}
        componentStack={componentStack}
        errorMessage={errorMe

sage: string | null,
};

export default function SuspendingErrorView({
  callStack,
  componentStack,
  errorMessage,
}: Props): React.Node {
  const maybeItem =
    errorMessage !== null ? findGitHubIssue(errorMessage) : null;


ight (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
 */

import * as React from 'react';
import styles from './shared.css';

type Props = {
  callStack: string | null,
  children: React$Node,
  componentStack: string | null,
  errorMessage: string | null,
};

export default function UnsupportedBridgeOperationView({
  callStack,
  children,
  componentStack,
  errorMessage,
}

{errorMessage || 'Bridge protocol mismatch'}

          An incompatible version of react-devtools-core has been
          embedded in a renderer like React Native.

: Props): React.Node {
  return (

      {children}


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {isInternalFacebookBuild} from 'react-devtools-feature-flags';
import {REACT_DEVTOOLS_WORKPLACE_URL} from 'react-devtools-shared/src/devtools/constants';
import Icon from '../Icon';
import styles from './shared.css';

export default function WorkplaceGroup(): React.Node {
  if (!isInternalFacebookBuild) {
    return null;
  }

  return (

  <Icon className={styles.ReportIcon} type="facebook" />
      <a
        className={styles.ReportLink}
        href={REACT_DEVTOOLS_WORKPLACE_URL}
        rel="noopener noreferrer"
        target="_blank">
        Report this on Workplace
      </a>


 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
 */

export type GitHubIssue = {
  title: string,
  url: string,
};

const GITHUB_ISSUES_API = 'https://api.github.com/search/issues';

export function searchGitHubIssuesURL(message: string): string {
  // Remove Fiber IDs from error message (as those will be unique).
  message = message.replace(/"[0-9]+"/g, '');

  c

sage) +
    '%20' +
    filters.map(encodeURIComponent).join('%20')
  );
}

export async function searchGitHubIssues(
  message: string,
): Promise<GitHubIssue | null> {
  const response = await fetch(searchGitHubIssuesURL(message));
  const data = await r

onst filters = [
    'in:title',
    'is:issue',
    'is:open',
    'is:public',
    'label:"Component: Developer Tools"',
    'repo:facebook/react',
  ];

  return (
    GITHUB_ISSUES_API +
    '?q=' +
    encodeURIComponent(mes


 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
 */

import * as React from 'react';
import {useImperativeHandle} from 'react';

import ContextMenu from './ContextMenu';
import useContextMenu from './useContextMenu';

import type {ContextMenuItem, ContextMenuRef} from './types';

type Props = {
  anchorElementRef: {
    current: React.ElementRef<any> | null,
  },

nst {shouldShow, position, hide} = useContextMenu(anchorElementRef);

  useImperativeHandle(
    ref,
    () => ({
      isShown() {
        return shouldShow;
      },
      hide,
    }),
    [shouldShow, hide],
  );

  if (!shouldShow) {
    return close

 items: ContextMenuItem[],
  closedMenuStub?: React.Node | null,
  ref?: ContextMenuRef,
};

export default function ContextMenuContainer({
  anchorElementRef,
  items,
  closedMenuStub = null,
  ref,
}: Props): React.Node {
  co


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {useState, useEffect, useCallback} from 'react';

import type {ContextMenuPosition} from './types';

type Payload = {
  shouldShow: boolean,
  position: ContextMenuPosition | null,
  hide: () => void,
};

export default function useContextMenu(anchorElementRef: {
  current: React.ElementRef<any> | null,
}): Payload {

);
  }, []);

  useEffect(() => {
    const anchor = anchorElementRef.current;
    if (anchor == null) return;

    function handleAnchorContextMenu(e: MouseEvent) {
      e.preventDefault();
      e.stopPropagation();

      const {pageX, pageY} = e;

 const [shouldShow, setShouldShow] = useState(false);
  const [position, setPosition] = React.useState<ContextMenuPosition | null>(
    null,
  );

  const hide = useCallback(() => {
    setShouldShow(false);
    setPosition(null


import * as React from 'react';
import is from 'shared/objectIs';

// Intentionally not using named imports because Rollup uses dynamic
// dispatch for CommonJS interop named imports.
const {useState, useEffect, useLayoutEffect, useDebugValue} = React;

let didWarnOld18Alpha = false;
let didWarnUncachedGetSnapshot = false;

// Disclaimer: This shim breaks many of the rules of React, and only works
// because of a very particular set of implementation details and assumptions
// -- change any one of them and

 this shim when the built-in API
// does not exist.
//
// Do not assume that the clever hacks used by this hook also work in general.
// The point of this shim is to replace the need for hacks by other libraries.
export function useSyncExternalStore<T>(

it will break. The most important assumption
// is that updates are always synchronous, because concurrent rendering is
// only available in versions of React that also have a built-in
// useSyncExternalStore API. And we only use


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 *
 * @jest-environment node
 */

'use strict';

let React;
let ReactNoop;
let Scheduler;
let useSyncExternalStore;
let useSyncExternalStoreWithSelector;
let act;
let assertLog;

// This tests the userspace shim of `useSyncExternalStore` in a server-rendering
// (Node) environment
describe('useSyncExternalStore (userspace shim, server rendering)', () => {
  beforeEach(() => {
    jest.resetModules()

.
    //
    // Longer term, we'll probably test this branch using an actual build of
    // React 17.
    jest.mock('react', () => {
      const {
        startTransition: _,
        useSyncExternalStore: __,
        ...otherExports
      } = jest.require

;

    // Remove useSyncExternalStore from the React imports so that we use the
    // shim instead. Also removing startTransition, since we use that to detect
    // outdated 18 alphas that don't yet include useSyncExternalStore


import * as React from 'react';
import {Fragment, useContext} from 'react';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import {ProfilerContext} from './ProfilerContext';
import SnapshotCommitList from './SnapshotCommitList';
import {maxBarWidth} from './constants';
import {StoreContext} from '../context';

import styles from './SnapshotSelector.css';

export type Props = {};

export default function SnapshotSelector(_: Props): React.Node {
  const {
    rootID,
    selectedCommi

t);
  const {commitData} = profilerStore.getDataForRoot(((rootID: any): number));

  const totalDurations: Array<number> = [];
  const commitTimes: Array<number> = [];
  commitData.forEach(commitDatum => {
    totalDurations.push(
      commitDatum.duratio

tIndex,
    selectCommitIndex,
    selectPrevCommitIndex,
    selectNextCommitIndex,
    filteredCommitIndices,
    selectedFilteredCommitIndex,
  } = useContext(ProfilerContext);

  const {profilerStore} = useContext(StoreContex


 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
 */

import type {CommitTree} from './types';
import type {SerializedElement} from 'react-devtools-shared/src/frontend/types';

import * as React from 'react';
import {useContext} from 'react';
import {ProfilerContext} from './ProfilerContext';
import styles from './Updaters.css';
import {ElementTypeRoot} from '../../../frontend/types';

st children =
    updaters.length > 0 ? (
      updaters.map((serializedElement: SerializedElement): React$Node => {
        const {displayName, id, key, type} = serializedElement;
        const isVisibleInTree =
          commitTree.nodes.has(id) && type

export type Props = {
  commitTree: CommitTree,
  updaters: Array<SerializedElement>,
};

export default function Updaters({commitTree, updaters}: Props): React.Node {
  const {selectFiber} = useContext(ProfilerContext);

  con


**
 * 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
 */

import * as React from 'react';
import styles from './shared.css';

type Props = {
  callStack: string | null,
  children: React$Node,
  info: React$Node | null,
  componentStack: string | null,
  errorMessage: string,
};

export default function CaughtErrorView({
  callStack,
  children,
  info,
  component

tyles.ErrorHeader}>{errorMessage}

        {!!info &&
{info}
}
        {!!callStack && (

            The error was thrown {callStack.trim()}
          </

Stack,
  errorMessage,
}: Props): React.Node {
  return (

      {children}

          <div className={s


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import Icon from '../Icon';
import {searchGitHubIssuesURL} from './githubAPI';
import styles from './shared.css';

const LABELS = [
  'Component: Developer Tools',
  'Type: Bug',
  'Status: Unconfirmed',
];

// This must match the filename in ".github/ISSUE_TEMPLATE/"
const TEMPLATE = 'devtools_bug_report.yml';

type Props =

ess.env.GITHUB_URL;
  if (!bugURL) {
    return null;
  }

  const gitHubAPISearch =
    errorMessage !== null ? searchGitHubIssuesURL(errorMessage) : '(none)';

  const title = `[DevTools Bug] ${errorMessage || ''}`;

  const parameters = [
    `template=

{
  callStack: string | null,
  componentStack: string | null,
  errorMessage: string | null,
};

export default function ReportNewIssue({
  callStack,
  componentStack,
  errorMessage,
}: Props): React.Node {
  let bugURL = proc


, 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
 */

import type {GitHubIssue} from './githubAPI';

import * as React from 'react';
import Icon from '../Icon';
import styles from './shared.css';

export default function UpdateExistingIssue({
  gitHubIssue,
}: {
  gitHubIssue: GitHubIssue,
}): React.Node {
  const {title, url} = gitHubIssue;
  return (
    <div className={styles.GitHubLinkRow}>

" />
      <div className={styles.UpdateExistingIssuePrompt}>
        Update existing issue:
      </div>
      <a
        className={styles.ReportLink}
        href={url}
        rel="noopener noreferrer"
        target="_blank"
        title="Report bug"


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {
  Thenable,
  FulfilledThenable,
  RejectedThenable,
} from 'shared/ReactTypes';
import type {GitHubIssue} from './githubAPI';

import * as React from 'react';

import {unstable_getCacheForType as getCacheForType} from 'react';
import {searchGitHubIssues} from './githubAPI';

const API_TIMEOUT = 3000;
function readRecord<T>(record: Thenable<T>): T | null {
  if (typeof React.use === 'function'

tus === 'fulfilled') {
    return record.value;
  } else if (record.status === 'rejected') {
    return null;
  } else {
    throw record;
  }
}

type GitHubIssueMap = Map<string, Thenable<GitHubIssue>>;

function createMap(): GitHubIssueMap {
  return new

) {
    try {
      // eslint-disable-next-line react-hooks-published/rules-of-hooks
      return React.use(record);
    } catch (x) {
      if (x === null) {
        return null;
      }
      throw x;
    }
  }
  if (record.sta


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import is from 'shared/objectIs';
import {useSyncExternalStore} from 'use-sync-external-store/src/useSyncExternalStore';

// Intentionally not using named imports because Rollup uses dynamic dispatch
// for CommonJS interop.
const {useRef, useEffect, useMemo, useDebugValue} = React;

// Same as useSyncExternalStore, but supports selector and isEqual arguments.
export function

 isEqual?: (a: Selection, b: Selection) => boolean,
): Selection {
  type Inst =
    | {
        hasValue: true,
        value: Selection,
      }
    | {
        hasValue: false,
        value: null,
      };

  // Use this to track the rendered snapshot.

 useSyncExternalStoreWithSelector<Snapshot, Selection>(
  subscribe: (() => void) => () => void,
  getSnapshot: () => Snapshot,
  getServerSnapshot: void | null | (() => Snapshot),
  selector: (snapshot: Snapshot) => Selection,


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {Fragment, useContext, useEffect, useRef} from 'react';

import WhatChanged from './WhatChanged';
import {ProfilerContext} from './ProfilerContext';
import {formatDuration, formatTime} from './utils';
import {StoreContext} from '../context';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import InspectedElementBadges from '../Components/Inspect

ndex,
    selectedCommitIndex,
    selectedFiberID,
    selectedFiberName,
    selectFiber,
  } = useContext(ProfilerContext);
  const {profilingCache} = profilerStore;
  const selectedListItemRef = useRef<HTMLElement | null>(null);

  useEffect(() => {

edElementBadges';

import styles from './SidebarSelectedFiberInfo.css';

export default function SidebarSelectedFiberInfo(): React.Node {
  const {profilerStore} = useContext(StoreContext);
  const {
    rootID,
    selectCommitI


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {Fragment, useContext} from 'react';
import {ProfilerContext} from './ProfilerContext';
import Updaters from './Updaters';
import {formatDuration, formatTime} from './utils';
import {StoreContext} from '../context';
import {getCommitTree} from './CommitTreeBuilder';

import styles from './SidebarCommitInfo.css';

export type Props = {};

export default function Sidebar

v className={styles.NothingSelected}>Nothing selected</div>;
  }

  const {
    duration,
    effectDuration,
    passiveEffectDuration,
    priorityLevel,
    timestamp,
    updaters,
  } = profilerStore.getCommitData(rootID, selectedCommitIndex);

  cons

CommitInfo(_: Props): React.Node {
  const {selectedCommitIndex, rootID} = useContext(ProfilerContext);

  const {profilerStore} = useContext(StoreContext);

  if (rootID === null || selectedCommitIndex === null) {
    return <di


ight (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
 */

import * as React from 'react';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import styles from './shared.css';

type Props = {
  callStack: string | null,
  children: React$Node,
  componentStack: string | null,
  dismissError: Function,
  errorMessage: string | null,
};

export default func

rInfo}>

            {errorMessage || 'Timed out waiting'}

          <Button className={styles.CloseButton} onClick={dismissError}>
            Retr

tion TimeoutView({
  callStack,
  children,
  componentStack,
  dismissError = null,
  errorMessage,
}: Props): React.Node {
  return (

      {children}
      <div className={styles.Erro


 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
 */

'use strict';

// Intentionally not using named imports because Rollup uses dynamic
// dispatch for CommonJS interop named imports.
import * as React from 'react';

export const useSyncExternalStore = React.useSyncExternalStore;

if (__DEV__) {
  // Avoid transforming the `console.error` call as it would cause th

oes is re-export useSyncExternalStore from the 'react' package, so " +
      'it only works with React 18+.' +
      '\n\n' +
      'If you wish to support React 16 and 17, import from ' +
      "'use-sync-external-store/shim' instead. It will fall back to

e built artifact
  // to access React internals, which exist under different paths depending on the
  // React version.
  console['error'](
    "The main 'use-sync-external-store' entry point is not supported; all it " +
      "d


import type {
  ElementType,
  SerializedElement,
} from 'react-devtools-shared/src/frontend/types';
import type {
  TimelineData,
  TimelineDataExport,
} from 'react-devtools-timeline/src/types';

export type CommitTreeNode = {
  id: number,
  children: Array<number>,
  displayName: string | null,
  hocDisplayNames: Array<string> | null,
  key: number | string | null,
  parentID: number,
  treeBaseDuration: number,
  type: ElementType,
  // If component is compiled with Forget, the backend will send its na

SnapshotNode = {
  id: number,
  children: Array<number>,
  displayName: string | null,
  hocDisplayNames: Array<string> | null,
  key: number | string | null,
  type: ElementType,
  // If component is compiled with Forget, the backend will send its name a

me as Forget(...)
  // Later, on the frontend side, we will strip HOC names and Forget prefix.
  compiledWithForget: boolean,
};

export type CommitTree = {
  nodes: Map<number, CommitTreeNode>,
  rootID: number,
};

export type


import * as React from 'react';
import {Component, Suspense} from 'react';
import Store from 'react-devtools-shared/src/devtools/store';
import UnsupportedBridgeOperationView from './UnsupportedBridgeOperationView';
import ErrorView from './ErrorView';
import SearchingGitHubIssues from './SearchingGitHubIssues';
import SuspendingErrorView from './SuspendingErrorView';
import TimeoutView from './TimeoutView';
import CaughtErrorView from './CaughtErrorView';
import UnsupportedBridgeOperationError from 'react-

ct-devtools-shared/src/errors/UnknownHookError';
import {logEvent} from 'react-devtools-shared/src/Logger';

type Props = {
  children: React$Node,
  canDismiss?: boolean,
  onBeforeDismissCallback?: () => void,
  store?: Store,
};

type State = {
  callSt

devtools-shared/src/UnsupportedBridgeOperationError';
import TimeoutError from 'react-devtools-shared/src/errors/TimeoutError';
import UserError from 'react-devtools-shared/src/errors/UserError';
import UnknownHookError from 'rea


ate;
    useEffect = React.useEffect;
    useLayoutEffect = React.useLayoutEffect;
    const InternalTestUtils = require('internal-test-utils');
    assertLog = InternalTestUtils.assertLog;
    assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
    const internalAct = require('internal-test-utils').act;

    // The internal act implementation doesn't batch updates by default, since
    // it's mostly used to test concurrent mode. But since these tests run
    // in both concurrent and legacy m

-store` entrypoint. In the compiled artifacts, this
      // is resolved to the `shim` implementation by our build config, but when
      // running the tests against the source files, we need to tell Jest how to
      // resolve it. Because this is a sour

ode, I'm adding batching here.
    act = cb => internalAct(() => ReactDOM.unstable_batchedUpdates(cb));
    if (gate(flags => flags.source)) {
      // The `shim/with-selector` module composes the main
      // `use-sync-external


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {useLayoutEffect} from 'react';
import {createPortal} from 'react-dom';

import ContextMenuItem from './ContextMenuItem';

import type {
  ContextMenuItem as ContextMenuItemType,
  ContextMenuPosition,
} from './types';

import styles from './ContextMenu.css';

function repositionToFit(element: HTMLElement, x: number, y: number) {
  const ownerWindow = element.ownerDoc

}
  } else {
    element.style.top = `${y}px`;
  }

  if (x + element.offsetWidth >= ownerWindow.innerWidth) {
    if (x - element.offsetWidth > 0) {
      element.style.left = `${x - element.offsetWidth}px`;
    } else {
      element.style.left = '0px';

ument.defaultView;
  if (y + element.offsetHeight >= ownerWindow.innerHeight) {
    if (y - element.offsetHeight > 0) {
      element.style.top = `${y - element.offsetHeight}px`;
    } else {
      element.style.top = '0px';


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

jest.mock('react-dom-bindings/src/events/isEventSupported');

describe('InvalidEventListeners', () => {
  let React;
  let ReactDOMClient;
  let act;
  let assertConsoleErrorDev;
  let container;

  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    ({ac

iner = null;
  });

  it('should prevent non-function listeners, at dispatch', async () => {
    const root = ReactDOMClient.createRoot(container);
    await act(() => {
      root.render(<div onClick="not a function" />);
    });
    assertConsoleErrorDev

t, assertConsoleErrorDev} = require('internal-test-utils'));

    container = document.createElement('div');
    document.body.appendChild(container);
  });

  afterEach(() => {
    document.body.removeChild(container);
    conta


 recordID(id);
  event.stopPropagation();
};
const recordIDAndReturnFalse = function (id, event) {
  recordID(id);
  return false;
};
const LISTENER = jest.fn();
const ON_CLICK_KEY = 'onClick';

let GRANDPARENT;
let PARENT;
let CHILD;
let BUTTON;

let renderTree;
let putListener;
let deleteAllListeners;

let container;

// This test is written in a bizarre way because it was previously using internals.
// It should probably be rewritten but we're keeping it for some extra coverage.
describe('ReactBrowserEve

ner = document.createElement('div');
    document.body.appendChild(container);

    let GRANDPARENT_PROPS = {};
    let PARENT_PROPS = {};
    let CHILD_PROPS = {};
    let BUTTON_PROPS = {};

    function Child(props) {
      return <div ref={c => (CHILD

ntEmitter', () => {
  beforeEach(() => {
    jest.resetModules();
    LISTENER.mockClear();

    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
    contai


=> {
    jest.resetModules();
    act = require('internal-test-utils').act;
    React = require('react');
    ReactDOM = require('react-dom');

    const InternalTestUtils = require('internal-test-utils');
    waitForThrow = InternalTestUtils.waitForThrow;

    ErrorBoundary = class extends React.Component {
      state = {error: null};
      static getDerivedStateFromError(error) {
        return {error};
      }
      render() {
        if (this.state.error) {
          return <h1>Caught: {this.state.erro

   windowOnError = jest.fn();
    window.addEventListener('error', windowOnError);
    spyOnDevAndProd(console, 'error');
    spyOnDevAndProd(console, 'warn');
  });

  afterEach(() => {
    document.body.removeChild(container);
    window.removeEventListe

r.message}
;
        }
        return this.props.children;
      }
    };
    NoError = function () {
      return
OK
;
    };
    container = document.createElement('div');
    document.body.appendChild(container);


');
        nativeEvent.initEvent('mouseout', true, true);
        childNode.dispatchEvent(nativeEvent);

        expect(mouseOut).toHaveBeenCalledTimes(2);
        expect(mouseOut).toHaveBeenNthCalledWith(1, childNode);
        expect(mouseOut).toHaveBeenNthCalledWith(2, parentNode);
      } finally {
        document.body.removeChild(parentContainer);
      }
    });

    it('should propagate events two levels down', async () => {
      const mouseOut = jest.fn();
      const onMouseOut = event => mouseOu

dRoot = ReactDOMClient.createRoot(childContainer);
      const parentRoot = ReactDOMClient.createRoot(parentContainer);
      const grandParentRoot = ReactDOMClient.createRoot(grandParentContainer);

      await act(() => {
        childRoot.render(<div on

t(event.currentTarget);

      const childContainer = document.createElement('div');
      const parentContainer = document.createElement('div');
      const grandParentContainer = document.createElement('div');

      const chil


,
        nativeEvent: 'focusout',
        dispatch(node) {
          const e = new Event('focusout', {
            bubbles: true,
            cancelable: true,
          });
          node.dispatchEvent(e);
        },
      });
    });

    // This test will fail in legacy mode (only used in WWW)
    // because we emulate the React 16 behavior where
    // the click handler is attached to the document.
    // @gate !enableLegacyFBSupport
    it('onClick', async () => {
      await testNativeBubblingEvent({

> {
      await testNativeBubblingEvent({
        type: 'div',
        reactEvent: 'onContextMenu',
        reactEventType: 'contextmenu',
        nativeEvent: 'contextmenu',
        dispatch(node) {
          node.dispatchEvent(
            new MouseEvent

        type: 'div',
        reactEvent: 'onClick',
        reactEventType: 'click',
        nativeEvent: 'click',
        dispatch(node) {
          node.click();
        },
      });
    });

    it('onContextMenu', async () =


('should render numbers as children', async () => {
    const Box = ({value}) =>
{value}
;

    await act(async () => {
      root.render(<Box value={10} />);
    });

    expect(container.textContent).toEqual('10');
  });

  it('should render bigints as children', async () => {
    const Box = ({value}) =>
{value}
;

    await act(async () => {
      root.render(<Box value={10n} />);
    });

    expect(container.textContent).toEqual('10');
  });

  it('should call an effect after mount

 act(async () => {
      root.render(<Component />);
    });
    assertLog(['Callback']);

    // updating phase
    await act(async () => {
      root.render(<Component />);
    });
    assertLog(['Callback']);
  });

  it('should call an effect when the

/update (replacing render callback pattern)', async () => {
    function Component() {
      React.useEffect(() => {
        Scheduler.log('Callback');
      });
      return
Foo
;
    }

    // mounting phase
    await


rDev =
      require('internal-test-utils').assertConsoleErrorDev;
    Scheduler = require('scheduler');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
    waitFor = InternalTestUtils.waitFor;
    waitForMicrotasks = InternalTestUtils.waitForMicrotasks;
    assertLog = InternalTestUtils.assertLog;

    document.body.appendChild(container);
    window.event = undefined;
  });

  afterEach(() => {
    document.body.removeChild(container);
  });

nder(
Bye
, container, () => {
      ops.push(container.textContent);
    });
    expect(ops).toEqual(['Hi', 'Bye']);
  });

  it('flushSync batches sync updates and flushes them at the end of the batch', async () => {
    const ops = [];
    let

// @gate !disableLegacyMode
  it('renders synchronously by default in legacy mode', () => {
    const ops = [];
    ReactDOM.render(
Hi
, container, () => {
      ops.push(container.textContent);
    });
    ReactDOM.re


ct-core
 */

'use strict';

import {
  insertNodesAndExecuteScripts,
  getVisibleChildren,
} from '../test-utils/FizzTestUtils';
import {patchMessageChannel} from '../../../../scripts/jest/patchMessageChannel';

// Polyfills for test environment
global.ReadableStream =
  require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;

let act;
let serverAct;
let assertLog;
let waitForPaint;
let container;
let React;
let Scheduler;
let ReactDOMServer;
let ReactD

tils').act;
    serverAct = require('internal-test-utils').serverAct;
    React = require('react');
    ReactDOMServer = require('react-dom/server.browser');
    ReactDOMClient = require('react-dom/client');
    useDeferredValue = React.useDeferredValue;

OMClient;
let useDeferredValue;
let Suspense;

describe('ReactDOMFizzForm', () => {
  beforeEach(() => {
    jest.resetModules();
    Scheduler = require('scheduler');
    patchMessageChannel();
    act = require('internal-test-u


esetModules();
    patchMessageChannel();
    React = require('react');
    ReactDOMServer = require('react-dom/server.browser');
    ReactDOMClient = require('react-dom/client');
    Suspense = React.Suspense;
    useFormStatus = require('react-dom').useFormStatus;
    useOptimistic = require('react').useOptimistic;
    act = require('internal-test-utils').act;
    serverAct = require('internal-test-utils').serverAct;
    assertConsoleErrorDev =
      require('internal-test-utils').assertConsoleErrorDev;

  // useActionState = require('react-dom').useFormState;
    // }
    useActionState = require('react').useActionState;
  });

  afterEach(() => {
    document.body.removeChild(container);
  });

  function submit(submitter) {
    const form = submitter.fo

   container = document.createElement('div');
    document.body.appendChild(container);
    // TODO: Test the old api but it warns so needs warnings to be asserted.
    // if (__VARIANT__) {
    // Remove after API is deleted.


   resolveA = r;
      });
    });

    let resolveB;
    const LazyB = React.lazy(() => {
      return new Promise(r => {
        resolveB = r;
      });
    });

    class TextWithPunctuation extends React.Component {
      render() {
        return <Text text={this.props.text + this.props.punctuation} />;
      }
    }

    // This tests that default props of the inner element is resolved.
    TextWithPunctuation.defaultProps = {
      punctuation: '!',
    };

    await act(() => {
      const {pipe} =

e fallback={<Text text="Loading..." />}>
              <LazyB text="world" />
            </Suspense>

,
      );
      pipe(writable);
    });

    expect(getVisibleChildren(container)).toEqual(

Loadi

renderToPipeableStream(

            <Suspense fallback={<Text text="Loading..." />}>
              <LazyA text="Hello" />
            </Suspense>

            <Suspens


');
    Suspense = React.Suspense;
  });

  const theError = new Error('This is an error');
  function Throw() {
    throw theError;
  }
  const theInfinitePromise = new Promise(() => {});
  function InfiniteSuspend() {
    throw theInfinitePromise;
  }

  async function readResult(stream) {
    const reader = stream.getReader();
    let result = '';
    while (true) {
      const {done, value} = await reader.read();
      if (done) {
        return result;
      }
      result += Buffer.from(value).toStrin

Result(stream);
    expect(result).toMatchInlineSnapshot(`"<div>hello world</div>"`);
  });

  it('should emit DOCTYPE at the root of the document', async () => {
    const stream = await serverAct(() =>
      ReactDOMFizzServer.renderToReadableStream(

g('utf8');
    }
  }

  it('should call renderToReadableStream', async () => {
    const stream = await serverAct(() =>
      ReactDOMFizzServer.renderToReadableStream(
hello world
),
    );
    const result = await read


ct-core
 */

'use strict';

// Polyfills for test environment
global.ReadableStream =
  require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;
global.AsyncLocalStorage = require('async_hooks').AsyncLocalStorage;

let React;
let ReactDOM;
let ReactDOMFizzServer;
let Suspense;

describe('ReactDOMFizzServerEdge', () => {
  beforeEach(() => {
    jest.resetModules();
    jest.useRealTimers();
    React = require('react');
    Suspense = React.Suspense;

{done, value} = await reader.read();
      if (done) {
        return result;
      }
      result += Buffer.from(value).toString('utf8');
    }
  }

  // https://github.com/facebook/react/issues/27540
  it('does not try to write to the stream after it has

 ReactDOM = require('react-dom');
    ReactDOMFizzServer = require('react-dom/server.edge');
  });

  async function readResult(stream) {
    const reader = stream.getReader();
    let result = '';
    while (true) {
      const


   output.result += chunk;
    });
    writable.on('error', error => {
      output.error = error;
    });
    const completed = new Promise(resolve => {
      writable.on('finish', () => {
        resolve();
      });
      writable.on('error', () => {
        resolve();
      });
    });
    return {writable, completed, output};
  }

  const theError = new Error('This is an error');
  function Throw() {
    throw theError;
  }
  const theInfinitePromise = new Promise(() => {});
  function InfiniteSuspend(

       return content;
      }
      content += Buffer.from(value).toString('utf8');
    }
  }

  it('should call renderToPipeableStream', async () => {
    const {writable, output} = getTestWritable();
    await act(() => {
      const {pipe} = ReactDOMFi

) {
    throw theInfinitePromise;
  }

  async function readContentWeb(stream) {
    const reader = stream.getReader();
    let content = '';
    while (true) {
      const {done, value} = await reader.read();
      if (done) {


Act = require('internal-test-utils').act;
    ReactDOMFizzServer = require('react-dom/server');
    Stream = require('stream');

    const InternalTestUtils = require('internal-test-utils');
    assertLog = InternalTestUtils.assertLog;

    startTransition = React.startTransition;

    textCache = new Map();

    // Test Environment
    const jsdom = new JSDOM(
      '<!DOCTYPE html>
',
      {
        runScripts: 'dangerously',
      },
    );
    document = jsdo

   buffer += chunk;
    });
    writable.on('error', error => {
      hasErrored = true;
      fatalError = error;
    });
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  async function serverAct(callback) {
    await callback();
    // Awa

m.window.document;
    container = document.getElementById('container');

    buffer = '';
    hasErrored = false;

    writable = new Stream.PassThrough();
    writable.setEncoding('utf8');
    writable.on('data', chunk => {


;
let textCache;
let document;
let writable;
let container;
let buffer = '';
let hasErrored = false;
let fatalError = undefined;

describe('ReactDOMFizzStatic', () => {
  beforeEach(() => {
    jest.resetModules();
    JSDOM = require('jsdom').JSDOM;
    React = require('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    ReactDOMFizzStatic = require('react-dom/static');
    Stream = require('stream');
    Suspense = React.Suspense;

    textCache = new Map();

tainer = document.getElementById('container');

    buffer = '';
    hasErrored = false;

    writable = new Stream.PassThrough();
    writable.setEncoding('utf8');
    writable.on('data', chunk => {
      buffer += chunk;
    });
    writable.on('error',

// Test Environment
    const jsdom = new JSDOM(
      '<!DOCTYPE html>
',
      {
        runScripts: 'dangerously',
      },
    );
    document = jsdom.window.document;
    con


ontainer;
let serverAct;

describe('ReactDOMFizzStaticBrowser', () => {
  beforeEach(() => {
    jest.resetModules();
    JSDOM = require('jsdom').JSDOM;

    // We need the mocked version of setTimeout inside the document.
    window.setTimeout = setTimeout;
    window.requestAnimationFrame = setTimeout;

    patchMessageChannel();
    serverAct = require('internal-test-utils').serverAct;

    React = require('react');
    ReactDOMFizzServer = require('react-dom/server.browser');
    ReactDOMFizzStatic = r

{
    if (typeof global.window.__restoreGlobalScope === 'function') {
      global.window.__restoreGlobalScope();
    }
    document.body.removeChild(container);
  });

  const theError = new Error('This is an error');
  function Throw() {
    throw theErr

equire('react-dom/static.browser');
    Suspense = React.Suspense;
    SuspenseList = React.unstable_SuspenseList;
    container = document.createElement('div');
    document.body.appendChild(container);
  });

  afterEach(() =>


require('react');
    ReactDOMFizzStatic = require('react-dom/static');
    Suspense = React.Suspense;
  });

  const theError = new Error('This is an error');
  function Throw() {
    throw theError;
  }
  const theInfinitePromise = new Promise(() => {});
  function InfiniteSuspend() {
    throw theInfinitePromise;
  }

  function readContent(readable) {
    return new Promise((resolve, reject) => {
      let content = '';
      readable.on('data', chunk => {
        content += Buffer.from(chunk).toString(

r();
    let content = '';
    while (true) {
      const {done, value} = await reader.read();
      if (done) {
        return content;
      }
      content += Buffer.from(value).toString('utf8');
    }
  }

  it('should call prerenderToNodeStream', asyn

'utf8');
      });
      readable.on('error', error => {
        reject(error);
      });
      readable.on('end', () => resolve(content));
    });
  }

  async function readContentWeb(stream) {
    const reader = stream.getReade


es();
    JSDOM = require('jsdom').JSDOM;
    Scheduler = require('scheduler');
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    ReactDOMFizzServer = require('react-dom/server');
    Stream = require('stream');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;

    // Test Environment
    const jsdom = new JSDOM(
      '<!DOCTYPE html>
',
      {
        runScripts: 'dan

utf8');
    writable.on('data', chunk => {
      buffer += chunk;
    });
    writable.on('error', error => {
      hasErrored = true;
      fatalError = error;
    });
  });

  async function act(callback) {
    await callback();
    // Await one turn aro

gerously',
      },
    );
    document = jsdom.window.document;
    container = document.getElementById('container');

    buffer = '';
    hasErrored = false;

    writable = new Stream.PassThrough();
    writable.setEncoding('


);
    assertLog = require('internal-test-utils').assertLog;
    ReactDOMFizzServer = require('react-dom/server');
    Stream = require('stream');

    Suspense = React.Suspense;
    SuspenseList = React.unstable_SuspenseList;

    Scheduler = require('scheduler');

    // Test Environment
    const jsdom = new JSDOM(
      '<!DOCTYPE html>
',
      {
        runScripts: 'dangerously',
      },
    );
    document = jsdom.window.document;
    container = document.

      setTimeout(cb);

    buffer = '';
    hasErrored = false;
    hasCompleted = false;

    writable = new Stream.PassThrough();
    writable.setEncoding('utf8');
    writable.on('data', chunk => {
      buffer += chunk;
    });
    writable.on('error'

getElementById('container');
    global.window = jsdom.window;
    // The Fizz runtime assumes requestAnimationFrame exists so we need to polyfill it.
    global.requestAnimationFrame = global.window.requestAnimationFrame = cb =>


ct-core
 * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
 */

'use strict';
import {
  insertNodesAndExecuteScripts,
  getVisibleChildren,
} from '../test-utils/FizzTestUtils';

let JSDOM;
let React;
let Suspense;
let ViewTransition;
let ReactDOMClient;
let clientAct;
let ReactDOMFizzServer;
let Stream;
let document;
let writable;
let container;
let buffer = '';
let hasErrored = false;
let fatalError = undefined;

describe('ReactDOMFizzViewTransition', () => {
  beforeEach(() => {

t-dom/server');
    Stream = require('stream');

    Suspense = React.Suspense;
    ViewTransition = React.ViewTransition;

    // Test Environment
    const jsdom = new JSDOM(
      '<!DOCTYPE html>
',
      {

  jest.resetModules();
    JSDOM = require('jsdom').JSDOM;
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    clientAct = require('internal-test-utils').act;
    ReactDOMFizzServer = require('reac


' + href);
    });
  }

  function resolveLoadables(hrefs, nodes, event, onLoad) {
    const hrefSet = hrefs ? new Set(hrefs) : null;
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i];
      if (loadCache.has(node)) {
        continue;
      }
      const href = node.getAttribute('href');
      if (!hrefSet || hrefSet.has(href)) {
        loadCache.add(node);
        onLoad(href);
        node.dispatchEvent(event);
      }
    }
  }

  it('can render resources before singletons', asyn

o world</body>
        </html>
      </>,
    );
    try {
      await waitForAll([]);
    } catch (e) {
      // for DOMExceptions that happen when expecting this test to fail we need
      // to clear the scheduler first otherwise the expected failure wi

c () => {
    const root = ReactDOMClient.createRoot(document);
    root.render(
      <>
        <title>foo</title>
        <html>
          <head>
            <link rel="foo" href="foo" />
          </head>
          <body>hell


{
      Scheduler.log(`Suspend! [${text}]`);
      const thenable = {
        pings: [],
        then(resolve) {
          if (newRecord.status === 'pending') {
            thenable.pings.push(resolve);
          } else {
            Promise.resolve().then(() => resolve(newRecord.value));
          }
        },
      };

      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.set(text, newRecord);

      throw thenable;
    }
  }

  function getText(text) {

        } else {
            Promise.resolve().then(() => resolve(newRecord.value));
          }
        },
      };
      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.set(text, newRecord);
      return t

 const record = textCache.get(text);
    if (record === undefined) {
      const thenable = {
        pings: [],
        then(resolve) {
          if (newRecord.status === 'pending') {
            thenable.pings.push(resolve);


ef={fragmentRef}>

A

B

          </Fragment>

C

          {show &&
D
}
        </Fragment>
      );
    }

    const root = ReactDOMClient.createRoot(container);
    await act(() => root.render(<Test show={false} />));

    const childA = document.querySelector('#childA');
    const childB = document.querySelector('#childB');
    const childC = document.querySelector('#childC');

    ex

ctFragments.has(fragmentParentRef.current)).toBe(true);
    expect(childB.reactFragments.has(fragmentParentRef.current)).toBe(true);
    expect(childC.reactFragments.has(fragmentParentRef.current)).toBe(true);

    await act(() => root.render(<Test show={t

pect(childA.reactFragments.has(fragmentRef.current)).toBe(true);
    expect(childB.reactFragments.has(fragmentRef.current)).toBe(true);
    expect(childC.reactFragments.has(fragmentRef.current)).toBe(false);
    expect(childA.rea


ct-core
 */

'use strict';

let React;
let ReactDOM;
let ReactDOMClient;
let act;
let waitForAll;

describe('ReactDOMHooks', () => {
  let container;

  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
    waitForAll = require('internal-test-utils').waitForAll;

    container = document.createElement('div');
    document.body.appendChild(container);

ontainer3 = document.createElement('div');

    function Example1({n}) {
      React.useEffect(() => {
        ReactDOM.render(<Example2 n={n} />, container2);
      });
      return 1 * n;
    }

    function Example2({n}) {
      React.useEffect(() => {

 });

  afterEach(() => {
    document.body.removeChild(container);
  });

  // @gate !disableLegacyMode
  it('can ReactDOM.render() from useEffect', async () => {
    const container2 = document.createElement('div');
    const c


MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
 */

'use strict';

let JSDOM;
let React;
let ReactDOMClient;
let container;
let waitForAll;

describe('ReactDOM HostSingleton', () => {
  beforeEach(() => {
    jest.resetModules();
    JSDOM = require('jsdom').JSDOM;
    // Test Environment
    const jsdom = new JSDOM(
      '<!DOCTYPE html><div id="c

ire('react');
    ReactDOMClient = require('react-dom/client');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
  });

  it('errors when a hoistable component becomes a Resource', async () => {

ontainer">',
      {
        runScripts: 'dangerously',
      },
    );
    global.window = jsdom.window;
    global.document = jsdom.window.document;
    container = global.document.getElementById('container');

    React = requ


Message(args, index) {
    const ownerStack = ownerStacks[index];

    if (ownerStack === undefined) {
      throw new Error(
        'Expected an owner stack for message ' +
          index +
          ':\n' +
          util.format(...args),
      );
    }

    const [format, ...rest] = args;
    if (format instanceof Error) {
      if (format.cause instanceof Error) {
        return (
          'Caught [' +
          format.message +
          ']\n  Cause [' +
          format.cause.message +
          ']

    rest[rest.length - 1] = normalizeCodeLocInfo(rest[rest.length - 1]);
    return (
      util.format(format, ...rest) +
      '\n  Owner Stack:' +
      normalizeCodeLocInfo(ownerStack)
    );
  }

  function formatConsoleErrors() {
    return console.e

\n  Owner Stack:' +
          normalizeCodeLocInfo(ownerStack)
        );
      }
      return (
        'Caught [' +
        format.message +
        ']\n  Owner Stack:' +
        normalizeCodeLocInfo(ownerStack)
      );
    }


/**
 * 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.
 *
 * @emails react-core
 */

'use strict';

describe('ReactDOMIframe', () => {
  let React;
  let ReactDOMClient;
  let act;

  beforeEach(() => {
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
  });

  it('should trigger load events', async ()

adSpy}));
    });
    const iframe = container.firstChild;

    const loadEvent = document.createEvent('Event');
    loadEvent.initEvent('load', false, false);

    await act(() => {
      iframe.dispatchEvent(loadEvent);
    });

    expect(onLoadSpy).toH

=> {
    const onLoadSpy = jest.fn();
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);
    await act(() => {
      root.render(React.createElement('iframe', {onLoad: onLo


Array.isArray(arr)) {
    if (arr.length) {
      return arr[arr.length - 1];
    }
    return undefined;
  }
  throw new Error('last was passed something that was not an array');
}

function Text(props) {
  Scheduler.log(props.text);
  return props.text;
}

// function AsyncText(props) {
//   const text = props.text;
//   try {
//     TextResource.read([props.text, props.ms]);
//     Scheduler.log(text);
//     return text;
//   } catch (promise) {
//     if (typeof promise.then === 'function') {
//

default';
  Scheduler.log('Img ' + src);
  return <img src={src} onLoad={onLoad} />;
}

function Yield() {
  Scheduler.log('Yield');
  Scheduler.unstable_requestPaint();
  return null;
}

function loadImage(element) {
  const event = new Event('load');
  e

Scheduler.log(`Suspend! [${text}]`);
//     } else {
//       Scheduler.log(`Error! [${text}]`);
//     }
//     throw promise;
//   }
// }

function Img({src: maybeSrc, onLoad, useImageLoader, ref}) {
  const src = maybeSrc || '


0 with missing onChange', async () => {
    await act(() => {
      root.render(<input type="text" value={0} />);
    });
    assertConsoleErrorDev([
      'You provided a `value` prop to a form ' +
        'field without an `onChange` handler. This will render a read-only ' +
        'field. If the field should be mutable use `defaultValue`. ' +
        'Otherwise, set either `onChange` or `readOnly`.\n' +
        '    in input (at **)',
    ]);
  });

  it('should warn for controlled value of "" with miss

ing onChange', async () => {
    await act(() => {
      root.render(<input type="text" value="" />);
    });
    assertConsoleErrorDev([
      'You provided a `value` prop to a form ' +
        'field without an `onChange` handl


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

describe('ReactDOMInvalidARIAHook', () => {
  let React;
  let ReactDOMClient;
  let mountComponent;
  let act;
  let assertConsoleErrorDev;

  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
    assertConsoleErrorDev =
      require('internal-test-utils').ass

...props} />);
      });
    };
  });

  describe('aria-* props', () => {
    it('should allow valid aria-* props', async () => {
      await mountComponent({'aria-label': 'Bumble bees'});
    });

    it('should allow new ARIA 1.3 attributes', async () =>

ertConsoleErrorDev;

    mountComponent = async function (props) {
      const container = document.createElement('div');
      const root = ReactDOMClient.createRoot(container);
      await act(() => {
        root.render(<div {


 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.
 *
 * @emails react-core
 */

'use strict';

describe('ReactDOMComponentTree', () => {
  let React;
  let ReactDOM;
  let container;
  let assertConsoleErrorDev;

  beforeEach(() => {
    React = require('react');
    ReactDOM = require('react-dom');
    assertConsoleErrorDev =
      require('internal-test-utils').assertConsoleErrorDev;

    contai

f node that is attempted to be unmounted', () => {
    const component = <div />;
    const node = ReactDOM.render(<div>{component}</div>, container);
    ReactDOM.unmountComponentAtNode(node);
    assertConsoleErrorDev([
      "unmountComponentAtNode(): T

ner = document.createElement('div');
    document.body.appendChild(container);
  });

  afterEach(() => {
    document.body.removeChild(container);
    container = null;
  });

  // @gate !disableLegacyMode
  it('finds instance o


expect(called).toEqual(true);
  });

  // @gate !disableLegacyMode
  it('should call a callback argument when the same element is re-rendered', () => {
    class Foo extends React.Component {
      render() {
        return
Foo
;
      }
    }
    const element = <Foo />;

    // mounting phase
    let called = false;
    ReactDOM.render(element, container, () => (called = true));
    expect(called).toEqual(true);

    // updating phase
    called = false;
    ReactDOM.unstable_batchedUpdates(() =

    const Text = ({value}) => value;

    ReactDOM.render(<Text value="foo" />, container);
    expect(container.textContent).toEqual('foo');
  });

  // @gate !disableLegacyMode
  it('should render a component returning numbers directly from render', ()

> {
      ReactDOM.render(element, container, () => (called = true));
    });
    expect(called).toEqual(true);
  });

  // @gate !disableLegacyMode
  it('should render a component returning strings directly from render', () => {


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
 */

'use strict';

let React;
let ReactDOMFizzServer;

describe('ReactDOMFloat', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactDOMFizzServer = require('react-dom/server');
  });

  // fixes #27177
  it('does not hoist above the <html> tag', async (

oString(
      <html>
        <head>
          <script src="foo" />
          <meta charSet="utf-8" />
          <title>title</title>
        </head>
      </html>,
    );

    expect(result).toEqual(
      '<html><head><meta charSet="utf-8"/>' +
        '

) => {
    const result = ReactDOMFizzServer.renderT


reEach(() => {
    jest.resetModules();
    container = document.createElement('div');
    React = require('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;

    const InternalTestUtils = require('internal-test-utils');
    assertLog = InternalTestUtils.assertLog;
    waitFor = InternalTestUtils.waitFor;

    document.body.appendChild(container);
  });

  afterEach(() => {
    d

ignores discrete events on a pending removed element', async () => {
    const disableButtonRef = React.createRef();
    const submitButtonRef = React.createRef();

    function Form() {
      const [active, setActive] = React.useState(true);

      React.

ocument.body.removeChild(container);
  });

  function dispatchAndSetCurrentEvent(el, event) {
    try {
      window.event = event;
      el.dispatchEvent(event);
    } finally {
      window.event = undefined;
    }
  }

  it('


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

import {insertNodesAndExecuteScripts} from '../test-utils/FizzTestUtils';
import {patchMessageChannel} from '../../../../scripts/jest/patchMessageChannel';

// Polyfills for test environment
global.ReadableStream =
  require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;

le

);
    patchMessageChannel();

    React = require('react');
    ReactDOMServer = require('react-dom/server.browser');
    assertLog = require('internal-test-utils').assertLog;
    serverAct = require('internal-test-utils').serverAct;
    container = docum

t React;
let ReactDOMServer;
let Scheduler;
let assertLog;
let container;
let serverAct;

describe('ReactClassComponentPropResolutionFizz', () => {
  beforeEach(() => {
    jest.resetModules();
    Scheduler = require('scheduler'


('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    ReactSharedInternals =
      require('react').__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
    Scheduler = require('scheduler');
    assertLog = require('internal-test-utils').assertLog;
    ({act, assertConsoleErrorDev} = require('internal-test-utils'));
  });

  describe('MorphingComponent', () => {
    let instance;
    let childInstance;

    beforeEach(() => {
      MorphingComponen

.setState({activated: !this.state.activated});
        };

        render() {
          const toggleActivatedState = this._toggleActivatedState;
          return !this.state.activated ? (
            <a ref={this.xRef} onClick={toggleActivatedState} />

t = class extends React.Component {
        state = {activated: false};
        xRef = React.createRef();

        componentDidMount() {
          instance = this;
        }

        _toggleActivatedState = () => {
          this


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

// Requires
let React;
let ReactDOMClient;
let act;

// Test components
let LowerLevelComposite;
let MyCompositeComponent;

/**
 * Integration test, testing the combination of JSX with our unit of
 * abstraction, `ReactCompositeComponent` does not ever add superfluous DOM
 * nodes.
 */
describe('ReactCompositeComponentDOMMinimali

er() {
        return <div>{this.props.children}</div>;
      }
    };

    MyCompositeComponent = class extends React.Component {
      render() {
        return <LowerLevelComposite>{this.props.children}</LowerLevelComposite>;
      }
    };
  });

  it(

sm', () => {
  beforeEach(() => {
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;

    LowerLevelComposite = class extends React.Component {
      rend


it({children, color}) {
      React.useEffect(() => {
        Scheduler.log(`commit ${color}`);
      });
      return children;
    }

    TestComponent = class extends React.Component {
      constructor(props) {
        super(props);
        this.peekAtState('getInitialState', undefined, props);
        this.state = {color: 'red'};
        testComponentInstance = this;
      }

      peekAtState = (from, state = this.state, props = this.props) => {
        Scheduler.log(`${from} ${state && state.color}`)

teColor'),
        );
      }

      render() {
        this.peekAtState('render');
        return (
          <LogAfterCommit color={this.state.color}>
            <div>{this.state.color}</div>
          </LogAfterCommit>
        );
      }

      UNSAFE_

;
      };

      peekAtCallback = from => {
        return () => this.peekAtState(from);
      };

      setFavoriteColor(nextColor) {
        this.setState(
          {color: nextColor},
          this.peekAtCallback('setFavori


e;

describe('ReactDOMActivity', () => {
  let container;

  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    Scheduler = require('scheduler/unstable_mock');
    Activity = React.Activity;
    useState = React.useState;
    Suspense = React.Suspense;
    useState = React.useState;
    LegacyHidden = React.unstable_LegacyHidden;
    useLayoutEffect = React.useLayoutEffect;
    useEffect = React.useEffect;
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-do

container);
  });

  afterEach(() => {
    document.body.removeChild(container);
  });

  function Text(props) {
    Scheduler.log(props.text);
    return {props.children};
  }

  it(
    'hiding an Activity boundary also hid

m/client');
    const InternalTestUtils = require('internal-test-utils');
    act = InternalTestUtils.act;
    assertLog = InternalTestUtils.assertLog;
    container = document.createElement('div');
    document.body.appendChild(


        get fontFamily() {
          return styleStore.fontFamily;
        },
        set fontFamily(v) {
          styleStore.fontFamily = v;
        },
        get lineHeight() {
          return styleStore.lineHeight;
        },
        set lineHeight(v) {
          styleStore.lineHeight = v;
        },
      };
      const container = document.createElement('div');
      const root = ReactDOMClient.createRoot(container);
      await act(() => {
        root.render(<div style={styles} />);
      });

{styles} />);
      });
      expect(stubStyle.display).toEqual('none');
      expect(stubStyle.fontFamily).toEqual('Arial');
      expect(stubStyle.lineHeight).toEqual('1.2');

      styles.fontFamily = 'Helvetica';

      await act(() => {
        root.r

    const stubStyle = container.firstChild.style;
      stubStyle.display = styles.display;
      stubStyle.fontFamily = styles.fontFamily;

      styles.display = 'block';

      await act(() => {
        root.render(<div style=


() => {
    jest.resetModules();
    act = require('internal-test-utils').act;
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    Scheduler = require('scheduler');

    ErrorBoundary = class extends React.Component {
      state = {error: null};
      static getDerivedStateFromError(error) {
        return {error};
      }
      render() {
        if (this.state.error) {
          return
Caught: {this.state.error.message}
;
        }
        return this.props.childre

rror', windowOnError);
    spyOnDevAndProd(console, 'error').mockImplementation(() => {});
    spyOnDevAndProd(console, 'warn').mockImplementation(() => {});
  });

  afterEach(() => {
    document.body.removeChild(container);
    window.removeEventListene

n;
      }
    };
    NoError = function () {
      return
OK
;
    };
    container = document.createElement('div');
    document.body.appendChild(container);
    windowOnError = jest.fn();
    window.addEventListener('e


est harness mounts each test app as a separate root to test multi-root applications.

import * as React from 'react';
import * as ReactDOMClient from 'react-dom/client';
import ListApp from '../e2e-apps/ListApp';

function mountApp(App: () => React$Node) {
  const container = document.createElement('div');

  ((document.body: any): HTMLBodyElement).appendChild(container);

  const root = ReactDOMClient.createRoot(container);
  root.render(<App />);
}
function mountTestApp() {
  mountApp(ListApp);
}

mountTe

ywright e2e tests
// If they don't exist, we mock them
window.parent.REACT_DOM_APP = {
  createTestNameSelector: name => `[data-testname="${name}"]`,
  findAllNodes: (container, nodes) =>
    container.querySelectorAll(nodes.join(' ')),
  ...ReactDOMClient

stApp();

// ReactDOM Test Selector APIs used by Pla


eact';
import * as ReactDOM from 'react-dom';
import * as ReactDOMClient from 'react-dom/client';
import {
  activate as activateBackend,
  initialize as initializeBackend,
} from 'react-devtools-inline/backend';
import {initialize as createDevTools} from 'react-devtools-inline/frontend';

// This is a pretty gross hack to make the runtime loaded named-hooks-code work.
// TODO (Webpack 5) Hoepfully we can remove this once we upgrade to Webpack 5.
__webpack_public_path__ = '/dist/'; // eslint-disable-line no

ePath, callback) {
  const script = contentDocument.createElement('script');
  script.onload = callback;
  script.src = sourcePath;

  ((contentDocument.body: any): HTMLBodyElement).appendChild(script);
}

function init(appIframe, devtoolsContainer, appSou

-undef

// TODO (Webpack 5) Hopefully we can remove this prop after the Webpack 5 migration.
function hookNamesModuleLoaderFunction() {
  return import('react-devtools-inline/hookNames');
}

function inject(contentDocument, sourc


/**
 * 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.
 */

// This file is only used for tests.
// It lazily loads the implementation so that we get the correct set of host configs.

import ReactVersion from 'shared/ReactVersion';
export {ReactVersion as version};

export function renderToString() {
  return require('./src/server/ReactDOMLegacyServerBrowser').renderToString.ap

bleStream() {
  return require('./src/server/react-dom-server.browser').renderToReadableStream.apply(
    this,
    arguments,
  );
}

export function resume() {
  return require('./src/server/react-dom-server.browser').resume.apply(
    this,
    argument

ply(
    this,
    arguments,
  );
}
export function renderToStaticMarkup() {
  return require('./src/server/ReactDOMLegacyServerBrowser').renderToStaticMarkup.apply(
    this,
    arguments,
  );
}

export function renderToReada


/**
 * 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.
 */

// This file is only used for tests.
// It lazily loads the implementation so that we get the correct set of host configs.

import ReactVersion from 'shared/ReactVersion';
export {ReactVersion as version};

export function renderToReadableStream() {
  return require('./src/server/react-dom-server.edge').renderToReadabl

Markup() {
  return require('./src/server/ReactDOMLegacyServerBrowser').renderToStaticMarkup.apply(
    this,
    arguments,
  );
}

export function resume() {
  return require('./src/server/react-dom-server.edge').resume.apply(
    this,
    arguments,

eStream.apply(
    this,
    arguments,
  );
}

export function renderToString() {
  return require('./src/server/ReactDOMLegacyServerBrowser').renderToString.apply(
    this,
    arguments,
  );
}

export function renderToStatic


/**
 * 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.
 */

// This file is only used for tests.
// It lazily loads the implementation so that we get the correct set of host configs.

import ReactVersion from 'shared/ReactVersion';
export {ReactVersion as version};

export function prerenderToNodeStream() {
  return require('./src/server/react-dom-server.node').prerenderToNodeS

 {
  return require('./src/server/react-dom-server.node').resumeAndPrerenderToNodeStream.apply(
    this,
    arguments,
  );
}

export function resumeAndPrerender() {
  return require('./src/server/react-dom-server.node').resumeAndPrerender.apply(
    thi

tream.apply(
    this,
    arguments,
  );
}

export function prerender() {
  return require('./src/server/react-dom-server.node').prerender.apply(
    this,
    arguments,
  );
}

export function resumeAndPrerenderToNodeStream()


ight (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
 */

import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities';
import type {HostDispatcher} from './shared/ReactDOMTypes';

import {NoEventPriority} from 'react-reconciler/src/ReactEventPriorities';

import noop from 'shared/noop';

type ReactDOMInternals = {
  Events: [any, any, any, any, any, any],
  d

her: HostDispatcher = {
  f /* flushSyncWork */: noop,
  r /* requestFormReset */: noop,
  D /* prefetchDNS */: noop,
  C /* preconnect */: noop,
  L /* preload */: noop,
  m /* preloadModule */: noop,
  X /* preinitScript */: noop,
  S /* preinitStyle */:

 /* ReactDOMCurrentDispatcher */: HostDispatcher,
  p /* currentUpdatePriority */: EventPriority,
  findDOMNode:
    | null
    | ((componentOrElement: component(...props: any)) => null | Element | Text),
};

const DefaultDispatc


ct-core
 */

'use strict';

const React = require('react');
const ReactDOMClient = require('react-dom/client');
const ReactDOMServer = require('react-dom/server');
const act = require('internal-test-utils').act;
const assertConsoleErrorDev =
  require('internal-test-utils').assertConsoleErrorDev;

describe('CSSPropertyOperations', () => {
  it('should automatically append `px` to relevant styles', () => {
    const styles = {
      left: 0,
      margin: 16,
      opacity: 0.5,
      padding: '4px',
    };

 {
      left: '16 ',
      opacity: 0.5,
      right: ' 4 ',
    };
    const div = <div style={styles} />;
    const html = ReactDOMServer.renderToString(div);
    expect(html).toContain('"left:16;opacity:0.5;right:4"');
  });

  it('should not append `p

    const div = <div style={styles} />;
    const html = ReactDOMServer.renderToString(div);
    expect(html).toContain('"left:0;margin:16px;opacity:0.5;padding:4px"');
  });

  it('should trim values', () => {
    const styles =


ct-core
 */

// NOTE: We're explicitly not using JSX here. This is intended to test
// the current stack addendum without having source location added by babel.

'use strict';

let React;
let ReactDOMClient;
let act;
let assertConsoleErrorDev;

describe('ReactChildReconciler', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactDOMClient = require('react-dom/client');
    ({act, assertConsoleErrorDev} = require('internal-test-utils'));
  });

  function createIterab

array.length,
            };
            i++;
            return next;
          },
        };
      },
    };
  }

  function makeIterableFunction(value) {
    const fn = () => {};
    fn['@@iterator'] = function iterator() {
      let timesCalled = 0;

le(array) {
    return {
      '@@iterator': function () {
        let i = 0;
        return {
          next() {
            const next = {
              value: i < array.length ? array[i] : undefined,
              done: i ===


ases. Better to just block all updates in initialization.
 */
describe('ReactComponentLifeCycle', () => {
  beforeEach(() => {
    jest.resetModules();

    ({
      act,
      assertConsoleErrorDev,
      assertConsoleWarnDev,
    } = require('internal-test-utils'));

    React = require('react');
    ReactDOMClient = require('react-dom/client');
  });

  it('should not reuse an instance when it has been unmounted', async () => {
    const container = document.createElement('div');

    class StatefulCompo

 root.render(element);
    });

    const firstInstance = container.firstChild;
    await act(() => {
      root.unmount();
    });
    root = ReactDOMClient.createRoot(container);
    await act(() => {
      root.render(element);
    });

    const second

nent extends React.Component {
      state = {};

      render() {
        return <div />;
      }
    }

    const element = <StatefulComponent />;
    let root = ReactDOMClient.createRoot(container);
    await act(() => {


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

let React;
let ReactDOMClient;
let act;

describe('ReactCompositeComponentNestedState-state', () => {
  beforeEach(() => {
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
  });

  it('should provide up to date values for props', async () => {
    class ParentComponent extends React.Component {
      sta

s.state.color);
        });
      };

      render() {
        this.props.logger('parent-render', this.state.color);
        return (
          <ChildComponent
            logger={this.props.logger}
            color={this.state.color}
            onSelect

te = {color: 'blue'};

      handleColor = color => {
        this.props.logger('parent-handleColor', this.state.color);
        this.setState({color: color}, function () {
          this.props.logger('parent-after-setState', thi


ync () => {
    const container = document.createElement('div');

    let count = 0;
    let buttonRef;

    function Parent() {
      return (
        <div
          onSubmit={event => {
            event.preventDefault();
            count++;
          }}>
          <Child />
        </div>
      );
    }

    function Child() {
      return (
        <form>
          <input type="submit" ref={button => (buttonRef = button)} />
        </form>
      );
    }

    document.body.appendChild(container);

(container);
    }
  });

  it('allows a DOM element to be used with a string', async () => {
    const element = React.createElement('div', {className: 'foo'});
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoo

const root = ReactDOMClient.createRoot(container);
    try {
      await act(() => {
        root.render(<Parent />);
      });
      buttonRef.click();
      expect(count).toBe(1);
    } finally {
      document.body.removeChild


 @flow */

// This test harness mounts each test app as a separate root to test multi-root applications.

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import ListApp from '../e2e-apps/ListApp';
import ListAppLegacy from '../e2e-apps/ListAppLegacy';
import {gte} from 'react-devtools-shared/src/backend/utils';

const version = process.env.E2E_APP_REACT_VERSION;

function mountApp(App: () => React$Node) {
  const container = document.createElement('div');

  ((document.body: any): HTM

App(gte(version, '16.8.0') ? ListApp : ListAppLegacy);
}

mountTestApp();

// ReactDOM Test Selector APIs used by Playwright e2e tests
// If they don't exist, we mock them
window.parent.REACT_DOM_APP = {
  createTestNameSelector: name => `[data-testname="$

LBodyElement).appendChild(container);

  // $FlowFixMe[prop-missing]: These are removed in 19.
  ReactDOM.render(<App />, container);
}
function mountTestApp() {
  // ListApp has hooks, which aren't available until 16.8.0
  mount


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as React from 'react';
import {useLayoutEffect, useRef, useState} from 'react';
import {createRoot} from 'react-dom/client';

function createContainer() {
  const container = document.createElement('div');

  ((document.body: any): HTMLBodyElement).appendChild(container);

  return container;
}

function EffectWithState() {
  const [didMount, setDidMount] = useState(0);

  const renderCountRef = useRef

() => {
    if (!didMount) {
      setDidMount(true);
    }
  }, [didMount]);

  return (

Rendered {renderCountRef.current} times

      {didMount &&
Mounted!
}

  );
}

createRoot(createContainer()).render(<EffectWi

(0);
  renderCountRef.current++;

  useLayoutEffect(


ight (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.
 */

// This file is only used for tests.
// It lazily loads the implementation so that we get the correct set of host configs.

import ReactVersion from 'shared/ReactVersion';
export {ReactVersion as version};

export function renderToReadableStream() {
  return require('./src/server/react-dom-server.bun').renderToReadableStream.apply

return require('./src/server/ReactDOMLegacyServerBrowser').renderToStaticMarkup.apply(
    this,
    arguments,
  );
}

export function resume() {
  return require('./src/server/react-dom-server.bun').resume.apply(
    this,
    arguments,
  );
}

export f

(
    this,
    arguments,
  );
}

export function renderToString() {
  return require('./src/server/ReactDOMLegacyServerBrowser').renderToString.apply(
    this,
    arguments,
  );
}

export function renderToStaticMarkup() {


 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
 */

import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities';
import type {HostDispatcher} from './shared/ReactDOMTypes';

import noop from 'shared/noop';

// This should line up with NoEventPriority from react-reconciler/src/ReactEventPriorities
// but we can't depend on the react-reconciler from this isomorphic co

entOrElement: component(...props: any)) => null | Element | Text),
};

function requestFormReset(element: HTMLFormElement) {
  throw new Error(
    'Invalid form element. requestFormReset must be passed a form that was ' +
      'rendered by React.',
  );

de.
export const NoEventPriority: EventPriority = (0: any);

type ReactDOMInternals = {
  d /* ReactDOMCurrentDispatcher */: HostDispatcher,
  p /* currentUpdatePriority */: EventPriority,
  findDOMNode:
    | null
    | ((compon


xpect(container.firstChild.getAttribute('role')).toBe('#');
      expect(container.firstChild.role).toBeUndefined();
    });

    it('should set values as namespace attributes if necessary', async () => {
      const container = document.createElementNS(
        'http://www.w3.org/2000/svg',
        'svg',
      );
      const root = ReactDOMClient.createRoot(container);
      await act(() => {
        root.render(<image xlinkHref="about:blank" />);
      });
      expect(
        container.firstChild.getAt

t('div');
      const root = ReactDOMClient.createRoot(container);
      await act(() => {
        root.render(<div disabled="disabled" />);
      });
      expect(container.firstChild.getAttribute('disabled')).toBe('');
      await act(() => {
        roo

tributeNS(
          'http://www.w3.org/1999/xlink',
          'href',
        ),
      ).toBe('about:blank');
    });

    it('should set values as boolean properties', async () => {
      const container = document.createElemen


ct-core
 */

'use strict';

// Fix JSDOM. setAttribute is supposed to throw on things that can't be implicitly toStringed.
const setAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function (name, value) {
  // eslint-disable-next-line react-internal/safe-string-coercion
  return setAttribute.call(this, name, '' + value);
};

describe('ReactDOM unknown attribute', () => {
  let React;
  let ReactDOMClient;
  let act;
  let assertConsoleErrorDev;

  beforeEach(() => {
    jest.res

});

  async function testUnknownAttributeRemoval(givenValue) {
    const el = document.createElement('div');
    const root = ReactDOMClient.createRoot(el);

    await act(() => {
      root.render(<div unknown="something" />);
    });

    expect(el.firs

etModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
    assertConsoleErrorDev =
      require('internal-test-utils').assertConsoleErrorDev;