repo_name
stringlengths 4
68
⌀ | text
stringlengths 21
269k
| avg_line_length
float64 9.4
9.51k
| max_line_length
int64 20
28.5k
| alphnanum_fraction
float64 0.3
0.92
|
---|---|---|---|---|
null | #!/usr/bin/env node
'use strict';
const {execRead, logPromise} = require('../utils');
const theme = require('../theme');
const run = async ({cwd, packages, version}) => {
const currentUser = await execRead('npm whoami');
const failedProjects = [];
const checkProject = async project => {
const owners = (await execRead(`npm owner ls ${project}`))
.split('\n')
.filter(owner => owner)
.map(owner => owner.split(' ')[0]);
if (!owners.includes(currentUser)) {
failedProjects.push(project);
}
};
await logPromise(
Promise.all(packages.map(checkProject)),
theme`Checking NPM permissions for {underline ${currentUser}}.`
);
if (failedProjects.length) {
console.error(
theme`
{error Insufficient NPM permissions}
\nNPM user {underline ${currentUser}} is not an owner for: ${failedProjects
.map(name => theme.package(name))
.join(', ')}
\nPlease contact a React team member to be added to the above project(s).
`
.replace(/\n +/g, '\n')
.trim()
);
process.exit(1);
}
};
module.exports = run;
| 24.044444 | 81 | 0.604796 |
Mastering-Machine-Learning-for-Penetration-Testing | /**
* 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 './AutoSizeInput.css';
type Props = {
className?: string,
onFocus?: (event: FocusEvent) => void,
placeholder?: string,
testName?: ?string,
value: any,
};
export default function AutoSizeInput({
className,
onFocus,
placeholder = '',
testName,
value,
...rest
}: Props): React.Node {
// $FlowFixMe[missing-local-annot]
const onFocusWrapper = event => {
const input = event.target;
if (input !== null) {
input.selectionStart = 0;
input.selectionEnd = value.length;
}
if (typeof onFocus === 'function') {
onFocus(event);
}
};
const isEmpty = value === '' || value === '""';
return (
// $FlowFixMe[cannot-spread-inexact] unsafe rest spread
<input
className={[styles.Input, className].join(' ')}
data-testname={testName}
onFocus={onFocusWrapper}
placeholder={placeholder}
style={{
width: `calc(${isEmpty ? placeholder.length : value.length}ch + 1px)`,
}}
value={isEmpty ? '' : value}
{...rest}
/>
);
}
| 20.966102 | 78 | 0.608494 |
cybersecurity-penetration-testing | /**
* 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 type {NormalizedWheelDelta} from './utils/normalizeWheel';
import type {Point} from './geometry';
import {useEffect, useRef} from 'react';
import {normalizeWheel} from './utils/normalizeWheel';
export type ClickInteraction = {
type: 'click',
payload: {
event: MouseEvent,
location: Point,
},
};
export type DoubleClickInteraction = {
type: 'double-click',
payload: {
event: MouseEvent,
location: Point,
},
};
export type MouseDownInteraction = {
type: 'mousedown',
payload: {
event: MouseEvent,
location: Point,
},
};
export type MouseMoveInteraction = {
type: 'mousemove',
payload: {
event: MouseEvent,
location: Point,
},
};
export type MouseUpInteraction = {
type: 'mouseup',
payload: {
event: MouseEvent,
location: Point,
},
};
export type WheelPlainInteraction = {
type: 'wheel-plain',
payload: {
event: WheelEvent,
location: Point,
delta: NormalizedWheelDelta,
},
};
export type WheelWithShiftInteraction = {
type: 'wheel-shift',
payload: {
event: WheelEvent,
location: Point,
delta: NormalizedWheelDelta,
},
};
export type WheelWithControlInteraction = {
type: 'wheel-control',
payload: {
event: WheelEvent,
location: Point,
delta: NormalizedWheelDelta,
},
};
export type WheelWithMetaInteraction = {
type: 'wheel-meta',
payload: {
event: WheelEvent,
location: Point,
delta: NormalizedWheelDelta,
},
};
export type Interaction =
| ClickInteraction
| DoubleClickInteraction
| MouseDownInteraction
| MouseMoveInteraction
| MouseUpInteraction
| WheelPlainInteraction
| WheelWithShiftInteraction
| WheelWithControlInteraction
| WheelWithMetaInteraction;
let canvasBoundingRectCache = null;
function cacheFirstGetCanvasBoundingRect(
canvas: HTMLCanvasElement,
): ClientRect {
if (
canvasBoundingRectCache &&
canvas.width === canvasBoundingRectCache.width &&
canvas.height === canvasBoundingRectCache.height
) {
return canvasBoundingRectCache.rect;
}
canvasBoundingRectCache = {
width: canvas.width,
height: canvas.height,
rect: canvas.getBoundingClientRect(),
};
return canvasBoundingRectCache.rect;
}
export function useCanvasInteraction(
canvasRef: {current: HTMLCanvasElement | null},
interactor: (interaction: Interaction) => void,
) {
const isMouseDownRef = useRef<boolean>(false);
const didMouseMoveWhileDownRef = useRef<boolean>(false);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) {
return;
}
function localToCanvasCoordinates(localCoordinates: Point): Point {
// $FlowFixMe[incompatible-call] found when upgrading Flow
const canvasRect = cacheFirstGetCanvasBoundingRect(canvas);
return {
x: localCoordinates.x - canvasRect.left,
y: localCoordinates.y - canvasRect.top,
};
}
const onCanvasClick: MouseEventHandler = event => {
if (didMouseMoveWhileDownRef.current) {
return;
}
interactor({
type: 'click',
payload: {
event,
location: localToCanvasCoordinates({x: event.x, y: event.y}),
},
});
};
const onCanvasDoubleClick: MouseEventHandler = event => {
if (didMouseMoveWhileDownRef.current) {
return;
}
interactor({
type: 'double-click',
payload: {
event,
location: localToCanvasCoordinates({x: event.x, y: event.y}),
},
});
};
const onCanvasMouseDown: MouseEventHandler = event => {
didMouseMoveWhileDownRef.current = false;
isMouseDownRef.current = true;
interactor({
type: 'mousedown',
payload: {
event,
location: localToCanvasCoordinates({x: event.x, y: event.y}),
},
});
};
const onDocumentMouseMove: MouseEventHandler = event => {
if (isMouseDownRef.current) {
didMouseMoveWhileDownRef.current = true;
}
interactor({
type: 'mousemove',
payload: {
event,
location: localToCanvasCoordinates({x: event.x, y: event.y}),
},
});
};
const onDocumentMouseUp: MouseEventHandler = event => {
isMouseDownRef.current = false;
interactor({
type: 'mouseup',
payload: {
event,
location: localToCanvasCoordinates({x: event.x, y: event.y}),
},
});
};
const onCanvasWheel: WheelEventHandler = event => {
event.preventDefault();
event.stopPropagation();
const location = localToCanvasCoordinates({x: event.x, y: event.y});
const delta = normalizeWheel(event);
if (event.shiftKey) {
interactor({
type: 'wheel-shift',
payload: {event, location, delta},
});
} else if (event.ctrlKey) {
interactor({
type: 'wheel-control',
payload: {event, location, delta},
});
} else if (event.metaKey) {
interactor({
type: 'wheel-meta',
payload: {event, location, delta},
});
} else {
interactor({
type: 'wheel-plain',
payload: {event, location, delta},
});
}
return false;
};
const ownerDocument = canvas.ownerDocument;
ownerDocument.addEventListener('mousemove', onDocumentMouseMove);
ownerDocument.addEventListener('mouseup', onDocumentMouseUp);
canvas.addEventListener('click', onCanvasClick);
canvas.addEventListener('dblclick', onCanvasDoubleClick);
canvas.addEventListener('mousedown', onCanvasMouseDown);
canvas.addEventListener('wheel', onCanvasWheel);
return () => {
ownerDocument.removeEventListener('mousemove', onDocumentMouseMove);
ownerDocument.removeEventListener('mouseup', onDocumentMouseUp);
canvas.removeEventListener('click', onCanvasClick);
canvas.removeEventListener('dblclick', onCanvasDoubleClick);
canvas.removeEventListener('mousedown', onCanvasMouseDown);
canvas.removeEventListener('wheel', onCanvasWheel);
};
}, [canvasRef, interactor]);
}
| 23.972549 | 74 | 0.639391 |
cybersecurity-penetration-testing | /**
* 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 * from './index.stable.js';
| 20.818182 | 66 | 0.682008 |
Python-Penetration-Testing-for-Developers | let React;
let ReactNoop;
let Scheduler;
let act;
let Suspense;
let useState;
let textCache;
let readText;
let resolveText;
// let rejectText;
let assertLog;
let waitForPaint;
describe('ReactSuspenseWithNoopRenderer', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
Suspense = React.Suspense;
useState = React.useState;
const InternalTestUtils = require('internal-test-utils');
assertLog = InternalTestUtils.assertLog;
waitForPaint = InternalTestUtils.waitForPaint;
textCache = new Map();
readText = text => {
const record = textCache.get(text);
if (record !== undefined) {
switch (record.status) {
case 'pending':
throw record.promise;
case 'rejected':
throw Error('Failed to load: ' + text);
case 'resolved':
return text;
}
} else {
let ping;
const promise = new Promise(resolve => (ping = resolve));
const newRecord = {
status: 'pending',
ping: ping,
promise,
};
textCache.set(text, newRecord);
throw promise;
}
};
resolveText = text => {
const record = textCache.get(text);
if (record !== undefined) {
if (record.status === 'pending') {
record.ping();
record.ping = null;
record.status = 'resolved';
record.promise = null;
}
} else {
const newRecord = {
ping: null,
status: 'resolved',
promise: null,
};
textCache.set(text, newRecord);
}
};
// rejectText = text => {
// const record = textCache.get(text);
// if (record !== undefined) {
// if (record.status === 'pending') {
// Scheduler.log(`Promise rejected [${text}]`);
// record.ping();
// record.status = 'rejected';
// clearTimeout(record.promise._timer);
// record.promise = null;
// }
// } else {
// const newRecord = {
// ping: null,
// status: 'rejected',
// promise: null,
// };
// textCache.set(text, newRecord);
// }
// };
});
function Text(props) {
Scheduler.log(props.text);
return props.text;
}
function AsyncText(props) {
const text = props.text;
try {
readText(text);
Scheduler.log(text);
return text;
} catch (promise) {
if (typeof promise.then === 'function') {
Scheduler.log(`Suspend! [${text}]`);
} else {
Scheduler.log(`Error! [${text}]`);
}
throw promise;
}
}
// @gate enableCPUSuspense
it('skips CPU-bound trees on initial mount', async () => {
function App() {
return (
<>
<Text text="Outer" />
<div>
<Suspense
unstable_expectedLoadTime={2000}
fallback={<Text text="Loading..." />}>
<Text text="Inner" />
</Suspense>
</div>
</>
);
}
const root = ReactNoop.createRoot();
await act(async () => {
root.render(<App />);
await waitForPaint(['Outer', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
Outer
<div>Loading...</div>
</>,
);
});
// Inner contents finish in separate commit from outer
assertLog(['Inner']);
expect(root).toMatchRenderedOutput(
<>
Outer
<div>Inner</div>
</>,
);
});
// @gate enableCPUSuspense
it('does not skip CPU-bound trees during updates', async () => {
let setCount;
function App() {
const [count, _setCount] = useState(0);
setCount = _setCount;
return (
<>
<Text text="Outer" />
<div>
<Suspense
unstable_expectedLoadTime={2000}
fallback={<Text text="Loading..." />}>
<Text text={`Inner [${count}]`} />
</Suspense>
</div>
</>
);
}
// Initial mount
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
// Inner contents finish in separate commit from outer
assertLog(['Outer', 'Loading...', 'Inner [0]']);
expect(root).toMatchRenderedOutput(
<>
Outer
<div>Inner [0]</div>
</>,
);
// Update
await act(() => {
setCount(1);
});
// Entire update finishes in a single commit
assertLog(['Outer', 'Inner [1]']);
expect(root).toMatchRenderedOutput(
<>
Outer
<div>Inner [1]</div>
</>,
);
});
// @gate enableCPUSuspense
it('suspend inside CPU-bound tree', async () => {
function App() {
return (
<>
<Text text="Outer" />
<div>
<Suspense
unstable_expectedLoadTime={2000}
fallback={<Text text="Loading..." />}>
<AsyncText text="Inner" />
</Suspense>
</div>
</>
);
}
const root = ReactNoop.createRoot();
await act(async () => {
root.render(<App />);
await waitForPaint(['Outer', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
Outer
<div>Loading...</div>
</>,
);
});
// Inner contents suspended, so we continue showing a fallback.
assertLog(['Suspend! [Inner]']);
expect(root).toMatchRenderedOutput(
<>
Outer
<div>Loading...</div>
</>,
);
// Resolve the data and finish rendering
await act(async () => {
await resolveText('Inner');
});
assertLog(['Inner']);
expect(root).toMatchRenderedOutput(
<>
Outer
<div>Inner</div>
</>,
);
});
// @gate enableCPUSuspense
it('nested CPU-bound trees', async () => {
function App() {
return (
<>
<Text text="A" />
<div>
<Suspense
unstable_expectedLoadTime={2000}
fallback={<Text text="Loading B..." />}>
<Text text="B" />
<div>
<Suspense
unstable_expectedLoadTime={2000}
fallback={<Text text="Loading C..." />}>
<Text text="C" />
</Suspense>
</div>
</Suspense>
</div>
</>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
// Each level commits separately
assertLog(['A', 'Loading B...', 'B', 'Loading C...', 'C']);
expect(root).toMatchRenderedOutput(
<>
A
<div>
B<div>C</div>
</div>
</>,
);
});
});
| 22.640678 | 67 | 0.486161 |
null | /**
* 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';
export * from './src/useSubscription';
| 18.923077 | 66 | 0.686047 |
owtf | import Fixture from '../../Fixture';
const React = window.React;
class ReplaceEmailInput extends React.Component {
state = {
formSubmitted: false,
};
onReset = () => {
this.setState({formSubmitted: false});
};
onSubmit = event => {
event.preventDefault();
this.setState({formSubmitted: true});
};
render() {
return (
<Fixture>
<form className="control-box" onSubmit={this.onSubmit}>
<fieldset>
<legend>Email</legend>
{!this.state.formSubmitted ? (
<input type="email" />
) : (
<input type="text" disabled={true} />
)}
</fieldset>
</form>
<button type="button" onClick={this.onReset}>
Reset
</button>
</Fixture>
);
}
}
export default ReplaceEmailInput;
| 19.707317 | 63 | 0.53184 |
PenetrationTestingScripts | 'use strict';
/** @flow */
async function addItem(page, newItemText) {
await page.evaluate(text => {
const {createTestNameSelector, findAllNodes} = window.REACT_DOM_APP;
const container = document.getElementById('iframe').contentDocument;
const input = findAllNodes(container, [
createTestNameSelector('AddItemInput'),
])[0];
input.value = text;
const button = findAllNodes(container, [
createTestNameSelector('AddItemButton'),
])[0];
button.click();
}, newItemText);
}
module.exports = {
addItem,
};
| 20.461538 | 72 | 0.667864 |
cybersecurity-penetration-testing | /**
* 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
* @jest-environment node
*/
'use strict';
let React;
let ReactDOMServer;
let ReactDOMServerBrowser;
describe('ReactServerRenderingBrowser', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOMServer = require('react-dom/server');
// For extra isolation between what would be two bundles on npm
jest.resetModules();
ReactDOMServerBrowser = require('react-dom/server.browser');
});
it('returns the same results as react-dom/server', () => {
class Nice extends React.Component {
render() {
return <h2>I am feeling very good today, thanks, how are you?</h2>;
}
}
function Greeting() {
return (
<div>
<h1>How are you?</h1>
<Nice />
</div>
);
}
expect(ReactDOMServerBrowser.renderToString(<Greeting />)).toEqual(
ReactDOMServer.renderToString(<Greeting />),
);
expect(ReactDOMServerBrowser.renderToStaticMarkup(<Greeting />)).toEqual(
ReactDOMServer.renderToStaticMarkup(<Greeting />),
);
});
it('throws meaningfully for server-only APIs', () => {
expect(() => ReactDOMServerBrowser.renderToNodeStream(<div />)).toThrow(
'ReactDOMServer.renderToNodeStream(): The streaming API is not available ' +
'in the browser. Use ReactDOMServer.renderToString() instead.',
);
expect(() =>
ReactDOMServerBrowser.renderToStaticNodeStream(<div />),
).toThrow(
'ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' +
'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.',
);
});
});
| 28.935484 | 88 | 0.650674 |
Python-Penetration-Testing-for-Developers | /**
* 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
* @jest-environment node
*/
/* eslint-disable no-func-assign */
'use strict';
let React;
let textCache;
let readText;
let resolveText;
let ReactNoop;
let Scheduler;
let Suspense;
let useState;
let useReducer;
let useEffect;
let useInsertionEffect;
let useLayoutEffect;
let useCallback;
let useMemo;
let useRef;
let useImperativeHandle;
let useTransition;
let useDeferredValue;
let forwardRef;
let memo;
let act;
let ContinuousEventPriority;
let SuspenseList;
let waitForAll;
let waitFor;
let waitForThrow;
let waitForPaint;
let assertLog;
describe('ReactHooksWithNoopRenderer', () => {
beforeEach(() => {
jest.resetModules();
jest.useFakeTimers();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
useState = React.useState;
useReducer = React.useReducer;
useEffect = React.useEffect;
useInsertionEffect = React.useInsertionEffect;
useLayoutEffect = React.useLayoutEffect;
useCallback = React.useCallback;
useMemo = React.useMemo;
useRef = React.useRef;
useImperativeHandle = React.useImperativeHandle;
forwardRef = React.forwardRef;
memo = React.memo;
useTransition = React.useTransition;
useDeferredValue = React.useDeferredValue;
Suspense = React.Suspense;
ContinuousEventPriority =
require('react-reconciler/constants').ContinuousEventPriority;
if (gate(flags => flags.enableSuspenseList)) {
SuspenseList = React.unstable_SuspenseList;
}
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
waitFor = InternalTestUtils.waitFor;
waitForThrow = InternalTestUtils.waitForThrow;
waitForPaint = InternalTestUtils.waitForPaint;
assertLog = InternalTestUtils.assertLog;
textCache = new Map();
readText = text => {
const record = textCache.get(text);
if (record !== undefined) {
switch (record.status) {
case 'pending':
throw record.promise;
case 'rejected':
throw Error('Failed to load: ' + text);
case 'resolved':
return text;
}
} else {
let ping;
const promise = new Promise(resolve => (ping = resolve));
const newRecord = {
status: 'pending',
ping: ping,
promise,
};
textCache.set(text, newRecord);
throw promise;
}
};
resolveText = text => {
const record = textCache.get(text);
if (record !== undefined) {
if (record.status === 'pending') {
Scheduler.log(`Promise resolved [${text}]`);
record.ping();
record.ping = null;
record.status = 'resolved';
clearTimeout(record.promise._timer);
record.promise = null;
}
} else {
const newRecord = {
ping: null,
status: 'resolved',
promise: null,
};
textCache.set(text, newRecord);
}
};
});
function Text(props) {
Scheduler.log(props.text);
return <span prop={props.text} />;
}
function AsyncText(props) {
const text = props.text;
try {
readText(text);
Scheduler.log(text);
return <span prop={text} />;
} catch (promise) {
if (typeof promise.then === 'function') {
Scheduler.log(`Suspend! [${text}]`);
if (typeof props.ms === 'number' && promise._timer === undefined) {
promise._timer = setTimeout(() => {
resolveText(text);
}, props.ms);
}
} else {
Scheduler.log(`Error! [${text}]`);
}
throw promise;
}
}
function advanceTimers(ms) {
// Note: This advances Jest's virtual time but not React's. Use
// ReactNoop.expire for that.
if (typeof ms !== 'number') {
throw new Error('Must specify ms');
}
jest.advanceTimersByTime(ms);
// Wait until the end of the current tick
// We cannot use a timer since we're faking them
return Promise.resolve().then(() => {});
}
it('resumes after an interruption', async () => {
function Counter(props, ref) {
const [count, updateCount] = useState(0);
useImperativeHandle(ref, () => ({updateCount}));
return <Text text={props.label + ': ' + count} />;
}
Counter = forwardRef(Counter);
// Initial mount
const counter = React.createRef(null);
ReactNoop.render(<Counter label="Count" ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
// Schedule some updates
await act(async () => {
React.startTransition(() => {
counter.current.updateCount(1);
counter.current.updateCount(count => count + 10);
});
// Partially flush without committing
await waitFor(['Count: 11']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
// Interrupt with a high priority update
ReactNoop.flushSync(() => {
ReactNoop.render(<Counter label="Total" />);
});
assertLog(['Total: 0']);
// Resume rendering
await waitForAll(['Total: 11']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Total: 11" />);
});
});
it('throws inside class components', async () => {
class BadCounter extends React.Component {
render() {
const [count] = useState(0);
return <Text text={this.props.label + ': ' + count} />;
}
}
ReactNoop.render(<BadCounter />);
await waitForThrow(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
' one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
);
// Confirm that a subsequent hook works properly.
function GoodCounter(props, ref) {
const [count] = useState(props.initialCount);
return <Text text={count} />;
}
ReactNoop.render(<GoodCounter initialCount={10} />);
await waitForAll([10]);
});
// @gate !disableModulePatternComponents
it('throws inside module-style components', async () => {
function Counter() {
return {
render() {
const [count] = useState(0);
return <Text text={this.props.label + ': ' + count} />;
},
};
}
ReactNoop.render(<Counter />);
await expect(
async () =>
await waitForThrow(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen ' +
'for one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
),
).toErrorDev(
'Warning: The <Counter /> component appears to be a function component that returns a class instance. ' +
'Change Counter to a class that extends React.Component instead. ' +
"If you can't use a class try assigning the prototype on the function as a workaround. " +
'`Counter.prototype = React.Component.prototype`. ' +
"Don't use an arrow function since it cannot be called with `new` by React.",
);
// Confirm that a subsequent hook works properly.
function GoodCounter(props) {
const [count] = useState(props.initialCount);
return <Text text={count} />;
}
ReactNoop.render(<GoodCounter initialCount={10} />);
await waitForAll([10]);
});
it('throws when called outside the render phase', async () => {
expect(() => {
expect(() => useState(0)).toThrow(
"Cannot read property 'useState' of null",
);
}).toErrorDev(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
' one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
{withoutStack: true},
);
});
describe('useState', () => {
it('simple mount and update', async () => {
function Counter(props, ref) {
const [count, updateCount] = useState(0);
useImperativeHandle(ref, () => ({updateCount}));
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
await act(() => counter.current.updateCount(1));
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
await act(() => counter.current.updateCount(count => count + 10));
assertLog(['Count: 11']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 11" />);
});
it('lazy state initializer', async () => {
function Counter(props, ref) {
const [count, updateCount] = useState(() => {
Scheduler.log('getInitialState');
return props.initialState;
});
useImperativeHandle(ref, () => ({updateCount}));
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter initialState={42} ref={counter} />);
await waitForAll(['getInitialState', 'Count: 42']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 42" />);
await act(() => counter.current.updateCount(7));
assertLog(['Count: 7']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 7" />);
});
it('multiple states', async () => {
function Counter(props, ref) {
const [count, updateCount] = useState(0);
const [label, updateLabel] = useState('Count');
useImperativeHandle(ref, () => ({updateCount, updateLabel}));
return <Text text={label + ': ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
await act(() => counter.current.updateCount(7));
assertLog(['Count: 7']);
await act(() => counter.current.updateLabel('Total'));
assertLog(['Total: 7']);
});
it('returns the same updater function every time', async () => {
let updater = null;
function Counter() {
const [count, updateCount] = useState(0);
updater = updateCount;
return <Text text={'Count: ' + count} />;
}
ReactNoop.render(<Counter />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
const firstUpdater = updater;
await act(() => firstUpdater(1));
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
const secondUpdater = updater;
await act(() => firstUpdater(count => count + 10));
assertLog(['Count: 11']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 11" />);
expect(firstUpdater).toBe(secondUpdater);
});
it('does not warn on set after unmount', async () => {
let _updateCount;
function Counter(props, ref) {
const [, updateCount] = useState(0);
_updateCount = updateCount;
return null;
}
ReactNoop.render(<Counter />);
await waitForAll([]);
ReactNoop.render(null);
await waitForAll([]);
await act(() => _updateCount(1));
});
it('works with memo', async () => {
let _updateCount;
function Counter(props) {
const [count, updateCount] = useState(0);
_updateCount = updateCount;
return <Text text={'Count: ' + count} />;
}
Counter = memo(Counter);
ReactNoop.render(<Counter />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
ReactNoop.render(<Counter />);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
await act(() => _updateCount(1));
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
});
describe('updates during the render phase', () => {
it('restarts the render function and applies the new updates on top', async () => {
function ScrollView({row: newRow}) {
const [isScrollingDown, setIsScrollingDown] = useState(false);
const [row, setRow] = useState(null);
if (row !== newRow) {
// Row changed since last render. Update isScrollingDown.
setIsScrollingDown(row !== null && newRow > row);
setRow(newRow);
}
return <Text text={`Scrolling down: ${isScrollingDown}`} />;
}
ReactNoop.render(<ScrollView row={1} />);
await waitForAll(['Scrolling down: false']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Scrolling down: false" />,
);
ReactNoop.render(<ScrollView row={5} />);
await waitForAll(['Scrolling down: true']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Scrolling down: true" />,
);
ReactNoop.render(<ScrollView row={5} />);
await waitForAll(['Scrolling down: true']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Scrolling down: true" />,
);
ReactNoop.render(<ScrollView row={10} />);
await waitForAll(['Scrolling down: true']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Scrolling down: true" />,
);
ReactNoop.render(<ScrollView row={2} />);
await waitForAll(['Scrolling down: false']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Scrolling down: false" />,
);
ReactNoop.render(<ScrollView row={2} />);
await waitForAll(['Scrolling down: false']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Scrolling down: false" />,
);
});
it('warns about render phase update on a different component', async () => {
let setStep;
function Foo() {
const [step, _setStep] = useState(0);
setStep = _setStep;
return <Text text={`Foo [${step}]`} />;
}
function Bar({triggerUpdate}) {
if (triggerUpdate) {
setStep(x => x + 1);
}
return <Text text="Bar" />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(
<>
<Foo />
<Bar />
</>,
);
});
assertLog(['Foo [0]', 'Bar']);
// Bar will update Foo during its render phase. React should warn.
root.render(
<>
<Foo />
<Bar triggerUpdate={true} />
</>,
);
await expect(
async () => await waitForAll(['Foo [0]', 'Bar', 'Foo [1]']),
).toErrorDev([
'Cannot update a component (`Foo`) while rendering a ' +
'different component (`Bar`). To locate the bad setState() call inside `Bar`',
]);
// It should not warn again (deduplication).
await act(async () => {
root.render(
<>
<Foo />
<Bar triggerUpdate={true} />
</>,
);
await waitForAll(['Foo [1]', 'Bar', 'Foo [2]']);
});
});
it('keeps restarting until there are no more new updates', async () => {
function Counter({row: newRow}) {
const [count, setCount] = useState(0);
if (count < 3) {
setCount(count + 1);
}
Scheduler.log('Render: ' + count);
return <Text text={count} />;
}
ReactNoop.render(<Counter />);
await waitForAll(['Render: 0', 'Render: 1', 'Render: 2', 'Render: 3', 3]);
expect(ReactNoop).toMatchRenderedOutput(<span prop={3} />);
});
it('updates multiple times within same render function', async () => {
function Counter({row: newRow}) {
const [count, setCount] = useState(0);
if (count < 12) {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
Scheduler.log('Render: ' + count);
return <Text text={count} />;
}
ReactNoop.render(<Counter />);
await waitForAll([
// Should increase by three each time
'Render: 0',
'Render: 3',
'Render: 6',
'Render: 9',
'Render: 12',
12,
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop={12} />);
});
it('throws after too many iterations', async () => {
function Counter({row: newRow}) {
const [count, setCount] = useState(0);
setCount(count + 1);
Scheduler.log('Render: ' + count);
return <Text text={count} />;
}
ReactNoop.render(<Counter />);
await waitForThrow(
'Too many re-renders. React limits the number of renders to prevent ' +
'an infinite loop.',
);
});
it('works with useReducer', async () => {
function reducer(state, action) {
return action === 'increment' ? state + 1 : state;
}
function Counter({row: newRow}) {
const [count, dispatch] = useReducer(reducer, 0);
if (count < 3) {
dispatch('increment');
}
Scheduler.log('Render: ' + count);
return <Text text={count} />;
}
ReactNoop.render(<Counter />);
await waitForAll(['Render: 0', 'Render: 1', 'Render: 2', 'Render: 3', 3]);
expect(ReactNoop).toMatchRenderedOutput(<span prop={3} />);
});
it('uses reducer passed at time of render, not time of dispatch', async () => {
// This test is a bit contrived but it demonstrates a subtle edge case.
// Reducer A increments by 1. Reducer B increments by 10.
function reducerA(state, action) {
switch (action) {
case 'increment':
return state + 1;
case 'reset':
return 0;
}
}
function reducerB(state, action) {
switch (action) {
case 'increment':
return state + 10;
case 'reset':
return 0;
}
}
function Counter({row: newRow}, ref) {
const [reducer, setReducer] = useState(() => reducerA);
const [count, dispatch] = useReducer(reducer, 0);
useImperativeHandle(ref, () => ({dispatch}));
if (count < 20) {
dispatch('increment');
// Swap reducers each time we increment
if (reducer === reducerA) {
setReducer(() => reducerB);
} else {
setReducer(() => reducerA);
}
}
Scheduler.log('Render: ' + count);
return <Text text={count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll([
// The count should increase by alternating amounts of 10 and 1
// until we reach 21.
'Render: 0',
'Render: 10',
'Render: 11',
'Render: 21',
21,
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop={21} />);
// Test that it works on update, too. This time the log is a bit different
// because we started with reducerB instead of reducerA.
await act(() => {
counter.current.dispatch('reset');
});
ReactNoop.render(<Counter ref={counter} />);
assertLog([
'Render: 0',
'Render: 1',
'Render: 11',
'Render: 12',
'Render: 22',
22,
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop={22} />);
});
it('discards render phase updates if something suspends', async () => {
const thenable = {then() {}};
function Foo({signal}) {
return (
<Suspense fallback="Loading...">
<Bar signal={signal} />
</Suspense>
);
}
function Bar({signal: newSignal}) {
const [counter, setCounter] = useState(0);
const [signal, setSignal] = useState(true);
// Increment a counter every time the signal changes
if (signal !== newSignal) {
setCounter(c => c + 1);
setSignal(newSignal);
if (counter === 0) {
// We're suspending during a render that includes render phase
// updates. Those updates should not persist to the next render.
Scheduler.log('Suspend!');
throw thenable;
}
}
return <Text text={counter} />;
}
const root = ReactNoop.createRoot();
root.render(<Foo signal={true} />);
await waitForAll([0]);
expect(root).toMatchRenderedOutput(<span prop={0} />);
React.startTransition(() => {
root.render(<Foo signal={false} />);
});
await waitForAll(['Suspend!']);
expect(root).toMatchRenderedOutput(<span prop={0} />);
// Rendering again should suspend again.
React.startTransition(() => {
root.render(<Foo signal={false} />);
});
await waitForAll(['Suspend!']);
});
it('discards render phase updates if something suspends, but not other updates in the same component', async () => {
const thenable = {then() {}};
function Foo({signal}) {
return (
<Suspense fallback="Loading...">
<Bar signal={signal} />
</Suspense>
);
}
let setLabel;
function Bar({signal: newSignal}) {
const [counter, setCounter] = useState(0);
if (counter === 1) {
// We're suspending during a render that includes render phase
// updates. Those updates should not persist to the next render.
Scheduler.log('Suspend!');
throw thenable;
}
const [signal, setSignal] = useState(true);
// Increment a counter every time the signal changes
if (signal !== newSignal) {
setCounter(c => c + 1);
setSignal(newSignal);
}
const [label, _setLabel] = useState('A');
setLabel = _setLabel;
return <Text text={`${label}:${counter}`} />;
}
const root = ReactNoop.createRoot();
root.render(<Foo signal={true} />);
await waitForAll(['A:0']);
expect(root).toMatchRenderedOutput(<span prop="A:0" />);
await act(async () => {
React.startTransition(() => {
root.render(<Foo signal={false} />);
setLabel('B');
});
await waitForAll(['Suspend!']);
expect(root).toMatchRenderedOutput(<span prop="A:0" />);
// Rendering again should suspend again.
React.startTransition(() => {
root.render(<Foo signal={false} />);
});
await waitForAll(['Suspend!']);
// Flip the signal back to "cancel" the update. However, the update to
// label should still proceed. It shouldn't have been dropped.
React.startTransition(() => {
root.render(<Foo signal={true} />);
});
await waitForAll(['B:0']);
expect(root).toMatchRenderedOutput(<span prop="B:0" />);
});
});
it('regression: render phase updates cause lower pri work to be dropped', async () => {
let setRow;
function ScrollView() {
const [row, _setRow] = useState(10);
setRow = _setRow;
const [scrollDirection, setScrollDirection] = useState('Up');
const [prevRow, setPrevRow] = useState(null);
if (prevRow !== row) {
setScrollDirection(prevRow !== null && row > prevRow ? 'Down' : 'Up');
setPrevRow(row);
}
return <Text text={scrollDirection} />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<ScrollView row={10} />);
});
assertLog(['Up']);
expect(root).toMatchRenderedOutput(<span prop="Up" />);
await act(() => {
ReactNoop.discreteUpdates(() => {
setRow(5);
});
React.startTransition(() => {
setRow(20);
});
});
assertLog(['Up', 'Down']);
expect(root).toMatchRenderedOutput(<span prop="Down" />);
});
// TODO: This should probably warn
it('calling startTransition inside render phase', async () => {
function App() {
const [counter, setCounter] = useState(0);
if (counter === 0) {
React.startTransition(() => {
setCounter(c => c + 1);
});
}
return <Text text={counter} />;
}
const root = ReactNoop.createRoot();
root.render(<App />);
await waitForAll([1]);
expect(root).toMatchRenderedOutput(<span prop={1} />);
});
});
describe('useReducer', () => {
it('simple mount and update', async () => {
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
function reducer(state, action) {
switch (action) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
function Counter(props, ref) {
const [count, dispatch] = useReducer(reducer, 0);
useImperativeHandle(ref, () => ({dispatch}));
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
await act(() => counter.current.dispatch(INCREMENT));
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
await act(() => {
counter.current.dispatch(DECREMENT);
counter.current.dispatch(DECREMENT);
counter.current.dispatch(DECREMENT);
});
assertLog(['Count: -2']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: -2" />);
});
it('lazy init', async () => {
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
function reducer(state, action) {
switch (action) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
function Counter(props, ref) {
const [count, dispatch] = useReducer(reducer, props, p => {
Scheduler.log('Init');
return p.initialCount;
});
useImperativeHandle(ref, () => ({dispatch}));
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter initialCount={10} ref={counter} />);
await waitForAll(['Init', 'Count: 10']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 10" />);
await act(() => counter.current.dispatch(INCREMENT));
assertLog(['Count: 11']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 11" />);
await act(() => {
counter.current.dispatch(DECREMENT);
counter.current.dispatch(DECREMENT);
counter.current.dispatch(DECREMENT);
});
assertLog(['Count: 8']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 8" />);
});
// Regression test for https://github.com/facebook/react/issues/14360
it('handles dispatches with mixed priorities', async () => {
const INCREMENT = 'INCREMENT';
function reducer(state, action) {
return action === INCREMENT ? state + 1 : state;
}
function Counter(props, ref) {
const [count, dispatch] = useReducer(reducer, 0);
useImperativeHandle(ref, () => ({dispatch}));
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
ReactNoop.batchedUpdates(() => {
counter.current.dispatch(INCREMENT);
counter.current.dispatch(INCREMENT);
counter.current.dispatch(INCREMENT);
});
ReactNoop.flushSync(() => {
counter.current.dispatch(INCREMENT);
});
if (gate(flags => flags.enableUnifiedSyncLane)) {
assertLog(['Count: 4']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 4" />);
} else {
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
await waitForAll(['Count: 4']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 4" />);
}
});
});
describe('useEffect', () => {
it('simple mount and update', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Passive effect [${props.count}]`);
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
// Effects are deferred until after the commit
await waitForAll(['Passive effect [0]']);
});
await act(async () => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
// Effects are deferred until after the commit
await waitForAll(['Passive effect [1]']);
});
});
it('flushes passive effects even with sibling deletions', async () => {
function LayoutEffect(props) {
useLayoutEffect(() => {
Scheduler.log(`Layout effect`);
});
return <Text text="Layout" />;
}
function PassiveEffect(props) {
useEffect(() => {
Scheduler.log(`Passive effect`);
}, []);
return <Text text="Passive" />;
}
const passive = <PassiveEffect key="p" />;
await act(async () => {
ReactNoop.render([<LayoutEffect key="l" />, passive]);
await waitFor(['Layout', 'Passive', 'Layout effect']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Layout" />
<span prop="Passive" />
</>,
);
// Destroying the first child shouldn't prevent the passive effect from
// being executed
ReactNoop.render([passive]);
await waitForAll(['Passive effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Passive" />);
});
// exiting act calls flushPassiveEffects(), but there are none left to flush.
assertLog([]);
});
it('flushes passive effects even if siblings schedule an update', async () => {
function PassiveEffect(props) {
useEffect(() => {
Scheduler.log('Passive effect');
});
return <Text text="Passive" />;
}
function LayoutEffect(props) {
const [count, setCount] = useState(0);
useLayoutEffect(() => {
// Scheduling work shouldn't interfere with the queued passive effect
if (count === 0) {
setCount(1);
}
Scheduler.log('Layout effect ' + count);
});
return <Text text="Layout" />;
}
ReactNoop.render([<PassiveEffect key="p" />, <LayoutEffect key="l" />]);
await act(async () => {
await waitForAll([
'Passive',
'Layout',
'Layout effect 0',
'Passive effect',
'Layout',
'Layout effect 1',
]);
});
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Passive" />
<span prop="Layout" />
</>,
);
});
it('flushes passive effects even if siblings schedule a new root', async () => {
function PassiveEffect(props) {
useEffect(() => {
Scheduler.log('Passive effect');
}, []);
return <Text text="Passive" />;
}
function LayoutEffect(props) {
useLayoutEffect(() => {
Scheduler.log('Layout effect');
// Scheduling work shouldn't interfere with the queued passive effect
ReactNoop.renderToRootWithID(<Text text="New Root" />, 'root2');
});
return <Text text="Layout" />;
}
await act(async () => {
ReactNoop.render([<PassiveEffect key="p" />, <LayoutEffect key="l" />]);
await waitForAll([
'Passive',
'Layout',
'Layout effect',
'Passive effect',
'New Root',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Passive" />
<span prop="Layout" />
</>,
);
});
});
it(
'flushes effects serially by flushing old effects before flushing ' +
"new ones, if they haven't already fired",
async () => {
function getCommittedText() {
const children = ReactNoop.getChildrenAsJSX();
if (children === null) {
return null;
}
return children.props.prop;
}
function Counter(props) {
useEffect(() => {
Scheduler.log(
`Committed state when effect was fired: ${getCommittedText()}`,
);
});
return <Text text={props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor([0, 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop={0} />);
// Before the effects have a chance to flush, schedule another update
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor([
// The previous effect flushes before the reconciliation
'Committed state when effect was fired: 0',
1,
'Sync effect',
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop={1} />);
});
assertLog(['Committed state when effect was fired: 1']);
},
);
it('defers passive effect destroy functions during unmount', async () => {
function Child({bar, foo}) {
React.useEffect(() => {
Scheduler.log('passive bar create');
return () => {
Scheduler.log('passive bar destroy');
};
}, [bar]);
React.useLayoutEffect(() => {
Scheduler.log('layout bar create');
return () => {
Scheduler.log('layout bar destroy');
};
}, [bar]);
React.useEffect(() => {
Scheduler.log('passive foo create');
return () => {
Scheduler.log('passive foo destroy');
};
}, [foo]);
React.useLayoutEffect(() => {
Scheduler.log('layout foo create');
return () => {
Scheduler.log('layout foo destroy');
};
}, [foo]);
Scheduler.log('render');
return null;
}
await act(async () => {
ReactNoop.render(<Child bar={1} foo={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor([
'render',
'layout bar create',
'layout foo create',
'Sync effect',
]);
// Effects are deferred until after the commit
await waitForAll(['passive bar create', 'passive foo create']);
});
// This update exists to test an internal implementation detail:
// Effects without updating dependencies lose their layout/passive tag during an update.
await act(async () => {
ReactNoop.render(<Child bar={1} foo={2} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor([
'render',
'layout foo destroy',
'layout foo create',
'Sync effect',
]);
// Effects are deferred until after the commit
await waitForAll(['passive foo destroy', 'passive foo create']);
});
// Unmount the component and verify that passive destroy functions are deferred until post-commit.
await act(async () => {
ReactNoop.render(null, () => Scheduler.log('Sync effect'));
await waitFor([
'layout bar destroy',
'layout foo destroy',
'Sync effect',
]);
// Effects are deferred until after the commit
await waitForAll(['passive bar destroy', 'passive foo destroy']);
});
});
it('does not warn about state updates for unmounted components with pending passive unmounts', async () => {
let completePendingRequest = null;
function Component() {
Scheduler.log('Component');
const [didLoad, setDidLoad] = React.useState(false);
React.useLayoutEffect(() => {
Scheduler.log('layout create');
return () => {
Scheduler.log('layout destroy');
};
}, []);
React.useEffect(() => {
Scheduler.log('passive create');
// Mimic an XHR request with a complete handler that updates state.
completePendingRequest = () => setDidLoad(true);
return () => {
Scheduler.log('passive destroy');
};
}, []);
return didLoad;
}
await act(async () => {
ReactNoop.renderToRootWithID(<Component />, 'root', () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Component', 'layout create', 'Sync effect']);
ReactNoop.flushPassiveEffects();
assertLog(['passive create']);
// Unmount but don't process pending passive destroy function
ReactNoop.unmountRootWithID('root');
await waitFor(['layout destroy']);
// Simulate an XHR completing, which will cause a state update-
// but should not log a warning.
completePendingRequest();
ReactNoop.flushPassiveEffects();
assertLog(['passive destroy']);
});
});
it('does not warn about state updates for unmounted components with pending passive unmounts for alternates', async () => {
let setParentState = null;
const setChildStates = [];
function Parent() {
const [state, setState] = useState(true);
setParentState = setState;
Scheduler.log(`Parent ${state} render`);
useLayoutEffect(() => {
Scheduler.log(`Parent ${state} commit`);
});
if (state) {
return (
<>
<Child label="one" />
<Child label="two" />
</>
);
} else {
return null;
}
}
function Child({label}) {
const [state, setState] = useState(0);
useLayoutEffect(() => {
Scheduler.log(`Child ${label} commit`);
});
useEffect(() => {
setChildStates.push(setState);
Scheduler.log(`Child ${label} passive create`);
return () => {
Scheduler.log(`Child ${label} passive destroy`);
};
}, []);
Scheduler.log(`Child ${label} render`);
return state;
}
// Schedule debounced state update for child (prob a no-op for this test)
// later tick: schedule unmount for parent
// start process unmount (but don't flush passive effectS)
// State update on child
await act(async () => {
ReactNoop.render(<Parent />);
await waitFor([
'Parent true render',
'Child one render',
'Child two render',
'Child one commit',
'Child two commit',
'Parent true commit',
'Child one passive create',
'Child two passive create',
]);
// Update children.
setChildStates.forEach(setChildState => setChildState(1));
await waitFor([
'Child one render',
'Child two render',
'Child one commit',
'Child two commit',
]);
// Schedule another update for children, and partially process it.
React.startTransition(() => {
setChildStates.forEach(setChildState => setChildState(2));
});
await waitFor(['Child one render']);
// Schedule unmount for the parent that unmounts children with pending update.
ReactNoop.unstable_runWithPriority(ContinuousEventPriority, () => {
setParentState(false);
});
await waitForPaint(['Parent false render', 'Parent false commit']);
// Schedule updates for children too (which should be ignored)
setChildStates.forEach(setChildState => setChildState(2));
await waitForAll([
'Child one passive destroy',
'Child two passive destroy',
]);
});
});
it('does not warn about state updates for unmounted components with no pending passive unmounts', async () => {
let completePendingRequest = null;
function Component() {
Scheduler.log('Component');
const [didLoad, setDidLoad] = React.useState(false);
React.useLayoutEffect(() => {
Scheduler.log('layout create');
// Mimic an XHR request with a complete handler that updates state.
completePendingRequest = () => setDidLoad(true);
return () => {
Scheduler.log('layout destroy');
};
}, []);
return didLoad;
}
await act(async () => {
ReactNoop.renderToRootWithID(<Component />, 'root', () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Component', 'layout create', 'Sync effect']);
// Unmount but don't process pending passive destroy function
ReactNoop.unmountRootWithID('root');
await waitFor(['layout destroy']);
// Simulate an XHR completing.
completePendingRequest();
});
});
it('does not warn if there are pending passive unmount effects but not for the current fiber', async () => {
let completePendingRequest = null;
function ComponentWithXHR() {
Scheduler.log('Component');
const [didLoad, setDidLoad] = React.useState(false);
React.useLayoutEffect(() => {
Scheduler.log('a:layout create');
return () => {
Scheduler.log('a:layout destroy');
};
}, []);
React.useEffect(() => {
Scheduler.log('a:passive create');
// Mimic an XHR request with a complete handler that updates state.
completePendingRequest = () => setDidLoad(true);
}, []);
return didLoad;
}
function ComponentWithPendingPassiveUnmount() {
React.useEffect(() => {
Scheduler.log('b:passive create');
return () => {
Scheduler.log('b:passive destroy');
};
}, []);
return null;
}
await act(async () => {
ReactNoop.renderToRootWithID(
<>
<ComponentWithXHR />
<ComponentWithPendingPassiveUnmount />
</>,
'root',
() => Scheduler.log('Sync effect'),
);
await waitFor(['Component', 'a:layout create', 'Sync effect']);
ReactNoop.flushPassiveEffects();
assertLog(['a:passive create', 'b:passive create']);
// Unmount but don't process pending passive destroy function
ReactNoop.unmountRootWithID('root');
await waitFor(['a:layout destroy']);
// Simulate an XHR completing in the component without a pending passive effect..
completePendingRequest();
});
});
it('does not warn if there are updates after pending passive unmount effects have been flushed', async () => {
let updaterFunction;
function Component() {
Scheduler.log('Component');
const [state, setState] = React.useState(false);
updaterFunction = setState;
React.useEffect(() => {
Scheduler.log('passive create');
return () => {
Scheduler.log('passive destroy');
};
}, []);
return state;
}
await act(() => {
ReactNoop.renderToRootWithID(<Component />, 'root', () =>
Scheduler.log('Sync effect'),
);
});
assertLog(['Component', 'Sync effect', 'passive create']);
ReactNoop.unmountRootWithID('root');
await waitForAll(['passive destroy']);
await act(() => {
updaterFunction(true);
});
});
it('does not show a warning when a component updates its own state from within passive unmount function', async () => {
function Component() {
Scheduler.log('Component');
const [didLoad, setDidLoad] = React.useState(false);
React.useEffect(() => {
Scheduler.log('passive create');
return () => {
setDidLoad(true);
Scheduler.log('passive destroy');
};
}, []);
return didLoad;
}
await act(async () => {
ReactNoop.renderToRootWithID(<Component />, 'root', () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Component', 'Sync effect', 'passive create']);
// Unmount but don't process pending passive destroy function
ReactNoop.unmountRootWithID('root');
await waitForAll(['passive destroy']);
});
});
it('does not show a warning when a component updates a child state from within passive unmount function', async () => {
function Parent() {
Scheduler.log('Parent');
const updaterRef = useRef(null);
React.useEffect(() => {
Scheduler.log('Parent passive create');
return () => {
updaterRef.current(true);
Scheduler.log('Parent passive destroy');
};
}, []);
return <Child updaterRef={updaterRef} />;
}
function Child({updaterRef}) {
Scheduler.log('Child');
const [state, setState] = React.useState(false);
React.useEffect(() => {
Scheduler.log('Child passive create');
updaterRef.current = setState;
}, []);
return state;
}
await act(async () => {
ReactNoop.renderToRootWithID(<Parent />, 'root');
await waitFor([
'Parent',
'Child',
'Child passive create',
'Parent passive create',
]);
// Unmount but don't process pending passive destroy function
ReactNoop.unmountRootWithID('root');
await waitForAll(['Parent passive destroy']);
});
});
it('does not show a warning when a component updates a parents state from within passive unmount function', async () => {
function Parent() {
const [state, setState] = React.useState(false);
Scheduler.log('Parent');
return <Child setState={setState} state={state} />;
}
function Child({setState, state}) {
Scheduler.log('Child');
React.useEffect(() => {
Scheduler.log('Child passive create');
return () => {
Scheduler.log('Child passive destroy');
setState(true);
};
}, []);
return state;
}
await act(async () => {
ReactNoop.renderToRootWithID(<Parent />, 'root');
await waitFor(['Parent', 'Child', 'Child passive create']);
// Unmount but don't process pending passive destroy function
ReactNoop.unmountRootWithID('root');
await waitForAll(['Child passive destroy']);
});
});
it('updates have async priority', async () => {
function Counter(props) {
const [count, updateCount] = useState('(empty)');
useEffect(() => {
Scheduler.log(`Schedule update [${props.count}]`);
updateCount(props.count);
}, [props.count]);
return <Text text={'Count: ' + count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: (empty)', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: (empty)" />);
ReactNoop.flushPassiveEffects();
assertLog(['Schedule update [0]']);
await waitForAll(['Count: 0']);
});
await act(async () => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
ReactNoop.flushPassiveEffects();
assertLog(['Schedule update [1]']);
await waitForAll(['Count: 1']);
});
});
it('updates have async priority even if effects are flushed early', async () => {
function Counter(props) {
const [count, updateCount] = useState('(empty)');
useEffect(() => {
Scheduler.log(`Schedule update [${props.count}]`);
updateCount(props.count);
}, [props.count]);
return <Text text={'Count: ' + count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: (empty)', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: (empty)" />);
// Rendering again should flush the previous commit's effects
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
} else {
React.startTransition(() => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
});
}
await waitFor(['Schedule update [0]', 'Count: 0']);
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Count: (empty)" />,
);
await waitFor(['Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
ReactNoop.flushPassiveEffects();
assertLog(['Schedule update [1]']);
await waitForAll(['Count: 1']);
} else {
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
await waitFor([
'Count: 0',
'Sync effect',
'Schedule update [1]',
'Count: 1',
]);
}
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
});
it('does not flush non-discrete passive effects when flushing sync', async () => {
let _updateCount;
function Counter(props) {
const [count, updateCount] = useState(0);
_updateCount = updateCount;
useEffect(() => {
Scheduler.log(`Will set count to 1`);
updateCount(1);
}, []);
return <Text text={'Count: ' + count} />;
}
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
// A flush sync doesn't cause the passive effects to fire.
// So we haven't added the other update yet.
await act(() => {
ReactNoop.flushSync(() => {
_updateCount(2);
});
});
// As a result we, somewhat surprisingly, commit them in the opposite order.
// This should be fine because any non-discrete set of work doesn't guarantee order
// and easily could've happened slightly later too.
if (gate(flags => flags.enableUnifiedSyncLane)) {
assertLog(['Will set count to 1', 'Count: 1']);
} else {
assertLog(['Will set count to 1', 'Count: 2', 'Count: 1']);
}
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
it(
'in legacy mode, useEffect is deferred and updates finish synchronously ' +
'(in a single batch)',
async () => {
function Counter(props) {
const [count, updateCount] = useState('(empty)');
useEffect(() => {
// Update multiple times. These should all be batched together in
// a single render.
updateCount(props.count);
updateCount(props.count);
updateCount(props.count);
updateCount(props.count);
updateCount(props.count);
updateCount(props.count);
}, [props.count]);
return <Text text={'Count: ' + count} />;
}
await act(() => {
ReactNoop.flushSync(() => {
ReactNoop.renderLegacySyncRoot(<Counter count={0} />);
});
// Even in legacy mode, effects are deferred until after paint
assertLog(['Count: (empty)']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Count: (empty)" />,
);
});
// effects get forced on exiting act()
// There were multiple updates, but there should only be a
// single render
assertLog(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
},
);
it('flushSync is not allowed', async () => {
function Counter(props) {
const [count, updateCount] = useState('(empty)');
useEffect(() => {
Scheduler.log(`Schedule update [${props.count}]`);
ReactNoop.flushSync(() => {
updateCount(props.count);
});
assertLog([`Schedule update [${props.count}]`]);
// This shouldn't flush synchronously.
expect(ReactNoop).not.toMatchRenderedOutput(
<span prop={`Count: ${props.count}`} />,
);
}, [props.count]);
return <Text text={'Count: ' + count} />;
}
await expect(async () => {
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: (empty)', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Count: (empty)" />,
);
});
}).toErrorDev('flushSync was called from inside a lifecycle method');
assertLog([`Count: 0`]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
});
it('unmounts previous effect', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Did create [${props.count}]`);
return () => {
Scheduler.log(`Did destroy [${props.count}]`);
};
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
});
assertLog(['Did create [0]']);
await act(async () => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
assertLog(['Did destroy [0]', 'Did create [1]']);
});
it('unmounts on deletion', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Did create [${props.count}]`);
return () => {
Scheduler.log(`Did destroy [${props.count}]`);
};
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
});
assertLog(['Did create [0]']);
ReactNoop.render(null);
await waitForAll(['Did destroy [0]']);
expect(ReactNoop).toMatchRenderedOutput(null);
});
it('unmounts on deletion after skipped effect', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Did create [${props.count}]`);
return () => {
Scheduler.log(`Did destroy [${props.count}]`);
};
}, []);
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
});
assertLog(['Did create [0]']);
await act(async () => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
assertLog([]);
ReactNoop.render(null);
await waitForAll(['Did destroy [0]']);
expect(ReactNoop).toMatchRenderedOutput(null);
});
it('always fires effects if no dependencies are provided', async () => {
function effect() {
Scheduler.log(`Did create`);
return () => {
Scheduler.log(`Did destroy`);
};
}
function Counter(props) {
useEffect(effect);
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
});
assertLog(['Did create']);
await act(async () => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
assertLog(['Did destroy', 'Did create']);
ReactNoop.render(null);
await waitForAll(['Did destroy']);
expect(ReactNoop).toMatchRenderedOutput(null);
});
it('skips effect if inputs have not changed', async () => {
function Counter(props) {
const text = `${props.label}: ${props.count}`;
useEffect(() => {
Scheduler.log(`Did create [${text}]`);
return () => {
Scheduler.log(`Did destroy [${text}]`);
};
}, [props.label, props.count]);
return <Text text={text} />;
}
await act(async () => {
ReactNoop.render(<Counter label="Count" count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
});
assertLog(['Did create [Count: 0]']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
await act(async () => {
ReactNoop.render(<Counter label="Count" count={1} />, () =>
Scheduler.log('Sync effect'),
);
// Count changed
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
assertLog(['Did destroy [Count: 0]', 'Did create [Count: 1]']);
await act(async () => {
ReactNoop.render(<Counter label="Count" count={1} />, () =>
Scheduler.log('Sync effect'),
);
// Nothing changed, so no effect should have fired
await waitFor(['Count: 1', 'Sync effect']);
});
assertLog([]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
await act(async () => {
ReactNoop.render(<Counter label="Total" count={1} />, () =>
Scheduler.log('Sync effect'),
);
// Label changed
await waitFor(['Total: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Total: 1" />);
});
assertLog(['Did destroy [Count: 1]', 'Did create [Total: 1]']);
});
it('multiple effects', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Did commit 1 [${props.count}]`);
});
useEffect(() => {
Scheduler.log(`Did commit 2 [${props.count}]`);
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
});
assertLog(['Did commit 1 [0]', 'Did commit 2 [0]']);
await act(async () => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
assertLog(['Did commit 1 [1]', 'Did commit 2 [1]']);
});
it('unmounts all previous effects before creating any new ones', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Mount A [${props.count}]`);
return () => {
Scheduler.log(`Unmount A [${props.count}]`);
};
});
useEffect(() => {
Scheduler.log(`Mount B [${props.count}]`);
return () => {
Scheduler.log(`Unmount B [${props.count}]`);
};
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
});
assertLog(['Mount A [0]', 'Mount B [0]']);
await act(async () => {
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
});
assertLog([
'Unmount A [0]',
'Unmount B [0]',
'Mount A [1]',
'Mount B [1]',
]);
});
it('unmounts all previous effects between siblings before creating any new ones', async () => {
function Counter({count, label}) {
useEffect(() => {
Scheduler.log(`Mount ${label} [${count}]`);
return () => {
Scheduler.log(`Unmount ${label} [${count}]`);
};
});
return <Text text={`${label} ${count}`} />;
}
await act(async () => {
ReactNoop.render(
<>
<Counter label="A" count={0} />
<Counter label="B" count={0} />
</>,
() => Scheduler.log('Sync effect'),
);
await waitFor(['A 0', 'B 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A 0" />
<span prop="B 0" />
</>,
);
});
assertLog(['Mount A [0]', 'Mount B [0]']);
await act(async () => {
ReactNoop.render(
<>
<Counter label="A" count={1} />
<Counter label="B" count={1} />
</>,
() => Scheduler.log('Sync effect'),
);
await waitFor(['A 1', 'B 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A 1" />
<span prop="B 1" />
</>,
);
});
assertLog([
'Unmount A [0]',
'Unmount B [0]',
'Mount A [1]',
'Mount B [1]',
]);
await act(async () => {
ReactNoop.render(
<>
<Counter label="B" count={2} />
<Counter label="C" count={0} />
</>,
() => Scheduler.log('Sync effect'),
);
await waitFor(['B 2', 'C 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="B 2" />
<span prop="C 0" />
</>,
);
});
assertLog([
'Unmount A [1]',
'Unmount B [1]',
'Mount B [2]',
'Mount C [0]',
]);
});
it('handles errors in create on mount', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Mount A [${props.count}]`);
return () => {
Scheduler.log(`Unmount A [${props.count}]`);
};
});
useEffect(() => {
Scheduler.log('Oops!');
throw new Error('Oops!');
// eslint-disable-next-line no-unreachable
Scheduler.log(`Mount B [${props.count}]`);
return () => {
Scheduler.log(`Unmount B [${props.count}]`);
};
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
expect(() => ReactNoop.flushPassiveEffects()).toThrow('Oops');
});
assertLog([
'Mount A [0]',
'Oops!',
// Clean up effect A. There's no effect B to clean-up, because it
// never mounted.
'Unmount A [0]',
]);
expect(ReactNoop).toMatchRenderedOutput(null);
});
it('handles errors in create on update', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Mount A [${props.count}]`);
return () => {
Scheduler.log(`Unmount A [${props.count}]`);
};
});
useEffect(() => {
if (props.count === 1) {
Scheduler.log('Oops!');
throw new Error('Oops!');
}
Scheduler.log(`Mount B [${props.count}]`);
return () => {
Scheduler.log(`Unmount B [${props.count}]`);
};
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
ReactNoop.flushPassiveEffects();
assertLog(['Mount A [0]', 'Mount B [0]']);
});
await act(async () => {
// This update will trigger an error
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
expect(() => ReactNoop.flushPassiveEffects()).toThrow('Oops');
assertLog(['Unmount A [0]', 'Unmount B [0]', 'Mount A [1]', 'Oops!']);
expect(ReactNoop).toMatchRenderedOutput(null);
});
assertLog([
// Clean up effect A runs passively on unmount.
// There's no effect B to clean-up, because it never mounted.
'Unmount A [1]',
]);
});
it('handles errors in destroy on update', async () => {
function Counter(props) {
useEffect(() => {
Scheduler.log(`Mount A [${props.count}]`);
return () => {
Scheduler.log('Oops!');
if (props.count === 0) {
throw new Error('Oops!');
}
};
});
useEffect(() => {
Scheduler.log(`Mount B [${props.count}]`);
return () => {
Scheduler.log(`Unmount B [${props.count}]`);
};
});
return <Text text={'Count: ' + props.count} />;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
ReactNoop.flushPassiveEffects();
assertLog(['Mount A [0]', 'Mount B [0]']);
});
await act(async () => {
// This update will trigger an error during passive effect unmount
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
expect(() => ReactNoop.flushPassiveEffects()).toThrow('Oops');
// This branch enables a feature flag that flushes all passive destroys in a
// separate pass before flushing any passive creates.
// A result of this two-pass flush is that an error thrown from unmount does
// not block the subsequent create functions from being run.
assertLog(['Oops!', 'Unmount B [0]', 'Mount A [1]', 'Mount B [1]']);
});
// <Counter> gets unmounted because an error is thrown above.
// The remaining destroy functions are run later on unmount, since they're passive.
// In this case, one of them throws again (because of how the test is written).
assertLog(['Oops!', 'Unmount B [1]']);
expect(ReactNoop).toMatchRenderedOutput(null);
});
it('works with memo', async () => {
function Counter({count}) {
useLayoutEffect(() => {
Scheduler.log('Mount: ' + count);
return () => Scheduler.log('Unmount: ' + count);
});
return <Text text={'Count: ' + count} />;
}
Counter = memo(Counter);
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 0', 'Mount: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Count: 1', 'Unmount: 0', 'Mount: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
ReactNoop.render(null);
await waitFor(['Unmount: 1']);
expect(ReactNoop).toMatchRenderedOutput(null);
});
describe('errors thrown in passive destroy function within unmounted trees', () => {
let BrokenUseEffectCleanup;
let ErrorBoundary;
let LogOnlyErrorBoundary;
beforeEach(() => {
BrokenUseEffectCleanup = function () {
useEffect(() => {
Scheduler.log('BrokenUseEffectCleanup useEffect');
return () => {
Scheduler.log('BrokenUseEffectCleanup useEffect destroy');
throw new Error('Expected error');
};
}, []);
return 'inner child';
};
ErrorBoundary = class extends React.Component {
state = {error: null};
static getDerivedStateFromError(error) {
Scheduler.log(`ErrorBoundary static getDerivedStateFromError`);
return {error};
}
componentDidCatch(error, info) {
Scheduler.log(`ErrorBoundary componentDidCatch`);
}
render() {
if (this.state.error) {
Scheduler.log('ErrorBoundary render error');
return <span prop="ErrorBoundary fallback" />;
}
Scheduler.log('ErrorBoundary render success');
return this.props.children || null;
}
};
LogOnlyErrorBoundary = class extends React.Component {
componentDidCatch(error, info) {
Scheduler.log(`LogOnlyErrorBoundary componentDidCatch`);
}
render() {
Scheduler.log(`LogOnlyErrorBoundary render`);
return this.props.children || null;
}
};
});
it('should use the nearest still-mounted boundary if there are no unmounted boundaries', async () => {
await act(() => {
ReactNoop.render(
<LogOnlyErrorBoundary>
<BrokenUseEffectCleanup />
</LogOnlyErrorBoundary>,
);
});
assertLog([
'LogOnlyErrorBoundary render',
'BrokenUseEffectCleanup useEffect',
]);
await act(() => {
ReactNoop.render(<LogOnlyErrorBoundary />);
});
assertLog([
'LogOnlyErrorBoundary render',
'BrokenUseEffectCleanup useEffect destroy',
'LogOnlyErrorBoundary componentDidCatch',
]);
});
it('should skip unmounted boundaries and use the nearest still-mounted boundary', async () => {
function Conditional({showChildren}) {
if (showChildren) {
return (
<ErrorBoundary>
<BrokenUseEffectCleanup />
</ErrorBoundary>
);
} else {
return null;
}
}
await act(() => {
ReactNoop.render(
<LogOnlyErrorBoundary>
<Conditional showChildren={true} />
</LogOnlyErrorBoundary>,
);
});
assertLog([
'LogOnlyErrorBoundary render',
'ErrorBoundary render success',
'BrokenUseEffectCleanup useEffect',
]);
await act(() => {
ReactNoop.render(
<LogOnlyErrorBoundary>
<Conditional showChildren={false} />
</LogOnlyErrorBoundary>,
);
});
assertLog([
'LogOnlyErrorBoundary render',
'BrokenUseEffectCleanup useEffect destroy',
'LogOnlyErrorBoundary componentDidCatch',
]);
});
it('should call getDerivedStateFromError in the nearest still-mounted boundary', async () => {
function Conditional({showChildren}) {
if (showChildren) {
return <BrokenUseEffectCleanup />;
} else {
return null;
}
}
await act(() => {
ReactNoop.render(
<ErrorBoundary>
<Conditional showChildren={true} />
</ErrorBoundary>,
);
});
assertLog([
'ErrorBoundary render success',
'BrokenUseEffectCleanup useEffect',
]);
await act(() => {
ReactNoop.render(
<ErrorBoundary>
<Conditional showChildren={false} />
</ErrorBoundary>,
);
});
assertLog([
'ErrorBoundary render success',
'BrokenUseEffectCleanup useEffect destroy',
'ErrorBoundary static getDerivedStateFromError',
'ErrorBoundary render error',
'ErrorBoundary componentDidCatch',
]);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="ErrorBoundary fallback" />,
);
});
it('should rethrow error if there are no still-mounted boundaries', async () => {
function Conditional({showChildren}) {
if (showChildren) {
return (
<ErrorBoundary>
<BrokenUseEffectCleanup />
</ErrorBoundary>
);
} else {
return null;
}
}
await act(() => {
ReactNoop.render(<Conditional showChildren={true} />);
});
assertLog([
'ErrorBoundary render success',
'BrokenUseEffectCleanup useEffect',
]);
await act(async () => {
ReactNoop.render(<Conditional showChildren={false} />);
await waitForThrow('Expected error');
});
assertLog(['BrokenUseEffectCleanup useEffect destroy']);
expect(ReactNoop).toMatchRenderedOutput(null);
});
});
it('calls passive effect destroy functions for memoized components', async () => {
const Wrapper = ({children}) => children;
function Child() {
React.useEffect(() => {
Scheduler.log('passive create');
return () => {
Scheduler.log('passive destroy');
};
}, []);
React.useLayoutEffect(() => {
Scheduler.log('layout create');
return () => {
Scheduler.log('layout destroy');
};
}, []);
Scheduler.log('render');
return null;
}
const isEqual = (prevProps, nextProps) =>
prevProps.prop === nextProps.prop;
const MemoizedChild = React.memo(Child, isEqual);
await act(() => {
ReactNoop.render(
<Wrapper>
<MemoizedChild key={1} />
</Wrapper>,
);
});
assertLog(['render', 'layout create', 'passive create']);
// Include at least one no-op (memoized) update to trigger original bug.
await act(() => {
ReactNoop.render(
<Wrapper>
<MemoizedChild key={1} />
</Wrapper>,
);
});
assertLog([]);
await act(() => {
ReactNoop.render(
<Wrapper>
<MemoizedChild key={2} />
</Wrapper>,
);
});
assertLog([
'render',
'layout destroy',
'layout create',
'passive destroy',
'passive create',
]);
await act(() => {
ReactNoop.render(null);
});
assertLog(['layout destroy', 'passive destroy']);
});
it('calls passive effect destroy functions for descendants of memoized components', async () => {
const Wrapper = ({children}) => children;
function Child() {
return <Grandchild />;
}
function Grandchild() {
React.useEffect(() => {
Scheduler.log('passive create');
return () => {
Scheduler.log('passive destroy');
};
}, []);
React.useLayoutEffect(() => {
Scheduler.log('layout create');
return () => {
Scheduler.log('layout destroy');
};
}, []);
Scheduler.log('render');
return null;
}
const isEqual = (prevProps, nextProps) =>
prevProps.prop === nextProps.prop;
const MemoizedChild = React.memo(Child, isEqual);
await act(() => {
ReactNoop.render(
<Wrapper>
<MemoizedChild key={1} />
</Wrapper>,
);
});
assertLog(['render', 'layout create', 'passive create']);
// Include at least one no-op (memoized) update to trigger original bug.
await act(() => {
ReactNoop.render(
<Wrapper>
<MemoizedChild key={1} />
</Wrapper>,
);
});
assertLog([]);
await act(() => {
ReactNoop.render(
<Wrapper>
<MemoizedChild key={2} />
</Wrapper>,
);
});
assertLog([
'render',
'layout destroy',
'layout create',
'passive destroy',
'passive create',
]);
await act(() => {
ReactNoop.render(null);
});
assertLog(['layout destroy', 'passive destroy']);
});
it('assumes passive effect destroy function is either a function or undefined', async () => {
function App(props) {
useEffect(() => {
return props.return;
});
return null;
}
const root1 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root1.render(<App return={17} />);
});
}).toErrorDev([
'Warning: useEffect must not return anything besides a ' +
'function, which is used for clean-up. You returned: 17',
]);
const root2 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root2.render(<App return={null} />);
});
}).toErrorDev([
'Warning: useEffect must not return anything besides a ' +
'function, which is used for clean-up. You returned null. If your ' +
'effect does not require clean up, return undefined (or nothing).',
]);
const root3 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root3.render(<App return={Promise.resolve()} />);
});
}).toErrorDev([
'Warning: useEffect must not return anything besides a ' +
'function, which is used for clean-up.\n\n' +
'It looks like you wrote useEffect(async () => ...) or returned a Promise.',
]);
// Error on unmount because React assumes the value is a function
await act(async () => {
root3.render(null);
await waitForThrow('is not a function');
});
});
});
describe('useInsertionEffect', () => {
it('fires insertion effects after snapshots on update', async () => {
function CounterA(props) {
useInsertionEffect(() => {
Scheduler.log(`Create insertion`);
return () => {
Scheduler.log(`Destroy insertion`);
};
});
return null;
}
class CounterB extends React.Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
Scheduler.log(`Get Snapshot`);
return null;
}
componentDidUpdate() {}
render() {
return null;
}
}
await act(async () => {
ReactNoop.render(
<>
<CounterA />
<CounterB />
</>,
);
await waitForAll(['Create insertion']);
});
// Update
await act(async () => {
ReactNoop.render(
<>
<CounterA />
<CounterB />
</>,
);
await waitForAll([
'Get Snapshot',
'Destroy insertion',
'Create insertion',
]);
});
// Unmount everything
await act(async () => {
ReactNoop.render(null);
await waitForAll(['Destroy insertion']);
});
});
it('fires insertion effects before layout effects', async () => {
let committedText = '(empty)';
function Counter(props) {
useInsertionEffect(() => {
Scheduler.log(`Create insertion [current: ${committedText}]`);
committedText = String(props.count);
return () => {
Scheduler.log(`Destroy insertion [current: ${committedText}]`);
};
});
useLayoutEffect(() => {
Scheduler.log(`Create layout [current: ${committedText}]`);
return () => {
Scheduler.log(`Destroy layout [current: ${committedText}]`);
};
});
useEffect(() => {
Scheduler.log(`Create passive [current: ${committedText}]`);
return () => {
Scheduler.log(`Destroy passive [current: ${committedText}]`);
};
});
return null;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />);
await waitForPaint([
'Create insertion [current: (empty)]',
'Create layout [current: 0]',
]);
expect(committedText).toEqual('0');
});
assertLog(['Create passive [current: 0]']);
// Unmount everything
await act(async () => {
ReactNoop.render(null);
await waitForPaint([
'Destroy insertion [current: 0]',
'Destroy layout [current: 0]',
]);
});
assertLog(['Destroy passive [current: 0]']);
});
it('force flushes passive effects before firing new insertion effects', async () => {
let committedText = '(empty)';
function Counter(props) {
useInsertionEffect(() => {
Scheduler.log(`Create insertion [current: ${committedText}]`);
committedText = String(props.count);
return () => {
Scheduler.log(`Destroy insertion [current: ${committedText}]`);
};
});
useLayoutEffect(() => {
Scheduler.log(`Create layout [current: ${committedText}]`);
committedText = String(props.count);
return () => {
Scheduler.log(`Destroy layout [current: ${committedText}]`);
};
});
useEffect(() => {
Scheduler.log(`Create passive [current: ${committedText}]`);
return () => {
Scheduler.log(`Destroy passive [current: ${committedText}]`);
};
});
return null;
}
await act(async () => {
React.startTransition(() => {
ReactNoop.render(<Counter count={0} />);
});
await waitForPaint([
'Create insertion [current: (empty)]',
'Create layout [current: 0]',
]);
expect(committedText).toEqual('0');
React.startTransition(() => {
ReactNoop.render(<Counter count={1} />);
});
await waitForPaint([
'Create passive [current: 0]',
'Destroy insertion [current: 0]',
'Create insertion [current: 0]',
'Destroy layout [current: 1]',
'Create layout [current: 1]',
]);
expect(committedText).toEqual('1');
});
assertLog([
'Destroy passive [current: 1]',
'Create passive [current: 1]',
]);
});
it('fires all insertion effects (interleaved) before firing any layout effects', async () => {
let committedA = '(empty)';
let committedB = '(empty)';
function CounterA(props) {
useInsertionEffect(() => {
Scheduler.log(
`Create Insertion 1 for Component A [A: ${committedA}, B: ${committedB}]`,
);
committedA = String(props.count);
return () => {
Scheduler.log(
`Destroy Insertion 1 for Component A [A: ${committedA}, B: ${committedB}]`,
);
};
});
useInsertionEffect(() => {
Scheduler.log(
`Create Insertion 2 for Component A [A: ${committedA}, B: ${committedB}]`,
);
committedA = String(props.count);
return () => {
Scheduler.log(
`Destroy Insertion 2 for Component A [A: ${committedA}, B: ${committedB}]`,
);
};
});
useLayoutEffect(() => {
Scheduler.log(
`Create Layout 1 for Component A [A: ${committedA}, B: ${committedB}]`,
);
return () => {
Scheduler.log(
`Destroy Layout 1 for Component A [A: ${committedA}, B: ${committedB}]`,
);
};
});
useLayoutEffect(() => {
Scheduler.log(
`Create Layout 2 for Component A [A: ${committedA}, B: ${committedB}]`,
);
return () => {
Scheduler.log(
`Destroy Layout 2 for Component A [A: ${committedA}, B: ${committedB}]`,
);
};
});
return null;
}
function CounterB(props) {
useInsertionEffect(() => {
Scheduler.log(
`Create Insertion 1 for Component B [A: ${committedA}, B: ${committedB}]`,
);
committedB = String(props.count);
return () => {
Scheduler.log(
`Destroy Insertion 1 for Component B [A: ${committedA}, B: ${committedB}]`,
);
};
});
useInsertionEffect(() => {
Scheduler.log(
`Create Insertion 2 for Component B [A: ${committedA}, B: ${committedB}]`,
);
committedB = String(props.count);
return () => {
Scheduler.log(
`Destroy Insertion 2 for Component B [A: ${committedA}, B: ${committedB}]`,
);
};
});
useLayoutEffect(() => {
Scheduler.log(
`Create Layout 1 for Component B [A: ${committedA}, B: ${committedB}]`,
);
return () => {
Scheduler.log(
`Destroy Layout 1 for Component B [A: ${committedA}, B: ${committedB}]`,
);
};
});
useLayoutEffect(() => {
Scheduler.log(
`Create Layout 2 for Component B [A: ${committedA}, B: ${committedB}]`,
);
return () => {
Scheduler.log(
`Destroy Layout 2 for Component B [A: ${committedA}, B: ${committedB}]`,
);
};
});
return null;
}
await act(async () => {
ReactNoop.render(
<React.Fragment>
<CounterA count={0} />
<CounterB count={0} />
</React.Fragment>,
);
await waitForAll([
// All insertion effects fire before all layout effects
'Create Insertion 1 for Component A [A: (empty), B: (empty)]',
'Create Insertion 2 for Component A [A: 0, B: (empty)]',
'Create Insertion 1 for Component B [A: 0, B: (empty)]',
'Create Insertion 2 for Component B [A: 0, B: 0]',
'Create Layout 1 for Component A [A: 0, B: 0]',
'Create Layout 2 for Component A [A: 0, B: 0]',
'Create Layout 1 for Component B [A: 0, B: 0]',
'Create Layout 2 for Component B [A: 0, B: 0]',
]);
expect([committedA, committedB]).toEqual(['0', '0']);
});
await act(async () => {
ReactNoop.render(
<React.Fragment>
<CounterA count={1} />
<CounterB count={1} />
</React.Fragment>,
);
await waitForAll([
'Destroy Insertion 1 for Component A [A: 0, B: 0]',
'Destroy Insertion 2 for Component A [A: 0, B: 0]',
'Create Insertion 1 for Component A [A: 0, B: 0]',
'Create Insertion 2 for Component A [A: 1, B: 0]',
'Destroy Layout 1 for Component A [A: 1, B: 0]',
'Destroy Layout 2 for Component A [A: 1, B: 0]',
'Destroy Insertion 1 for Component B [A: 1, B: 0]',
'Destroy Insertion 2 for Component B [A: 1, B: 0]',
'Create Insertion 1 for Component B [A: 1, B: 0]',
'Create Insertion 2 for Component B [A: 1, B: 1]',
'Destroy Layout 1 for Component B [A: 1, B: 1]',
'Destroy Layout 2 for Component B [A: 1, B: 1]',
'Create Layout 1 for Component A [A: 1, B: 1]',
'Create Layout 2 for Component A [A: 1, B: 1]',
'Create Layout 1 for Component B [A: 1, B: 1]',
'Create Layout 2 for Component B [A: 1, B: 1]',
]);
expect([committedA, committedB]).toEqual(['1', '1']);
// Unmount everything
await act(async () => {
ReactNoop.render(null);
await waitForAll([
'Destroy Insertion 1 for Component A [A: 1, B: 1]',
'Destroy Insertion 2 for Component A [A: 1, B: 1]',
'Destroy Layout 1 for Component A [A: 1, B: 1]',
'Destroy Layout 2 for Component A [A: 1, B: 1]',
'Destroy Insertion 1 for Component B [A: 1, B: 1]',
'Destroy Insertion 2 for Component B [A: 1, B: 1]',
'Destroy Layout 1 for Component B [A: 1, B: 1]',
'Destroy Layout 2 for Component B [A: 1, B: 1]',
]);
});
});
});
it('assumes insertion effect destroy function is either a function or undefined', async () => {
function App(props) {
useInsertionEffect(() => {
return props.return;
});
return null;
}
const root1 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root1.render(<App return={17} />);
});
}).toErrorDev([
'Warning: useInsertionEffect must not return anything besides a ' +
'function, which is used for clean-up. You returned: 17',
]);
const root2 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root2.render(<App return={null} />);
});
}).toErrorDev([
'Warning: useInsertionEffect must not return anything besides a ' +
'function, which is used for clean-up. You returned null. If your ' +
'effect does not require clean up, return undefined (or nothing).',
]);
const root3 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root3.render(<App return={Promise.resolve()} />);
});
}).toErrorDev([
'Warning: useInsertionEffect must not return anything besides a ' +
'function, which is used for clean-up.\n\n' +
'It looks like you wrote useInsertionEffect(async () => ...) or returned a Promise.',
]);
// Error on unmount because React assumes the value is a function
await act(async () => {
root3.render(null);
await waitForThrow('is not a function');
});
});
it('warns when setState is called from insertion effect setup', async () => {
function App(props) {
const [, setX] = useState(0);
useInsertionEffect(() => {
setX(1);
if (props.throw) {
throw Error('No');
}
}, [props.throw]);
return null;
}
const root = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root.render(<App />);
});
}).toErrorDev(['Warning: useInsertionEffect must not schedule updates.']);
await act(async () => {
root.render(<App throw={true} />);
await waitForThrow('No');
});
// Should not warn for regular effects after throw.
function NotInsertion() {
const [, setX] = useState(0);
useEffect(() => {
setX(1);
}, []);
return null;
}
await act(() => {
root.render(<NotInsertion />);
});
});
it('warns when setState is called from insertion effect cleanup', async () => {
function App(props) {
const [, setX] = useState(0);
useInsertionEffect(() => {
if (props.throw) {
throw Error('No');
}
return () => {
setX(1);
};
}, [props.throw, props.foo]);
return null;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App foo="hello" />);
});
await expect(async () => {
await act(() => {
root.render(<App foo="goodbye" />);
});
}).toErrorDev(['Warning: useInsertionEffect must not schedule updates.']);
await act(async () => {
root.render(<App throw={true} />);
await waitForThrow('No');
});
// Should not warn for regular effects after throw.
function NotInsertion() {
const [, setX] = useState(0);
useEffect(() => {
setX(1);
}, []);
return null;
}
await act(() => {
root.render(<NotInsertion />);
});
});
});
describe('useLayoutEffect', () => {
it('fires layout effects after the host has been mutated', async () => {
function getCommittedText() {
const yields = Scheduler.unstable_clearLog();
const children = ReactNoop.getChildrenAsJSX();
Scheduler.log(yields);
if (children === null) {
return null;
}
return children.props.prop;
}
function Counter(props) {
useLayoutEffect(() => {
Scheduler.log(`Current: ${getCommittedText()}`);
});
return <Text text={props.count} />;
}
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor([[0], 'Current: 0', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop={0} />);
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor([[1], 'Current: 1', 'Sync effect']);
expect(ReactNoop).toMatchRenderedOutput(<span prop={1} />);
});
it('force flushes passive effects before firing new layout effects', async () => {
let committedText = '(empty)';
function Counter(props) {
useLayoutEffect(() => {
// Normally this would go in a mutation effect, but this test
// intentionally omits a mutation effect.
committedText = String(props.count);
Scheduler.log(`Mount layout [current: ${committedText}]`);
return () => {
Scheduler.log(`Unmount layout [current: ${committedText}]`);
};
});
useEffect(() => {
Scheduler.log(`Mount normal [current: ${committedText}]`);
return () => {
Scheduler.log(`Unmount normal [current: ${committedText}]`);
};
});
return null;
}
await act(async () => {
ReactNoop.render(<Counter count={0} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Mount layout [current: 0]', 'Sync effect']);
expect(committedText).toEqual('0');
ReactNoop.render(<Counter count={1} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor([
'Mount normal [current: 0]',
'Unmount layout [current: 0]',
'Mount layout [current: 1]',
'Sync effect',
]);
expect(committedText).toEqual('1');
});
assertLog(['Unmount normal [current: 1]', 'Mount normal [current: 1]']);
});
it('catches errors thrown in useLayoutEffect', async () => {
class ErrorBoundary extends React.Component {
state = {error: null};
static getDerivedStateFromError(error) {
Scheduler.log(`ErrorBoundary static getDerivedStateFromError`);
return {error};
}
render() {
const {children, id, fallbackID} = this.props;
const {error} = this.state;
if (error) {
Scheduler.log(`${id} render error`);
return <Component id={fallbackID} />;
}
Scheduler.log(`${id} render success`);
return children || null;
}
}
function Component({id}) {
Scheduler.log('Component render ' + id);
return <span prop={id} />;
}
function BrokenLayoutEffectDestroy() {
useLayoutEffect(() => {
return () => {
Scheduler.log('BrokenLayoutEffectDestroy useLayoutEffect destroy');
throw Error('Expected');
};
}, []);
Scheduler.log('BrokenLayoutEffectDestroy render');
return <span prop="broken" />;
}
ReactNoop.render(
<ErrorBoundary id="OuterBoundary" fallbackID="OuterFallback">
<Component id="sibling" />
<ErrorBoundary id="InnerBoundary" fallbackID="InnerFallback">
<BrokenLayoutEffectDestroy />
</ErrorBoundary>
</ErrorBoundary>,
);
await waitForAll([
'OuterBoundary render success',
'Component render sibling',
'InnerBoundary render success',
'BrokenLayoutEffectDestroy render',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="sibling" />
<span prop="broken" />
</>,
);
ReactNoop.render(
<ErrorBoundary id="OuterBoundary" fallbackID="OuterFallback">
<Component id="sibling" />
</ErrorBoundary>,
);
// React should skip over the unmounting boundary and find the nearest still-mounted boundary.
await waitForAll([
'OuterBoundary render success',
'Component render sibling',
'BrokenLayoutEffectDestroy useLayoutEffect destroy',
'ErrorBoundary static getDerivedStateFromError',
'OuterBoundary render error',
'Component render OuterFallback',
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="OuterFallback" />);
});
it('assumes layout effect destroy function is either a function or undefined', async () => {
function App(props) {
useLayoutEffect(() => {
return props.return;
});
return null;
}
const root1 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root1.render(<App return={17} />);
});
}).toErrorDev([
'Warning: useLayoutEffect must not return anything besides a ' +
'function, which is used for clean-up. You returned: 17',
]);
const root2 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root2.render(<App return={null} />);
});
}).toErrorDev([
'Warning: useLayoutEffect must not return anything besides a ' +
'function, which is used for clean-up. You returned null. If your ' +
'effect does not require clean up, return undefined (or nothing).',
]);
const root3 = ReactNoop.createRoot();
await expect(async () => {
await act(() => {
root3.render(<App return={Promise.resolve()} />);
});
}).toErrorDev([
'Warning: useLayoutEffect must not return anything besides a ' +
'function, which is used for clean-up.\n\n' +
'It looks like you wrote useLayoutEffect(async () => ...) or returned a Promise.',
]);
// Error on unmount because React assumes the value is a function
await act(async () => {
root3.render(null);
await waitForThrow('is not a function');
});
});
});
describe('useCallback', () => {
it('memoizes callback by comparing inputs', async () => {
class IncrementButton extends React.PureComponent {
increment = () => {
this.props.increment();
};
render() {
return <Text text="Increment" />;
}
}
function Counter({incrementBy}) {
const [count, updateCount] = useState(0);
const increment = useCallback(
() => updateCount(c => c + incrementBy),
[incrementBy],
);
return (
<>
<IncrementButton increment={increment} ref={button} />
<Text text={'Count: ' + count} />
</>
);
}
const button = React.createRef(null);
ReactNoop.render(<Counter incrementBy={1} />);
await waitForAll(['Increment', 'Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Increment" />
<span prop="Count: 0" />
</>,
);
await act(() => button.current.increment());
assertLog([
// Button should not re-render, because its props haven't changed
// 'Increment',
'Count: 1',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Increment" />
<span prop="Count: 1" />
</>,
);
// Increase the increment amount
ReactNoop.render(<Counter incrementBy={10} />);
await waitForAll([
// Inputs did change this time
'Increment',
'Count: 1',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Increment" />
<span prop="Count: 1" />
</>,
);
// Callback should have updated
await act(() => button.current.increment());
assertLog(['Count: 11']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Increment" />
<span prop="Count: 11" />
</>,
);
});
});
describe('useMemo', () => {
it('memoizes value by comparing to previous inputs', async () => {
function CapitalizedText(props) {
const text = props.text;
const capitalizedText = useMemo(() => {
Scheduler.log(`Capitalize '${text}'`);
return text.toUpperCase();
}, [text]);
return <Text text={capitalizedText} />;
}
ReactNoop.render(<CapitalizedText text="hello" />);
await waitForAll(["Capitalize 'hello'", 'HELLO']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="HELLO" />);
ReactNoop.render(<CapitalizedText text="hi" />);
await waitForAll(["Capitalize 'hi'", 'HI']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="HI" />);
ReactNoop.render(<CapitalizedText text="hi" />);
await waitForAll(['HI']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="HI" />);
ReactNoop.render(<CapitalizedText text="goodbye" />);
await waitForAll(["Capitalize 'goodbye'", 'GOODBYE']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="GOODBYE" />);
});
it('always re-computes if no inputs are provided', async () => {
function LazyCompute(props) {
const computed = useMemo(props.compute);
return <Text text={computed} />;
}
function computeA() {
Scheduler.log('compute A');
return 'A';
}
function computeB() {
Scheduler.log('compute B');
return 'B';
}
ReactNoop.render(<LazyCompute compute={computeA} />);
await waitForAll(['compute A', 'A']);
ReactNoop.render(<LazyCompute compute={computeA} />);
await waitForAll(['compute A', 'A']);
ReactNoop.render(<LazyCompute compute={computeA} />);
await waitForAll(['compute A', 'A']);
ReactNoop.render(<LazyCompute compute={computeB} />);
await waitForAll(['compute B', 'B']);
});
it('should not invoke memoized function during re-renders unless inputs change', async () => {
function LazyCompute(props) {
const computed = useMemo(
() => props.compute(props.input),
[props.input],
);
const [count, setCount] = useState(0);
if (count < 3) {
setCount(count + 1);
}
return <Text text={computed} />;
}
function compute(val) {
Scheduler.log('compute ' + val);
return val;
}
ReactNoop.render(<LazyCompute compute={compute} input="A" />);
await waitForAll(['compute A', 'A']);
ReactNoop.render(<LazyCompute compute={compute} input="A" />);
await waitForAll(['A']);
ReactNoop.render(<LazyCompute compute={compute} input="B" />);
await waitForAll(['compute B', 'B']);
});
});
describe('useImperativeHandle', () => {
it('does not update when deps are the same', async () => {
const INCREMENT = 'INCREMENT';
function reducer(state, action) {
return action === INCREMENT ? state + 1 : state;
}
function Counter(props, ref) {
const [count, dispatch] = useReducer(reducer, 0);
useImperativeHandle(ref, () => ({count, dispatch}), []);
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
expect(counter.current.count).toBe(0);
await act(() => {
counter.current.dispatch(INCREMENT);
});
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
// Intentionally not updated because of [] deps:
expect(counter.current.count).toBe(0);
});
// Regression test for https://github.com/facebook/react/issues/14782
it('automatically updates when deps are not specified', async () => {
const INCREMENT = 'INCREMENT';
function reducer(state, action) {
return action === INCREMENT ? state + 1 : state;
}
function Counter(props, ref) {
const [count, dispatch] = useReducer(reducer, 0);
useImperativeHandle(ref, () => ({count, dispatch}));
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
expect(counter.current.count).toBe(0);
await act(() => {
counter.current.dispatch(INCREMENT);
});
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
expect(counter.current.count).toBe(1);
});
it('updates when deps are different', async () => {
const INCREMENT = 'INCREMENT';
function reducer(state, action) {
return action === INCREMENT ? state + 1 : state;
}
let totalRefUpdates = 0;
function Counter(props, ref) {
const [count, dispatch] = useReducer(reducer, 0);
useImperativeHandle(
ref,
() => {
totalRefUpdates++;
return {count, dispatch};
},
[count],
);
return <Text text={'Count: ' + count} />;
}
Counter = forwardRef(Counter);
const counter = React.createRef(null);
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />);
expect(counter.current.count).toBe(0);
expect(totalRefUpdates).toBe(1);
await act(() => {
counter.current.dispatch(INCREMENT);
});
assertLog(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
expect(counter.current.count).toBe(1);
expect(totalRefUpdates).toBe(2);
// Update that doesn't change the ref dependencies
ReactNoop.render(<Counter ref={counter} />);
await waitForAll(['Count: 1']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />);
expect(counter.current.count).toBe(1);
expect(totalRefUpdates).toBe(2); // Should not increase since last time
});
});
describe('useTransition', () => {
it('delays showing loading state until after timeout', async () => {
let transition;
function App() {
const [show, setShow] = useState(false);
const [isPending, startTransition] = useTransition();
transition = () => {
startTransition(() => {
setShow(true);
});
};
return (
<Suspense
fallback={<Text text={`Loading... Pending: ${isPending}`} />}>
{show ? (
<AsyncText text={`After... Pending: ${isPending}`} />
) : (
<Text text={`Before... Pending: ${isPending}`} />
)}
</Suspense>
);
}
ReactNoop.render(<App />);
await waitForAll(['Before... Pending: false']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Before... Pending: false" />,
);
await act(async () => {
transition();
await waitForAll([
'Before... Pending: true',
'Suspend! [After... Pending: false]',
'Loading... Pending: false',
]);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Before... Pending: true" />,
);
Scheduler.unstable_advanceTime(500);
await advanceTimers(500);
// Even after a long amount of time, we still don't show a placeholder.
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Before... Pending: true" />,
);
await resolveText('After... Pending: false');
assertLog(['Promise resolved [After... Pending: false]']);
await waitForAll(['After... Pending: false']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="After... Pending: false" />,
);
});
});
});
describe('useDeferredValue', () => {
it('defers text value', async () => {
function TextBox({text}) {
return <AsyncText text={text} />;
}
let _setText;
function App() {
const [text, setText] = useState('A');
const deferredText = useDeferredValue(text);
_setText = setText;
return (
<>
<Text text={text} />
<Suspense fallback={<Text text={'Loading'} />}>
<TextBox text={deferredText} />
</Suspense>
</>
);
}
await act(() => {
ReactNoop.render(<App />);
});
assertLog(['A', 'Suspend! [A]', 'Loading']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading" />
</>,
);
await act(() => resolveText('A'));
assertLog(['Promise resolved [A]', 'A']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="A" />
</>,
);
await act(async () => {
_setText('B');
await waitForAll(['B', 'A', 'B', 'Suspend! [B]', 'Loading']);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="A" />
</>,
);
});
await act(async () => {
Scheduler.unstable_advanceTime(250);
await advanceTimers(250);
});
assertLog([]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="A" />
</>,
);
// Even after a long amount of time, we don't show a fallback
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="A" />
</>,
);
await act(async () => {
await resolveText('B');
});
assertLog(['Promise resolved [B]', 'B', 'B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="B" />
</>,
);
});
});
describe('progressive enhancement (not supported)', () => {
it('mount additional state', async () => {
let updateA;
let updateB;
// let updateC;
function App(props) {
const [A, _updateA] = useState(0);
const [B, _updateB] = useState(0);
updateA = _updateA;
updateB = _updateB;
let C;
if (props.loadC) {
useState(0);
} else {
C = '[not loaded]';
}
return <Text text={`A: ${A}, B: ${B}, C: ${C}`} />;
}
ReactNoop.render(<App loadC={false} />);
await waitForAll(['A: 0, B: 0, C: [not loaded]']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="A: 0, B: 0, C: [not loaded]" />,
);
await act(() => {
updateA(2);
updateB(3);
});
assertLog(['A: 2, B: 3, C: [not loaded]']);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="A: 2, B: 3, C: [not loaded]" />,
);
ReactNoop.render(<App loadC={true} />);
await expect(async () => {
await waitForThrow(
'Rendered more hooks than during the previous render.',
);
assertLog([]);
}).toErrorDev([
'Warning: React has detected a change in the order of Hooks called by App. ' +
'This will lead to bugs and errors if not fixed. For more information, ' +
'read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' +
' Previous render Next render\n' +
' ------------------------------------------------------\n' +
'1. useState useState\n' +
'2. useState useState\n' +
'3. undefined useState\n' +
' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n',
]);
// Uncomment if/when we support this again
// expect(ReactNoop).toMatchRenderedOutput(<span prop="A: 2, B: 3, C: 0" />]);
// updateC(4);
// expect(Scheduler).toFlushAndYield(['A: 2, B: 3, C: 4']);
// expect(ReactNoop).toMatchRenderedOutput(<span prop="A: 2, B: 3, C: 4" />]);
});
it('unmount state', async () => {
let updateA;
let updateB;
let updateC;
function App(props) {
const [A, _updateA] = useState(0);
const [B, _updateB] = useState(0);
updateA = _updateA;
updateB = _updateB;
let C;
if (props.loadC) {
const [_C, _updateC] = useState(0);
C = _C;
updateC = _updateC;
} else {
C = '[not loaded]';
}
return <Text text={`A: ${A}, B: ${B}, C: ${C}`} />;
}
ReactNoop.render(<App loadC={true} />);
await waitForAll(['A: 0, B: 0, C: 0']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A: 0, B: 0, C: 0" />);
await act(() => {
updateA(2);
updateB(3);
updateC(4);
});
assertLog(['A: 2, B: 3, C: 4']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A: 2, B: 3, C: 4" />);
ReactNoop.render(<App loadC={false} />);
await waitForThrow(
'Rendered fewer hooks than expected. This may be caused by an ' +
'accidental early return statement.',
);
});
it('unmount effects', async () => {
function App(props) {
useEffect(() => {
Scheduler.log('Mount A');
return () => {
Scheduler.log('Unmount A');
};
}, []);
if (props.showMore) {
useEffect(() => {
Scheduler.log('Mount B');
return () => {
Scheduler.log('Unmount B');
};
}, []);
}
return null;
}
await act(async () => {
ReactNoop.render(<App showMore={false} />, () =>
Scheduler.log('Sync effect'),
);
await waitFor(['Sync effect']);
});
assertLog(['Mount A']);
await act(async () => {
ReactNoop.render(<App showMore={true} />);
await expect(async () => {
await waitForThrow(
'Rendered more hooks than during the previous render.',
);
assertLog([]);
}).toErrorDev([
'Warning: React has detected a change in the order of Hooks called by App. ' +
'This will lead to bugs and errors if not fixed. For more information, ' +
'read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' +
' Previous render Next render\n' +
' ------------------------------------------------------\n' +
'1. useEffect useEffect\n' +
'2. undefined useEffect\n' +
' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n',
]);
});
// Uncomment if/when we support this again
// ReactNoop.flushPassiveEffects();
// expect(Scheduler).toHaveYielded(['Mount B']);
// ReactNoop.render(<App showMore={false} />);
// expect(Scheduler).toFlushAndThrow(
// 'Rendered fewer hooks than expected. This may be caused by an ' +
// 'accidental early return statement.',
// );
});
});
it('useReducer does not eagerly bail out of state updates', async () => {
// Edge case based on a bug report
let setCounter;
function App() {
const [counter, _setCounter] = useState(1);
setCounter = _setCounter;
return <Component count={counter} />;
}
function Component({count}) {
const [state, dispatch] = useReducer(() => {
// This reducer closes over a value from props. If the reducer is not
// properly updated, the eager reducer will compare to an old value
// and bail out incorrectly.
Scheduler.log('Reducer: ' + count);
return count;
}, -1);
useEffect(() => {
Scheduler.log('Effect: ' + count);
dispatch();
}, [count]);
Scheduler.log('Render: ' + state);
return count;
}
await act(async () => {
ReactNoop.render(<App />);
await waitForAll(['Render: -1', 'Effect: 1', 'Reducer: 1', 'Render: 1']);
expect(ReactNoop).toMatchRenderedOutput('1');
});
await act(() => {
setCounter(2);
});
assertLog(['Render: 1', 'Effect: 2', 'Reducer: 2', 'Render: 2']);
expect(ReactNoop).toMatchRenderedOutput('2');
});
it('useReducer does not replay previous no-op actions when other state changes', async () => {
let increment;
let setDisabled;
function Counter() {
const [disabled, _setDisabled] = useState(true);
const [count, dispatch] = useReducer((state, action) => {
if (disabled) {
return state;
}
if (action.type === 'increment') {
return state + 1;
}
return state;
}, 0);
increment = () => dispatch({type: 'increment'});
setDisabled = _setDisabled;
Scheduler.log('Render disabled: ' + disabled);
Scheduler.log('Render count: ' + count);
return count;
}
ReactNoop.render(<Counter />);
await waitForAll(['Render disabled: true', 'Render count: 0']);
expect(ReactNoop).toMatchRenderedOutput('0');
await act(() => {
// These increments should have no effect, since disabled=true
increment();
increment();
increment();
});
assertLog(['Render disabled: true', 'Render count: 0']);
expect(ReactNoop).toMatchRenderedOutput('0');
await act(() => {
// Enabling the updater should *not* replay the previous increment() actions
setDisabled(false);
});
assertLog(['Render disabled: false', 'Render count: 0']);
expect(ReactNoop).toMatchRenderedOutput('0');
});
it('useReducer does not replay previous no-op actions when props change', async () => {
let setDisabled;
let increment;
function Counter({disabled}) {
const [count, dispatch] = useReducer((state, action) => {
if (disabled) {
return state;
}
if (action.type === 'increment') {
return state + 1;
}
return state;
}, 0);
increment = () => dispatch({type: 'increment'});
Scheduler.log('Render count: ' + count);
return count;
}
function App() {
const [disabled, _setDisabled] = useState(true);
setDisabled = _setDisabled;
Scheduler.log('Render disabled: ' + disabled);
return <Counter disabled={disabled} />;
}
ReactNoop.render(<App />);
await waitForAll(['Render disabled: true', 'Render count: 0']);
expect(ReactNoop).toMatchRenderedOutput('0');
await act(() => {
// These increments should have no effect, since disabled=true
increment();
increment();
increment();
});
assertLog(['Render count: 0']);
expect(ReactNoop).toMatchRenderedOutput('0');
await act(() => {
// Enabling the updater should *not* replay the previous increment() actions
setDisabled(false);
});
assertLog(['Render disabled: false', 'Render count: 0']);
expect(ReactNoop).toMatchRenderedOutput('0');
});
it('useReducer applies potential no-op changes if made relevant by other updates in the batch', async () => {
let setDisabled;
let increment;
function Counter({disabled}) {
const [count, dispatch] = useReducer((state, action) => {
if (disabled) {
return state;
}
if (action.type === 'increment') {
return state + 1;
}
return state;
}, 0);
increment = () => dispatch({type: 'increment'});
Scheduler.log('Render count: ' + count);
return count;
}
function App() {
const [disabled, _setDisabled] = useState(true);
setDisabled = _setDisabled;
Scheduler.log('Render disabled: ' + disabled);
return <Counter disabled={disabled} />;
}
ReactNoop.render(<App />);
await waitForAll(['Render disabled: true', 'Render count: 0']);
expect(ReactNoop).toMatchRenderedOutput('0');
await act(() => {
// Although the increment happens first (and would seem to do nothing since disabled=true),
// because these calls are in a batch the parent updates first. This should cause the child
// to re-render with disabled=false and *then* process the increment action, which now
// increments the count and causes the component output to change.
increment();
setDisabled(false);
});
assertLog(['Render disabled: false', 'Render count: 1']);
expect(ReactNoop).toMatchRenderedOutput('1');
});
// Regression test. Covers a case where an internal state variable
// (`didReceiveUpdate`) is not reset properly.
it('state bail out edge case (#16359)', async () => {
let setCounterA;
let setCounterB;
function CounterA() {
const [counter, setCounter] = useState(0);
setCounterA = setCounter;
Scheduler.log('Render A: ' + counter);
useEffect(() => {
Scheduler.log('Commit A: ' + counter);
});
return counter;
}
function CounterB() {
const [counter, setCounter] = useState(0);
setCounterB = setCounter;
Scheduler.log('Render B: ' + counter);
useEffect(() => {
Scheduler.log('Commit B: ' + counter);
});
return counter;
}
const root = ReactNoop.createRoot(null);
await act(() => {
root.render(
<>
<CounterA />
<CounterB />
</>,
);
});
assertLog(['Render A: 0', 'Render B: 0', 'Commit A: 0', 'Commit B: 0']);
await act(() => {
setCounterA(1);
// In the same batch, update B twice. To trigger the condition we're
// testing, the first update is necessary to bypass the early
// bailout optimization.
setCounterB(1);
setCounterB(0);
});
assertLog([
'Render A: 1',
'Render B: 0',
'Commit A: 1',
// B should not fire an effect because the update bailed out
// 'Commit B: 0',
]);
});
it('should update latest rendered reducer when a preceding state receives a render phase update', async () => {
// Similar to previous test, except using a preceding render phase update
// instead of new props.
let dispatch;
function App() {
const [step, setStep] = useState(0);
const [shadow, _dispatch] = useReducer(() => step, step);
dispatch = _dispatch;
if (step < 5) {
setStep(step + 1);
}
Scheduler.log(`Step: ${step}, Shadow: ${shadow}`);
return shadow;
}
ReactNoop.render(<App />);
await waitForAll([
'Step: 0, Shadow: 0',
'Step: 1, Shadow: 0',
'Step: 2, Shadow: 0',
'Step: 3, Shadow: 0',
'Step: 4, Shadow: 0',
'Step: 5, Shadow: 0',
]);
expect(ReactNoop).toMatchRenderedOutput('0');
await act(() => dispatch());
assertLog(['Step: 5, Shadow: 5']);
expect(ReactNoop).toMatchRenderedOutput('5');
});
it('should process the rest pending updates after a render phase update', async () => {
// Similar to previous test, except using a preceding render phase update
// instead of new props.
let updateA;
let updateC;
function App() {
const [a, setA] = useState(false);
const [b, setB] = useState(false);
if (a !== b) {
setB(a);
}
// Even though we called setB above,
// we should still apply the changes to C,
// during this render pass.
const [c, setC] = useState(false);
updateA = setA;
updateC = setC;
return `${a ? 'A' : 'a'}${b ? 'B' : 'b'}${c ? 'C' : 'c'}`;
}
await act(() => ReactNoop.render(<App />));
expect(ReactNoop).toMatchRenderedOutput('abc');
await act(() => {
updateA(true);
// This update should not get dropped.
updateC(true);
});
expect(ReactNoop).toMatchRenderedOutput('ABC');
});
it("regression test: don't unmount effects on siblings of deleted nodes", async () => {
const root = ReactNoop.createRoot();
function Child({label}) {
useLayoutEffect(() => {
Scheduler.log('Mount layout ' + label);
return () => {
Scheduler.log('Unmount layout ' + label);
};
}, [label]);
useEffect(() => {
Scheduler.log('Mount passive ' + label);
return () => {
Scheduler.log('Unmount passive ' + label);
};
}, [label]);
return label;
}
await act(() => {
root.render(
<>
<Child key="A" label="A" />
<Child key="B" label="B" />
</>,
);
});
assertLog([
'Mount layout A',
'Mount layout B',
'Mount passive A',
'Mount passive B',
]);
// Delete A. This should only unmount the effect on A. In the regression,
// B's effect would also unmount.
await act(() => {
root.render(
<>
<Child key="B" label="B" />
</>,
);
});
assertLog(['Unmount layout A', 'Unmount passive A']);
// Now delete and unmount B.
await act(() => {
root.render(null);
});
assertLog(['Unmount layout B', 'Unmount passive B']);
});
it('regression: deleting a tree and unmounting its effects after a reorder', async () => {
const root = ReactNoop.createRoot();
function Child({label}) {
useEffect(() => {
Scheduler.log('Mount ' + label);
return () => {
Scheduler.log('Unmount ' + label);
};
}, [label]);
return label;
}
await act(() => {
root.render(
<>
<Child key="A" label="A" />
<Child key="B" label="B" />
</>,
);
});
assertLog(['Mount A', 'Mount B']);
await act(() => {
root.render(
<>
<Child key="B" label="B" />
<Child key="A" label="A" />
</>,
);
});
assertLog([]);
await act(() => {
root.render(null);
});
assertLog([
'Unmount B',
// In the regression, the reorder would cause Child A to "forget" that it
// contains passive effects. Then when we deleted the tree, A's unmount
// effect would not fire.
'Unmount A',
]);
});
// @gate enableSuspenseList
it('regression: SuspenseList causes unmounts to be dropped on deletion', async () => {
function Row({label}) {
useEffect(() => {
Scheduler.log('Mount ' + label);
return () => {
Scheduler.log('Unmount ' + label);
};
}, [label]);
return (
<Suspense fallback="Loading...">
<AsyncText text={label} />
</Suspense>
);
}
function App() {
return (
<SuspenseList revealOrder="together">
<Row label="A" />
<Row label="B" />
</SuspenseList>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['Suspend! [A]', 'Suspend! [B]', 'Mount A', 'Mount B']);
await act(async () => {
await resolveText('A');
});
assertLog(['Promise resolved [A]', 'A', 'Suspend! [B]']);
await act(() => {
root.render(null);
});
// In the regression, SuspenseList would cause the children to "forget" that
// it contains passive effects. Then when we deleted the tree, these unmount
// effects would not fire.
assertLog(['Unmount A', 'Unmount B']);
});
it('effect dependencies are persisted after a render phase update', async () => {
let handleClick;
function Test() {
const [count, setCount] = useState(0);
useEffect(() => {
Scheduler.log(`Effect: ${count}`);
}, [count]);
if (count > 0) {
setCount(0);
}
handleClick = () => setCount(2);
return <Text text={`Render: ${count}`} />;
}
await act(() => {
ReactNoop.render(<Test />);
});
assertLog(['Render: 0', 'Effect: 0']);
await act(() => {
handleClick();
});
assertLog(['Render: 0']);
await act(() => {
handleClick();
});
assertLog(['Render: 0']);
await act(() => {
handleClick();
});
assertLog(['Render: 0']);
});
});
| 30.269124 | 127 | 0.532299 |
null | /**
* 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 type {ImportManifestEntry} from './shared/ReactFlightImportMetadata';
import {join} from 'path';
import {pathToFileURL} from 'url';
import asyncLib from 'neo-async';
import * as acorn from 'acorn-loose';
import ModuleDependency from 'webpack/lib/dependencies/ModuleDependency';
import NullDependency from 'webpack/lib/dependencies/NullDependency';
import Template from 'webpack/lib/Template';
import {
sources,
WebpackError,
Compilation,
AsyncDependenciesBlock,
} from 'webpack';
import isArray from 'shared/isArray';
class ClientReferenceDependency extends ModuleDependency {
constructor(request: mixed) {
super(request);
}
get type(): string {
return 'client-reference';
}
}
// This is the module that will be used to anchor all client references to.
// I.e. it will have all the client files as async deps from this point on.
// We use the Flight client implementation because you can't get to these
// without the client runtime so it's the first time in the loading sequence
// you might want them.
const clientImportName = 'react-server-dom-webpack/client';
const clientFileName = require.resolve('../client.browser.js');
type ClientReferenceSearchPath = {
directory: string,
recursive?: boolean,
include: RegExp,
exclude?: RegExp,
};
type ClientReferencePath = string | ClientReferenceSearchPath;
type Options = {
isServer: boolean,
clientReferences?: ClientReferencePath | $ReadOnlyArray<ClientReferencePath>,
chunkName?: string,
clientManifestFilename?: string,
ssrManifestFilename?: string,
};
const PLUGIN_NAME = 'React Server Plugin';
export default class ReactFlightWebpackPlugin {
clientReferences: $ReadOnlyArray<ClientReferencePath>;
chunkName: string;
clientManifestFilename: string;
ssrManifestFilename: string;
constructor(options: Options) {
if (!options || typeof options.isServer !== 'boolean') {
throw new Error(
PLUGIN_NAME + ': You must specify the isServer option as a boolean.',
);
}
if (options.isServer) {
throw new Error('TODO: Implement the server compiler.');
}
if (!options.clientReferences) {
this.clientReferences = [
{
directory: '.',
recursive: true,
include: /\.(js|ts|jsx|tsx)$/,
},
];
} else if (
typeof options.clientReferences === 'string' ||
!isArray(options.clientReferences)
) {
this.clientReferences = [(options.clientReferences: $FlowFixMe)];
} else {
// $FlowFixMe[incompatible-type] found when upgrading Flow
this.clientReferences = options.clientReferences;
}
if (typeof options.chunkName === 'string') {
this.chunkName = options.chunkName;
if (!/\[(index|request)\]/.test(this.chunkName)) {
this.chunkName += '[index]';
}
} else {
this.chunkName = 'client[index]';
}
this.clientManifestFilename =
options.clientManifestFilename || 'react-client-manifest.json';
this.ssrManifestFilename =
options.ssrManifestFilename || 'react-ssr-manifest.json';
}
apply(compiler: any) {
const _this = this;
let resolvedClientReferences;
let clientFileNameFound = false;
// Find all client files on the file system
compiler.hooks.beforeCompile.tapAsync(
PLUGIN_NAME,
({contextModuleFactory}, callback) => {
const contextResolver = compiler.resolverFactory.get('context', {});
const normalResolver = compiler.resolverFactory.get('normal');
_this.resolveAllClientFiles(
compiler.context,
contextResolver,
normalResolver,
compiler.inputFileSystem,
contextModuleFactory,
function (err, resolvedClientRefs) {
if (err) {
callback(err);
return;
}
resolvedClientReferences = resolvedClientRefs;
callback();
},
);
},
);
compiler.hooks.thisCompilation.tap(
PLUGIN_NAME,
(compilation, {normalModuleFactory}) => {
compilation.dependencyFactories.set(
ClientReferenceDependency,
normalModuleFactory,
);
compilation.dependencyTemplates.set(
ClientReferenceDependency,
new NullDependency.Template(),
);
// $FlowFixMe[missing-local-annot]
const handler = parser => {
// We need to add all client references as dependency of something in the graph so
// Webpack knows which entries need to know about the relevant chunks and include the
// map in their runtime. The things that actually resolves the dependency is the Flight
// client runtime. So we add them as a dependency of the Flight client runtime.
// Anything that imports the runtime will be made aware of these chunks.
parser.hooks.program.tap(PLUGIN_NAME, () => {
const module = parser.state.module;
if (module.resource !== clientFileName) {
return;
}
clientFileNameFound = true;
if (resolvedClientReferences) {
// $FlowFixMe[incompatible-use] found when upgrading Flow
for (let i = 0; i < resolvedClientReferences.length; i++) {
// $FlowFixMe[incompatible-use] found when upgrading Flow
const dep = resolvedClientReferences[i];
const chunkName = _this.chunkName
.replace(/\[index\]/g, '' + i)
.replace(/\[request\]/g, Template.toPath(dep.userRequest));
const block = new AsyncDependenciesBlock(
{
name: chunkName,
},
null,
dep.request,
);
block.addDependency(dep);
module.addBlock(block);
}
}
});
};
normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap('HarmonyModulesPlugin', handler);
normalModuleFactory.hooks.parser
.for('javascript/esm')
.tap('HarmonyModulesPlugin', handler);
normalModuleFactory.hooks.parser
.for('javascript/dynamic')
.tap('HarmonyModulesPlugin', handler);
},
);
compiler.hooks.make.tap(PLUGIN_NAME, compilation => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_REPORT,
},
function () {
if (clientFileNameFound === false) {
compilation.warnings.push(
new WebpackError(
`Client runtime at ${clientImportName} was not found. React Server Components module map file ${_this.clientManifestFilename} was not created.`,
),
);
return;
}
const configuredCrossOriginLoading =
compilation.outputOptions.crossOriginLoading;
const crossOriginMode =
typeof configuredCrossOriginLoading === 'string'
? configuredCrossOriginLoading === 'use-credentials'
? configuredCrossOriginLoading
: 'anonymous'
: null;
const resolvedClientFiles = new Set(
(resolvedClientReferences || []).map(ref => ref.request),
);
const clientManifest: {
[string]: ImportManifestEntry,
} = {};
type SSRModuleMap = {
[string]: {
[string]: {specifier: string, name: string},
},
};
const moduleMap: SSRModuleMap = {};
const ssrBundleConfig: {
moduleLoading: {
prefix: string,
crossOrigin: string | null,
},
moduleMap: SSRModuleMap,
} = {
moduleLoading: {
prefix: compilation.outputOptions.publicPath || '',
crossOrigin: crossOriginMode,
},
moduleMap,
};
// We figure out which files are always loaded by any initial chunk (entrypoint).
// We use this to filter out chunks that Flight will never need to load
const emptySet: Set<string> = new Set();
const runtimeChunkFiles: Set<string> = emptySet;
compilation.entrypoints.forEach(entrypoint => {
const runtimeChunk = entrypoint.getRuntimeChunk();
if (runtimeChunk) {
runtimeChunk.files.forEach(runtimeFile => {
runtimeChunkFiles.add(runtimeFile);
});
}
});
compilation.chunkGroups.forEach(function (chunkGroup) {
const chunks: Array<string> = [];
chunkGroup.chunks.forEach(function (c) {
// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (const file of c.files) {
if (!file.endsWith('.js')) return;
if (file.endsWith('.hot-update.js')) return;
chunks.push(c.id, file);
break;
}
});
// $FlowFixMe[missing-local-annot]
function recordModule(id: $FlowFixMe, module) {
// TODO: Hook into deps instead of the target module.
// That way we know by the type of dep whether to include.
// It also resolves conflicts when the same module is in multiple chunks.
if (!resolvedClientFiles.has(module.resource)) {
return;
}
const href = pathToFileURL(module.resource).href;
if (href !== undefined) {
const ssrExports: {
[string]: {specifier: string, name: string},
} = {};
clientManifest[href] = {
id,
chunks,
name: '*',
};
ssrExports['*'] = {
specifier: href,
name: '*',
};
// TODO: If this module ends up split into multiple modules, then
// we should encode each the chunks needed for the specific export.
// When the module isn't split, it doesn't matter and we can just
// encode the id of the whole module. This code doesn't currently
// deal with module splitting so is likely broken from ESM anyway.
/*
clientManifest[href + '#'] = {
id,
chunks,
name: '',
};
ssrExports[''] = {
specifier: href,
name: '',
};
const moduleProvidedExports = compilation.moduleGraph
.getExportsInfo(module)
.getProvidedExports();
if (Array.isArray(moduleProvidedExports)) {
moduleProvidedExports.forEach(function (name) {
clientManifest[href + '#' + name] = {
id,
chunks,
name: name,
};
ssrExports[name] = {
specifier: href,
name: name,
};
});
}
*/
moduleMap[id] = ssrExports;
}
}
chunkGroup.chunks.forEach(function (chunk) {
const chunkModules =
compilation.chunkGraph.getChunkModulesIterable(chunk);
Array.from(chunkModules).forEach(function (module) {
const moduleId = compilation.chunkGraph.getModuleId(module);
recordModule(moduleId, module);
// If this is a concatenation, register each child to the parent ID.
if (module.modules) {
module.modules.forEach(concatenatedMod => {
recordModule(moduleId, concatenatedMod);
});
}
});
});
});
const clientOutput = JSON.stringify(clientManifest, null, 2);
compilation.emitAsset(
_this.clientManifestFilename,
new sources.RawSource(clientOutput, false),
);
const ssrOutput = JSON.stringify(ssrBundleConfig, null, 2);
compilation.emitAsset(
_this.ssrManifestFilename,
new sources.RawSource(ssrOutput, false),
);
},
);
});
}
// This attempts to replicate the dynamic file path resolution used for other wildcard
// resolution in Webpack is using.
resolveAllClientFiles(
context: string,
contextResolver: any,
normalResolver: any,
fs: any,
contextModuleFactory: any,
callback: (
err: null | Error,
result?: $ReadOnlyArray<ClientReferenceDependency>,
) => void,
) {
function hasUseClientDirective(source: string): boolean {
if (source.indexOf('use client') === -1) {
return false;
}
let body;
try {
body = acorn.parse(source, {
ecmaVersion: '2024',
sourceType: 'module',
}).body;
} catch (x) {
return false;
}
for (let i = 0; i < body.length; i++) {
const node = body[i];
if (node.type !== 'ExpressionStatement' || !node.directive) {
break;
}
if (node.directive === 'use client') {
return true;
}
}
return false;
}
asyncLib.map(
this.clientReferences,
(
clientReferencePath: string | ClientReferenceSearchPath,
cb: (
err: null | Error,
result?: $ReadOnlyArray<ClientReferenceDependency>,
) => void,
): void => {
if (typeof clientReferencePath === 'string') {
cb(null, [new ClientReferenceDependency(clientReferencePath)]);
return;
}
const clientReferenceSearch: ClientReferenceSearchPath =
clientReferencePath;
contextResolver.resolve(
{},
context,
clientReferencePath.directory,
{},
(err, resolvedDirectory) => {
if (err) return cb(err);
const options = {
resource: resolvedDirectory,
resourceQuery: '',
recursive:
clientReferenceSearch.recursive === undefined
? true
: clientReferenceSearch.recursive,
regExp: clientReferenceSearch.include,
include: undefined,
exclude: clientReferenceSearch.exclude,
};
contextModuleFactory.resolveDependencies(
fs,
options,
(err2: null | Error, deps: Array<any /*ModuleDependency*/>) => {
if (err2) return cb(err2);
const clientRefDeps = deps.map(dep => {
// use userRequest instead of request. request always end with undefined which is wrong
const request = join(resolvedDirectory, dep.userRequest);
const clientRefDep = new ClientReferenceDependency(request);
clientRefDep.userRequest = dep.userRequest;
return clientRefDep;
});
asyncLib.filter(
clientRefDeps,
(
clientRefDep: ClientReferenceDependency,
filterCb: (err: null | Error, truthValue: boolean) => void,
) => {
normalResolver.resolve(
{},
context,
clientRefDep.request,
{},
(err3: null | Error, resolvedPath: mixed) => {
if (err3 || typeof resolvedPath !== 'string') {
return filterCb(null, false);
}
fs.readFile(
resolvedPath,
'utf-8',
(err4: null | Error, content: string) => {
if (err4 || typeof content !== 'string') {
return filterCb(null, false);
}
const useClient = hasUseClientDirective(content);
filterCb(null, useClient);
},
);
},
);
},
cb,
);
},
);
},
);
},
(
err: null | Error,
result: $ReadOnlyArray<$ReadOnlyArray<ClientReferenceDependency>>,
): void => {
if (err) return callback(err);
const flat: Array<any> = [];
for (let i = 0; i < result.length; i++) {
// $FlowFixMe[method-unbinding]
flat.push.apply(flat, result[i]);
}
callback(null, flat);
},
);
}
}
| 32.474088 | 160 | 0.534606 |
null | /**
* 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
*/
// $FlowFixMe[method-unbinding]
const hasOwnProperty = Object.prototype.hasOwnProperty;
export default hasOwnProperty;
| 22.214286 | 66 | 0.737654 |
null | /**
* 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
*/
/* eslint-disable no-var */
import type {PriorityLevel} from '../SchedulerPriorities';
import {
enableSchedulerDebugging,
enableProfiling,
enableIsInputPending,
enableIsInputPendingContinuous,
frameYieldMs,
continuousYieldMs,
maxYieldMs,
userBlockingPriorityTimeout,
lowPriorityTimeout,
normalPriorityTimeout,
} from '../SchedulerFeatureFlags';
import {push, pop, peek} from '../SchedulerMinHeap';
// TODO: Use symbols?
import {
ImmediatePriority,
UserBlockingPriority,
NormalPriority,
LowPriority,
IdlePriority,
} from '../SchedulerPriorities';
import {
markTaskRun,
markTaskYield,
markTaskCompleted,
markTaskCanceled,
markTaskErrored,
markSchedulerSuspended,
markSchedulerUnsuspended,
markTaskStart,
stopLoggingProfilingEvents,
startLoggingProfilingEvents,
} from '../SchedulerProfiling';
export type Callback = boolean => ?Callback;
export opaque type Task = {
id: number,
callback: Callback | null,
priorityLevel: PriorityLevel,
startTime: number,
expirationTime: number,
sortIndex: number,
isQueued?: boolean,
};
let getCurrentTime: () => number | DOMHighResTimeStamp;
const hasPerformanceNow =
// $FlowFixMe[method-unbinding]
typeof performance === 'object' && typeof performance.now === 'function';
if (hasPerformanceNow) {
const localPerformance = performance;
getCurrentTime = () => localPerformance.now();
} else {
const localDate = Date;
const initialTime = localDate.now();
getCurrentTime = () => localDate.now() - initialTime;
}
// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var maxSigned31BitInt = 1073741823;
// Tasks are stored on a min heap
var taskQueue: Array<Task> = [];
var timerQueue: Array<Task> = [];
// Incrementing id counter. Used to maintain insertion order.
var taskIdCounter = 1;
// Pausing the scheduler is useful for debugging.
var isSchedulerPaused = false;
var currentTask = null;
var currentPriorityLevel = NormalPriority;
// This is set while performing work, to prevent re-entrance.
var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false;
// Capture local references to native APIs, in case a polyfill overrides them.
const localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
const localClearTimeout =
typeof clearTimeout === 'function' ? clearTimeout : null;
const localSetImmediate =
typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom
const isInputPending =
typeof navigator !== 'undefined' &&
// $FlowFixMe[prop-missing]
navigator.scheduling !== undefined &&
// $FlowFixMe[incompatible-type]
navigator.scheduling.isInputPending !== undefined
? navigator.scheduling.isInputPending.bind(navigator.scheduling)
: null;
const continuousOptions = {includeContinuous: enableIsInputPendingContinuous};
function advanceTimers(currentTime: number) {
// Check for tasks that are no longer delayed and add them to the queue.
let timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
// Timer was cancelled.
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
// Timer fired. Transfer to the task queue.
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
if (enableProfiling) {
markTaskStart(timer, currentTime);
timer.isQueued = true;
}
} else {
// Remaining timers are pending.
return;
}
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime: number) {
isHostTimeoutScheduled = false;
advanceTimers(currentTime);
if (!isHostCallbackScheduled) {
if (peek(taskQueue) !== null) {
isHostCallbackScheduled = true;
requestHostCallback();
} else {
const firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
}
}
function flushWork(initialTime: number) {
if (enableProfiling) {
markSchedulerUnsuspended(initialTime);
}
// We'll need a host callback the next time work is scheduled.
isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
// We scheduled a timeout but it's no longer needed. Cancel it.
isHostTimeoutScheduled = false;
cancelHostTimeout();
}
isPerformingWork = true;
const previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
return workLoop(initialTime);
} catch (error) {
if (currentTask !== null) {
const currentTime = getCurrentTime();
// $FlowFixMe[incompatible-call] found when upgrading Flow
markTaskErrored(currentTask, currentTime);
// $FlowFixMe[incompatible-use] found when upgrading Flow
currentTask.isQueued = false;
}
throw error;
}
} else {
// No catch in prod code path.
return workLoop(initialTime);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
if (enableProfiling) {
const currentTime = getCurrentTime();
markSchedulerSuspended(currentTime);
}
}
}
function workLoop(initialTime: number) {
let currentTime = initialTime;
advanceTimers(currentTime);
currentTask = peek(taskQueue);
while (
currentTask !== null &&
!(enableSchedulerDebugging && isSchedulerPaused)
) {
if (currentTask.expirationTime > currentTime && shouldYieldToHost()) {
// This currentTask hasn't expired, and we've reached the deadline.
break;
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
const callback = currentTask.callback;
if (typeof callback === 'function') {
// $FlowFixMe[incompatible-use] found when upgrading Flow
currentTask.callback = null;
// $FlowFixMe[incompatible-use] found when upgrading Flow
currentPriorityLevel = currentTask.priorityLevel;
// $FlowFixMe[incompatible-use] found when upgrading Flow
const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
if (enableProfiling) {
// $FlowFixMe[incompatible-call] found when upgrading Flow
markTaskRun(currentTask, currentTime);
}
const continuationCallback = callback(didUserCallbackTimeout);
currentTime = getCurrentTime();
if (typeof continuationCallback === 'function') {
// If a continuation is returned, immediately yield to the main thread
// regardless of how much time is left in the current time slice.
// $FlowFixMe[incompatible-use] found when upgrading Flow
currentTask.callback = continuationCallback;
if (enableProfiling) {
// $FlowFixMe[incompatible-call] found when upgrading Flow
markTaskYield(currentTask, currentTime);
}
advanceTimers(currentTime);
return true;
} else {
if (enableProfiling) {
// $FlowFixMe[incompatible-call] found when upgrading Flow
markTaskCompleted(currentTask, currentTime);
// $FlowFixMe[incompatible-use] found when upgrading Flow
currentTask.isQueued = false;
}
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
advanceTimers(currentTime);
}
} else {
pop(taskQueue);
}
currentTask = peek(taskQueue);
}
// Return whether there's additional work
if (currentTask !== null) {
return true;
} else {
const firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
function unstable_runWithPriority<T>(
priorityLevel: PriorityLevel,
eventHandler: () => T,
): T {
switch (priorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
case LowPriority:
case IdlePriority:
break;
default:
priorityLevel = NormalPriority;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_next<T>(eventHandler: () => T): T {
var priorityLevel;
switch (currentPriorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
// Shift down to normal priority
priorityLevel = NormalPriority;
break;
default:
// Anything lower than normal priority should remain at the current level.
priorityLevel = currentPriorityLevel;
break;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_wrapCallback<T: (...Array<mixed>) => mixed>(callback: T): T {
var parentPriorityLevel = currentPriorityLevel;
// $FlowFixMe[incompatible-return]
// $FlowFixMe[missing-this-annot]
return function () {
// This is a fork of runWithPriority, inlined for performance.
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
}
function unstable_scheduleCallback(
priorityLevel: PriorityLevel,
callback: Callback,
options?: {delay: number},
): Task {
var currentTime = getCurrentTime();
var startTime;
if (typeof options === 'object' && options !== null) {
var delay = options.delay;
if (typeof delay === 'number' && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
case ImmediatePriority:
// Times out immediately
timeout = -1;
break;
case UserBlockingPriority:
// Eventually times out
timeout = userBlockingPriorityTimeout;
break;
case IdlePriority:
// Never times out
timeout = maxSigned31BitInt;
break;
case LowPriority:
// Eventually times out
timeout = lowPriorityTimeout;
break;
case NormalPriority:
default:
// Eventually times out
timeout = normalPriorityTimeout;
break;
}
var expirationTime = startTime + timeout;
var newTask: Task = {
id: taskIdCounter++,
callback,
priorityLevel,
startTime,
expirationTime,
sortIndex: -1,
};
if (enableProfiling) {
newTask.isQueued = false;
}
if (startTime > currentTime) {
// This is a delayed task.
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
// All tasks are delayed, and this is the task with the earliest delay.
if (isHostTimeoutScheduled) {
// Cancel an existing timeout.
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
}
// Schedule a timeout.
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
if (enableProfiling) {
markTaskStart(newTask, currentTime);
newTask.isQueued = true;
}
// Schedule a host callback, if needed. If we're already performing work,
// wait until the next time we yield.
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback();
}
}
return newTask;
}
function unstable_pauseExecution() {
isSchedulerPaused = true;
}
function unstable_continueExecution() {
isSchedulerPaused = false;
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback();
}
}
function unstable_getFirstCallbackNode(): Task | null {
return peek(taskQueue);
}
function unstable_cancelCallback(task: Task) {
if (enableProfiling) {
if (task.isQueued) {
const currentTime = getCurrentTime();
markTaskCanceled(task, currentTime);
task.isQueued = false;
}
}
// Null out the callback to indicate the task has been canceled. (Can't
// remove from the queue because you can't remove arbitrary nodes from an
// array based heap, only the first one.)
task.callback = null;
}
function unstable_getCurrentPriorityLevel(): PriorityLevel {
return currentPriorityLevel;
}
let isMessageLoopRunning = false;
let taskTimeoutID: TimeoutID = (-1: any);
// Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.
let frameInterval = frameYieldMs;
const continuousInputInterval = continuousYieldMs;
const maxInterval = maxYieldMs;
let startTime = -1;
let needsPaint = false;
function shouldYieldToHost(): boolean {
const timeElapsed = getCurrentTime() - startTime;
if (timeElapsed < frameInterval) {
// The main thread has only been blocked for a really short amount of time;
// smaller than a single frame. Don't yield yet.
return false;
}
// The main thread has been blocked for a non-negligible amount of time. We
// may want to yield control of the main thread, so the browser can perform
// high priority tasks. The main ones are painting and user input. If there's
// a pending paint or a pending input, then we should yield. But if there's
// neither, then we can yield less often while remaining responsive. We'll
// eventually yield regardless, since there could be a pending paint that
// wasn't accompanied by a call to `requestPaint`, or other main thread tasks
// like network events.
if (enableIsInputPending) {
if (needsPaint) {
// There's a pending paint (signaled by `requestPaint`). Yield now.
return true;
}
if (timeElapsed < continuousInputInterval) {
// We haven't blocked the thread for that long. Only yield if there's a
// pending discrete input (e.g. click). It's OK if there's pending
// continuous input (e.g. mouseover).
if (isInputPending !== null) {
return isInputPending();
}
} else if (timeElapsed < maxInterval) {
// Yield if there's either a pending discrete or continuous input.
if (isInputPending !== null) {
return isInputPending(continuousOptions);
}
} else {
// We've blocked the thread for a long time. Even if there's no pending
// input, there may be some other scheduled work that we don't know about,
// like a network event. Yield now.
return true;
}
}
// `isInputPending` isn't available. Yield now.
return true;
}
function requestPaint() {
if (
enableIsInputPending &&
navigator !== undefined &&
// $FlowFixMe[prop-missing]
navigator.scheduling !== undefined &&
// $FlowFixMe[incompatible-type]
navigator.scheduling.isInputPending !== undefined
) {
needsPaint = true;
}
// Since we yield every frame regardless, `requestPaint` has no effect.
}
function forceFrameRate(fps: number) {
if (fps < 0 || fps > 125) {
// Using console['error'] to evade Babel and ESLint
console['error'](
'forceFrameRate takes a positive int between 0 and 125, ' +
'forcing frame rates higher than 125 fps is not supported',
);
return;
}
if (fps > 0) {
frameInterval = Math.floor(1000 / fps);
} else {
// reset the framerate
frameInterval = frameYieldMs;
}
}
const performWorkUntilDeadline = () => {
if (isMessageLoopRunning) {
const currentTime = getCurrentTime();
// Keep track of the start time so we can measure how long the main thread
// has been blocked.
startTime = currentTime;
// If a scheduler task throws, exit the current browser task so the
// error can be observed.
//
// Intentionally not using a try-catch, since that makes some debugging
// techniques harder. Instead, if `flushWork` errors, then `hasMoreWork` will
// remain true, and we'll continue the work loop.
let hasMoreWork = true;
try {
hasMoreWork = flushWork(currentTime);
} finally {
if (hasMoreWork) {
// If there's more work, schedule the next message event at the end
// of the preceding one.
schedulePerformWorkUntilDeadline();
} else {
isMessageLoopRunning = false;
}
}
}
// Yielding to the browser will give it a chance to paint, so we can
// reset this.
needsPaint = false;
};
let schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === 'function') {
// Node.js and old IE.
// There's a few reasons for why we prefer setImmediate.
//
// Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
// (Even though this is a DOM fork of the Scheduler, you could get here
// with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
// https://github.com/facebook/react/issues/20756
//
// But also, it runs earlier which is the semantic we want.
// If other browsers ever implement it, it's better to use it.
// Although both of these would be inferior to native scheduling.
schedulePerformWorkUntilDeadline = () => {
localSetImmediate(performWorkUntilDeadline);
};
} else if (typeof MessageChannel !== 'undefined') {
// DOM and Worker environments.
// We prefer MessageChannel because of the 4ms setTimeout clamping.
const channel = new MessageChannel();
const port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = () => {
port.postMessage(null);
};
} else {
// We should only fallback here in non-browser environments.
schedulePerformWorkUntilDeadline = () => {
// $FlowFixMe[not-a-function] nullable value
localSetTimeout(performWorkUntilDeadline, 0);
};
}
function requestHostCallback() {
if (!isMessageLoopRunning) {
isMessageLoopRunning = true;
schedulePerformWorkUntilDeadline();
}
}
function requestHostTimeout(
callback: (currentTime: number) => void,
ms: number,
) {
// $FlowFixMe[not-a-function] nullable value
taskTimeoutID = localSetTimeout(() => {
callback(getCurrentTime());
}, ms);
}
function cancelHostTimeout() {
// $FlowFixMe[not-a-function] nullable value
localClearTimeout(taskTimeoutID);
taskTimeoutID = ((-1: any): TimeoutID);
}
export {
ImmediatePriority as unstable_ImmediatePriority,
UserBlockingPriority as unstable_UserBlockingPriority,
NormalPriority as unstable_NormalPriority,
IdlePriority as unstable_IdlePriority,
LowPriority as unstable_LowPriority,
unstable_runWithPriority,
unstable_next,
unstable_scheduleCallback,
unstable_cancelCallback,
unstable_wrapCallback,
unstable_getCurrentPriorityLevel,
shouldYieldToHost as unstable_shouldYield,
requestPaint as unstable_requestPaint,
unstable_continueExecution,
unstable_pauseExecution,
unstable_getFirstCallbackNode,
getCurrentTime as unstable_now,
forceFrameRate as unstable_forceFrameRate,
};
export const unstable_Profiling: {
startLoggingProfilingEvents(): void,
stopLoggingProfilingEvents(): ArrayBuffer | null,
} | null = enableProfiling
? {
startLoggingProfilingEvents,
stopLoggingProfilingEvents,
}
: null;
| 28.648286 | 86 | 0.688886 |
Hands-On-Penetration-Testing-with-Python | /**
* 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 React from 'react';
import useTheme from './useTheme';
export function Component() {
const theme = useTheme();
return <div>theme: {theme}</div>;
}
| 19.277778 | 66 | 0.684066 |
owtf | import {useState, useEffect} from 'react';
export default function useTimer() {
const [value, setValue] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => {
setValue(new Date());
}, 1000);
return () => clearInterval(id);
}, []);
return value.toLocaleTimeString();
}
| 23.615385 | 55 | 0.595611 |
cybersecurity-penetration-testing | /**
* 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
* @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
*/
'use strict';
const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');
let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
function initModules() {
// Reset warning cache.
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
// Make them available to the helpers.
return {
ReactDOM,
ReactDOMServer,
ReactTestUtils,
};
}
const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);
describe('ReactDOMServerIntegration', () => {
beforeEach(() => {
resetModules();
});
// Test pragmas don't support itRenders abstraction
if (
__EXPERIMENTAL__ &&
require('shared/ReactFeatureFlags').enableDebugTracing
) {
describe('React.unstable_DebugTracingMode', () => {
beforeEach(() => {
spyOnDevAndProd(console, 'log');
});
itRenders('with one child', async render => {
const e = await render(
<React.unstable_DebugTracingMode>
<div>text1</div>
</React.unstable_DebugTracingMode>,
);
const parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
});
itRenders('mode with several children', async render => {
const Header = props => {
return <p>header</p>;
};
const Footer = props => {
return (
<React.unstable_DebugTracingMode>
<h2>footer</h2>
<h3>about</h3>
</React.unstable_DebugTracingMode>
);
};
const e = await render(
<React.unstable_DebugTracingMode>
<div>text1</div>
<span>text2</span>
<Header />
<Footer />
</React.unstable_DebugTracingMode>,
);
const parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('SPAN');
expect(parent.childNodes[2].tagName).toBe('P');
expect(parent.childNodes[3].tagName).toBe('H2');
expect(parent.childNodes[4].tagName).toBe('H3');
});
});
}
describe('React.StrictMode', () => {
itRenders('a strict mode with one child', async render => {
const e = await render(
<React.StrictMode>
<div>text1</div>
</React.StrictMode>,
);
const parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
});
itRenders('a strict mode with several children', async render => {
const Header = props => {
return <p>header</p>;
};
const Footer = props => {
return (
<React.StrictMode>
<h2>footer</h2>
<h3>about</h3>
</React.StrictMode>
);
};
const e = await render(
<React.StrictMode>
<div>text1</div>
<span>text2</span>
<Header />
<Footer />
</React.StrictMode>,
);
const parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('SPAN');
expect(parent.childNodes[2].tagName).toBe('P');
expect(parent.childNodes[3].tagName).toBe('H2');
expect(parent.childNodes[4].tagName).toBe('H3');
});
itRenders('a nested strict mode', async render => {
const e = await render(
<React.StrictMode>
<React.StrictMode>
<div>text1</div>
</React.StrictMode>
<span>text2</span>
<React.StrictMode>
<React.StrictMode>
<React.StrictMode>
{null}
<p />
</React.StrictMode>
{false}
</React.StrictMode>
</React.StrictMode>
</React.StrictMode>,
);
const parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('SPAN');
expect(parent.childNodes[2].tagName).toBe('P');
});
itRenders('an empty strict mode', async render => {
expect(
(
await render(
<div>
<React.StrictMode />
</div>,
)
).firstChild,
).toBe(null);
});
});
});
| 26.810651 | 93 | 0.561396 |
owtf | 'use client';
import * as React from 'react';
let LazyDynamic = React.lazy(() =>
import('./Dynamic.js').then(exp => ({default: exp.Dynamic}))
);
export function Client() {
const [loaded, load] = React.useReducer(() => true, false);
return loaded ? (
<div>
loaded dynamically: <LazyDynamic />
</div>
) : (
<div>
<button onClick={load}>Load dynamic import Component</button>
</div>
);
}
| 18.454545 | 67 | 0.592506 |
owtf | /**
* 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
*/
// These tests are based on ReactJSXElement-test,
// ReactJSXElementValidator-test, ReactComponent-test,
// and ReactElementJSX-test.
jest.mock('react/jsx-runtime', () => require('./jsx-runtime'), {virtual: true});
jest.mock('react/jsx-dev-runtime', () => require('./jsx-dev-runtime'), {
virtual: true,
});
let React = require('react');
let ReactDOM = require('react-dom');
let ReactTestUtils = {
renderIntoDocument(el) {
const container = document.createElement('div');
return ReactDOM.render(el, container);
},
};
let PropTypes = React.PropTypes;
let Component = class Component extends React.Component {
render() {
return <div />;
}
};
let RequiredPropComponent = class extends React.Component {
render() {
return <span>{this.props.prop}</span>;
}
};
RequiredPropComponent.displayName = 'RequiredPropComponent';
RequiredPropComponent.propTypes = {prop: PropTypes.string.isRequired};
it('works', () => {
const container = document.createElement('div');
ReactDOM.render(<h1>hello</h1>, container);
expect(container.textContent).toBe('hello');
});
it('returns a complete element according to spec', () => {
const element = <Component />;
expect(element.type).toBe(Component);
expect(element.key).toBe(null);
expect(element.ref).toBe(null);
const expectation = {};
Object.freeze(expectation);
expect(element.props).toEqual(expectation);
});
it('allows a lower-case to be passed as the string type', () => {
const element = <div />;
expect(element.type).toBe('div');
expect(element.key).toBe(null);
expect(element.ref).toBe(null);
const expectation = {};
Object.freeze(expectation);
expect(element.props).toEqual(expectation);
});
it('allows a string to be passed as the type', () => {
const TagName = 'div';
const element = <TagName />;
expect(element.type).toBe('div');
expect(element.key).toBe(null);
expect(element.ref).toBe(null);
const expectation = {};
Object.freeze(expectation);
expect(element.props).toEqual(expectation);
});
it('returns an immutable element', () => {
const element = <Component />;
if (process.env.NODE_ENV === 'development') {
expect(() => (element.type = 'div')).toThrow();
} else {
expect(() => (element.type = 'div')).not.toThrow();
}
});
it('does not reuse the object that is spread into props', () => {
const config = {foo: 1};
const element = <Component {...config} />;
expect(element.props.foo).toBe(1);
config.foo = 2;
expect(element.props.foo).toBe(1);
});
it('extracts key and ref from the rest of the props', () => {
const element = <Component key="12" ref="34" foo="56" />;
expect(element.type).toBe(Component);
expect(element.key).toBe('12');
expect(element.ref).toBe('34');
const expectation = {foo: '56'};
Object.freeze(expectation);
expect(element.props).toEqual(expectation);
});
it('coerces the key to a string', () => {
const element = <Component key={12} foo="56" />;
expect(element.type).toBe(Component);
expect(element.key).toBe('12');
expect(element.ref).toBe(null);
const expectation = {foo: '56'};
Object.freeze(expectation);
expect(element.props).toEqual(expectation);
});
it('merges JSX children onto the children prop', () => {
const a = 1;
const element = <Component children="text">{a}</Component>;
expect(element.props.children).toBe(a);
});
it('does not override children if no JSX children are provided', () => {
const element = <Component children="text" />;
expect(element.props.children).toBe('text');
});
it('overrides children if null is provided as a JSX child', () => {
const element = <Component children="text">{null}</Component>;
expect(element.props.children).toBe(null);
});
it('overrides children if undefined is provided as an argument', () => {
const element = <Component children="text">{undefined}</Component>;
expect(element.props.children).toBe(undefined);
const element2 = React.cloneElement(
<Component children="text" />,
{},
undefined
);
expect(element2.props.children).toBe(undefined);
});
it('merges JSX children onto the children prop in an array', () => {
const a = 1;
const b = 2;
const c = 3;
const element = (
<Component>
{a}
{b}
{c}
</Component>
);
expect(element.props.children).toEqual([1, 2, 3]);
});
it('allows static methods to be called using the type property', () => {
class StaticMethodComponent {
static someStaticMethod() {
return 'someReturnValue';
}
render() {
return <div />;
}
}
const element = <StaticMethodComponent />;
expect(element.type.someStaticMethod()).toBe('someReturnValue');
});
it('identifies valid elements', () => {
expect(React.isValidElement(<div />)).toEqual(true);
expect(React.isValidElement(<Component />)).toEqual(true);
expect(React.isValidElement(null)).toEqual(false);
expect(React.isValidElement(true)).toEqual(false);
expect(React.isValidElement({})).toEqual(false);
expect(React.isValidElement('string')).toEqual(false);
expect(React.isValidElement(Component)).toEqual(false);
expect(React.isValidElement({type: 'div', props: {}})).toEqual(false);
});
it('is indistinguishable from a plain object', () => {
const element = <div className="foo" />;
const object = {};
expect(element.constructor).toBe(object.constructor);
});
it('should use default prop value when removing a prop', () => {
Component.defaultProps = {fruit: 'persimmon'};
const container = document.createElement('div');
const instance = ReactDOM.render(<Component fruit="mango" />, container);
expect(instance.props.fruit).toBe('mango');
ReactDOM.render(<Component />, container);
expect(instance.props.fruit).toBe('persimmon');
});
it('should normalize props with default values', () => {
class NormalizingComponent extends React.Component {
render() {
return <span>{this.props.prop}</span>;
}
}
NormalizingComponent.defaultProps = {prop: 'testKey'};
const container = document.createElement('div');
const instance = ReactDOM.render(<NormalizingComponent />, container);
expect(instance.props.prop).toBe('testKey');
const inst2 = ReactDOM.render(
<NormalizingComponent prop={null} />,
container
);
expect(inst2.props.prop).toBe(null);
});
it('warns for keys for arrays of elements in children position', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<Component>{[<Component />, <Component />]}</Component>
)
).toErrorDev('Each child in a list should have a unique "key" prop.', {
withoutStack: true,
});
});
it('warns for keys for arrays of elements with owner info', () => {
class InnerComponent extends React.Component {
render() {
return <Component>{this.props.childSet}</Component>;
}
}
class ComponentWrapper extends React.Component {
render() {
return <InnerComponent childSet={[<Component />, <Component />]} />;
}
}
expect(() =>
ReactTestUtils.renderIntoDocument(<ComponentWrapper />)
).toErrorDev(
'Each child in a list should have a unique "key" prop.' +
'\n\nCheck the render method of `InnerComponent`. ' +
'It was passed a child from ComponentWrapper. ',
{withoutStack: true}
);
});
it('does not warn for arrays of elements with keys', () => {
ReactTestUtils.renderIntoDocument(
<Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>
);
});
it('does not warn for iterable elements with keys', () => {
const iterable = {
'@@iterator': function () {
let i = 0;
return {
next: function () {
const done = ++i > 2;
return {
value: done ? undefined : <Component key={'#' + i} />,
done: done,
};
},
};
},
};
ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>);
});
it('does not warn for numeric keys in entry iterable as a child', () => {
const iterable = {
'@@iterator': function () {
let i = 0;
return {
next: function () {
const done = ++i > 2;
return {value: done ? undefined : [i, <Component />], done: done};
},
};
},
};
iterable.entries = iterable['@@iterator'];
ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>);
});
it('does not warn when the element is directly as children', () => {
ReactTestUtils.renderIntoDocument(
<Component>
<Component />
<Component />
</Component>
);
});
it('does not warn when the child array contains non-elements', () => {
void (<Component>{[{}, {}]}</Component>);
});
it('should give context for PropType errors in nested components.', () => {
// In this test, we're making sure that if a proptype error is found in a
// component, we give a small hint as to which parent instantiated that
// component as per warnings about key usage in ReactElementValidator.
function MyComp({color}) {
return <div>My color is {color}</div>;
}
MyComp.propTypes = {
color: PropTypes.string,
};
class ParentComp extends React.Component {
render() {
return <MyComp color={123} />;
}
}
expect(() => ReactTestUtils.renderIntoDocument(<ParentComp />)).toErrorDev(
'Warning: Failed prop type: ' +
'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
'expected `string`.',
{withoutStack: true}
);
});
it('gives a helpful error when passing null, undefined, or boolean', () => {
const Undefined = undefined;
const Null = null;
const True = true;
const Div = 'div';
expect(() => void (<Undefined />)).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' +
"component from the file it's defined in, or you might have mixed up " +
'default and named imports.' +
(process.env.BABEL_ENV === 'development'
? '\n\nCheck your code at **.'
: ''),
{withoutStack: true}
);
expect(() => void (<Null />)).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: null.' +
(process.env.BABEL_ENV === 'development'
? '\n\nCheck your code at **.'
: ''),
{withoutStack: true}
);
expect(() => void (<True />)).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: boolean.' +
(process.env.BABEL_ENV === 'development'
? '\n\nCheck your code at **.'
: ''),
{withoutStack: true}
);
// No error expected
void (<Div />);
});
it('should check default prop values', () => {
RequiredPropComponent.defaultProps = {prop: null};
expect(() =>
ReactTestUtils.renderIntoDocument(<RequiredPropComponent />)
).toErrorDev(
'Warning: Failed prop type: Required prop `prop` was not specified in ' +
'`RequiredPropComponent`.',
{withoutStack: true}
);
});
it('should warn on invalid prop types', () => {
// Since there is no prevalidation step for ES6 classes, there is no hook
// for us to issue a warning earlier than element creation when the error
// actually occurs. Since this step is skipped in production, we should just
// warn instead of throwing for this case.
class NullPropTypeComponent extends React.Component {
render() {
return <span>{this.props.prop}</span>;
}
}
NullPropTypeComponent.propTypes = {
prop: null,
};
expect(() =>
ReactTestUtils.renderIntoDocument(<NullPropTypeComponent />)
).toErrorDev(
'NullPropTypeComponent: prop type `prop` is invalid; it must be a ' +
'function, usually from the `prop-types` package,',
{withoutStack: true}
);
});
xit('should warn on invalid context types', () => {
class NullContextTypeComponent extends React.Component {
render() {
return <span>{this.props.prop}</span>;
}
}
NullContextTypeComponent.contextTypes = {
prop: null,
};
expect(() =>
ReactTestUtils.renderIntoDocument(<NullContextTypeComponent />)
).toErrorDev(
'NullContextTypeComponent: type `prop` is invalid; it must ' +
'be a function, usually from the `prop-types` package,'
);
});
it('should warn if getDefaultProps is specified on the class', () => {
class GetDefaultPropsComponent extends React.Component {
render() {
return <span>{this.props.prop}</span>;
}
}
GetDefaultPropsComponent.getDefaultProps = () => ({
prop: 'foo',
});
expect(() =>
ReactTestUtils.renderIntoDocument(<GetDefaultPropsComponent />)
).toErrorDev(
'getDefaultProps is only used on classic React.createClass definitions.' +
' Use a static property named `defaultProps` instead.',
{withoutStack: true}
);
});
it('should warn if component declares PropTypes instead of propTypes', () => {
class MisspelledPropTypesComponent extends React.Component {
render() {
return <span>{this.props.prop}</span>;
}
}
MisspelledPropTypesComponent.PropTypes = {
prop: PropTypes.string,
};
expect(() =>
ReactTestUtils.renderIntoDocument(
<MisspelledPropTypesComponent prop="hi" />
)
).toErrorDev(
'Warning: Component MisspelledPropTypesComponent declared `PropTypes` ' +
'instead of `propTypes`. Did you misspell the property assignment?',
{withoutStack: true}
);
});
// Not supported.
xit('warns for fragments with illegal attributes', () => {
class Foo extends React.Component {
render() {
return <React.Fragment a={1}>hello</React.Fragment>;
}
}
expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toErrorDev(
'Invalid prop `a` supplied to `React.Fragment`. React.Fragment ' +
'can only have `key` and `children` props.'
);
});
// Not supported.
xit('warns for fragments with refs', () => {
class Foo extends React.Component {
render() {
return (
<React.Fragment
ref={bar => {
this.foo = bar;
}}>
hello
</React.Fragment>
);
}
}
expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toErrorDev(
'Invalid attribute `ref` supplied to `React.Fragment`.'
);
});
// Not supported.
xit('does not warn for fragments of multiple elements without keys', () => {
ReactTestUtils.renderIntoDocument(
<>
<span>1</span>
<span>2</span>
</>
);
});
// Not supported.
xit('warns for fragments of multiple elements with same key', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<>
<span key="a">1</span>
<span key="a">2</span>
<span key="b">3</span>
</>
)
).toErrorDev('Encountered two children with the same key, `a`.', {
withoutStack: true,
});
});
// Not supported.
xit('does not call lazy initializers eagerly', () => {
let didCall = false;
const Lazy = React.lazy(() => {
didCall = true;
return {then() {}};
});
<Lazy />;
expect(didCall).toBe(false);
});
it('supports classic refs', () => {
class Foo extends React.Component {
render() {
return <div className="foo" ref="inner" />;
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<Foo />, container);
expect(instance.refs.inner.className).toBe('foo');
});
it('should support refs on owned components', () => {
const innerObj = {};
const outerObj = {};
class Wrapper extends React.Component {
getObject = () => {
return this.props.object;
};
render() {
return <div>{this.props.children}</div>;
}
}
class Component extends React.Component {
render() {
const inner = <Wrapper object={innerObj} ref="inner" />;
const outer = (
<Wrapper object={outerObj} ref="outer">
{inner}
</Wrapper>
);
return outer;
}
componentDidMount() {
expect(this.refs.inner.getObject()).toEqual(innerObj);
expect(this.refs.outer.getObject()).toEqual(outerObj);
}
}
ReactTestUtils.renderIntoDocument(<Component />);
});
it('should support callback-style refs', () => {
const innerObj = {};
const outerObj = {};
class Wrapper extends React.Component {
getObject = () => {
return this.props.object;
};
render() {
return <div>{this.props.children}</div>;
}
}
let mounted = false;
class Component extends React.Component {
render() {
const inner = (
<Wrapper object={innerObj} ref={c => (this.innerRef = c)} />
);
const outer = (
<Wrapper object={outerObj} ref={c => (this.outerRef = c)}>
{inner}
</Wrapper>
);
return outer;
}
componentDidMount() {
expect(this.innerRef.getObject()).toEqual(innerObj);
expect(this.outerRef.getObject()).toEqual(outerObj);
mounted = true;
}
}
ReactTestUtils.renderIntoDocument(<Component />);
expect(mounted).toBe(true);
});
// Not supported.
xit('should support object-style refs', () => {
const innerObj = {};
const outerObj = {};
class Wrapper extends React.Component {
getObject = () => {
return this.props.object;
};
render() {
return <div>{this.props.children}</div>;
}
}
let mounted = false;
class Component extends React.Component {
constructor() {
super();
this.innerRef = React.createRef();
this.outerRef = React.createRef();
}
render() {
const inner = <Wrapper object={innerObj} ref={this.innerRef} />;
const outer = (
<Wrapper object={outerObj} ref={this.outerRef}>
{inner}
</Wrapper>
);
return outer;
}
componentDidMount() {
expect(this.innerRef.current.getObject()).toEqual(innerObj);
expect(this.outerRef.current.getObject()).toEqual(outerObj);
mounted = true;
}
}
ReactTestUtils.renderIntoDocument(<Component />);
expect(mounted).toBe(true);
});
it('should support new-style refs with mixed-up owners', () => {
class Wrapper extends React.Component {
getTitle = () => {
return this.props.title;
};
render() {
return this.props.getContent();
}
}
let mounted = false;
class Component extends React.Component {
getInner = () => {
// (With old-style refs, it's impossible to get a ref to this div
// because Wrapper is the current owner when this function is called.)
return <div className="inner" ref={c => (this.innerRef = c)} />;
};
render() {
return (
<Wrapper
title="wrapper"
ref={c => (this.wrapperRef = c)}
getContent={this.getInner}
/>
);
}
componentDidMount() {
// Check .props.title to make sure we got the right elements back
expect(this.wrapperRef.getTitle()).toBe('wrapper');
expect(this.innerRef.className).toBe('inner');
mounted = true;
}
}
ReactTestUtils.renderIntoDocument(<Component />);
expect(mounted).toBe(true);
});
it('should warn when `key` is being accessed on composite element', () => {
const container = document.createElement('div');
class Child extends React.Component {
render() {
return <div> {this.props.key} </div>;
}
}
class Parent extends React.Component {
render() {
return (
<div>
<Child key="0" />
<Child key="1" />
<Child key="2" />
</div>
);
}
}
expect(() => ReactDOM.render(<Parent />, container)).toErrorDev(
'Child: `key` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' +
'prop. (https://reactjs.org/link/special-props)',
{withoutStack: true}
);
});
it('should warn when `ref` is being accessed', () => {
const container = document.createElement('div');
class Child extends React.Component {
render() {
return <div> {this.props.ref} </div>;
}
}
class Parent extends React.Component {
render() {
return (
<div>
<Child ref="childElement" />
</div>
);
}
}
expect(() => ReactDOM.render(<Parent />, container)).toErrorDev(
'Child: `ref` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' +
'prop. (https://reactjs.org/link/special-props)',
{withoutStack: true}
);
});
// Note: no warning before 16.
it('should NOT warn when owner and self are different for string refs', () => {
class ClassWithRenderProp extends React.Component {
render() {
return this.props.children();
}
}
class ClassParent extends React.Component {
render() {
return (
<ClassWithRenderProp>{() => <div ref="myRef" />}</ClassWithRenderProp>
);
}
}
const container = document.createElement('div');
ReactDOM.render(<ClassParent />, container);
});
| 27 | 80 | 0.626678 |
null | /**
* 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 type {Wakeable, Thenable} from 'shared/ReactTypes';
import {REACT_LAZY_TYPE} from 'shared/ReactSymbols';
const Uninitialized = -1;
const Pending = 0;
const Resolved = 1;
const Rejected = 2;
type UninitializedPayload<T> = {
_status: -1,
_result: () => Thenable<{default: T, ...}>,
};
type PendingPayload = {
_status: 0,
_result: Wakeable,
};
type ResolvedPayload<T> = {
_status: 1,
_result: {default: T, ...},
};
type RejectedPayload = {
_status: 2,
_result: mixed,
};
type Payload<T> =
| UninitializedPayload<T>
| PendingPayload
| ResolvedPayload<T>
| RejectedPayload;
export type LazyComponent<T, P> = {
$$typeof: symbol | number,
_payload: P,
_init: (payload: P) => T,
};
function lazyInitializer<T>(payload: Payload<T>): T {
if (payload._status === Uninitialized) {
const ctor = payload._result;
const thenable = ctor();
// Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(
moduleObject => {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
const resolved: ResolvedPayload<T> = (payload: any);
resolved._status = Resolved;
resolved._result = moduleObject;
}
},
error => {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
const rejected: RejectedPayload = (payload: any);
rejected._status = Rejected;
rejected._result = error;
}
},
);
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
const pending: PendingPayload = (payload: any);
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
const moduleObject = payload._result;
if (__DEV__) {
if (moduleObject === undefined) {
console.error(
'lazy: Expected the result of a dynamic imp' +
'ort() call. ' +
'Instead received: %s\n\nYour code should look like: \n ' +
// Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' +
"ort('./MyComponent'))\n\n" +
'Did you accidentally put curly braces around the import?',
moduleObject,
);
}
}
if (__DEV__) {
if (!('default' in moduleObject)) {
console.error(
'lazy: Expected the result of a dynamic imp' +
'ort() call. ' +
'Instead received: %s\n\nYour code should look like: \n ' +
// Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' +
"ort('./MyComponent'))",
moduleObject,
);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
export function lazy<T>(
ctor: () => Thenable<{default: T, ...}>,
): LazyComponent<T, Payload<T>> {
const payload: Payload<T> = {
// We use these fields to store the result.
_status: Uninitialized,
_result: ctor,
};
const lazyType: LazyComponent<T, Payload<T>> = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer,
};
if (__DEV__) {
// In production, this would just set it on the object.
let defaultProps;
let propTypes;
// $FlowFixMe[prop-missing]
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get() {
return defaultProps;
},
// $FlowFixMe[missing-local-annot]
set(newDefaultProps) {
console.error(
'React.lazy(...): It is not supported to assign `defaultProps` to ' +
'a lazy component import. Either specify them where the component ' +
'is defined, or create a wrapping component around it.',
);
defaultProps = newDefaultProps;
// Match production behavior more closely:
// $FlowFixMe[prop-missing]
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true,
});
},
},
propTypes: {
configurable: true,
get() {
return propTypes;
},
// $FlowFixMe[missing-local-annot]
set(newPropTypes) {
console.error(
'React.lazy(...): It is not supported to assign `propTypes` to ' +
'a lazy component import. Either specify them where the component ' +
'is defined, or create a wrapping component around it.',
);
propTypes = newPropTypes;
// Match production behavior more closely:
// $FlowFixMe[prop-missing]
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true,
});
},
},
});
}
return lazyType;
}
| 28.636364 | 83 | 0.579679 |
owtf | import Fixture from '../../Fixture';
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import SwitchDateTestCase from './switch-date-test-case';
const React = window.React;
class DateInputFixtures extends React.Component {
render() {
return (
<FixtureSet title="Dates">
<TestCase title="Switching between date and datetime-local">
<TestCase.Steps>
<li>Type a date into the date picker</li>
<li>Toggle "Switch type"</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The month, day, and year values should correctly transfer. The
hours/minutes/seconds should not be discarded.
</TestCase.ExpectedResult>
<Fixture>
<SwitchDateTestCase />
</Fixture>
</TestCase>
</FixtureSet>
);
}
}
export default DateInputFixtures;
| 26.575758 | 74 | 0.616062 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function Component() {
const countState = (0, _react.useState)(0);
const count = countState[0];
const setCount = countState[1];
const darkMode = useIsDarkMode();
const [isDarkMode] = darkMode;
(0, _react.useEffect)(() => {// ...
}, []);
const handleClick = () => setCount(count + 1);
return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 28,
columnNumber: 7
}
}, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 29,
columnNumber: 7
}
}, "Count: ", count), /*#__PURE__*/_react.default.createElement("button", {
onClick: handleClick,
__source: {
fileName: _jsxFileName,
lineNumber: 30,
columnNumber: 7
}
}, "Update count"));
}
function useIsDarkMode() {
const darkModeState = (0, _react.useState)(false);
const [isDarkMode] = darkModeState;
(0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event...
}, []);
return [isDarkMode, () => {}];
}
//# sourceMappingURL=ComponentUsingHooksIndirectly.js.map?foo=bar¶m=some_value | 42.107143 | 743 | 0.653129 |
owtf | import {createContext} from 'react';
const ThemeContext = createContext(null);
export default ThemeContext;
| 17.5 | 41 | 0.790909 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ListItem = ListItem;
exports.List = List;
var React = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ListItem({
item,
removeItem,
toggleItem
}) {
const handleDelete = (0, React.useCallback)(() => {
removeItem(item);
}, [item, removeItem]);
const handleToggle = (0, React.useCallback)(() => {
toggleItem(item);
}, [item, toggleItem]);
return /*#__PURE__*/React.createElement("li", {
__source: {
fileName: _jsxFileName,
lineNumber: 23,
columnNumber: 5
}
}, /*#__PURE__*/React.createElement("button", {
onClick: handleDelete,
__source: {
fileName: _jsxFileName,
lineNumber: 24,
columnNumber: 7
}
}, "Delete"), /*#__PURE__*/React.createElement("label", {
__source: {
fileName: _jsxFileName,
lineNumber: 25,
columnNumber: 7
}
}, /*#__PURE__*/React.createElement("input", {
checked: item.isComplete,
onChange: handleToggle,
type: "checkbox",
__source: {
fileName: _jsxFileName,
lineNumber: 26,
columnNumber: 9
}
}), ' ', item.text));
}
function List(props) {
const [newItemText, setNewItemText] = (0, React.useState)('');
const [items, setItems] = (0, React.useState)([{
id: 1,
isComplete: true,
text: 'First'
}, {
id: 2,
isComplete: true,
text: 'Second'
}, {
id: 3,
isComplete: false,
text: 'Third'
}]);
const [uid, setUID] = (0, React.useState)(4);
const handleClick = (0, React.useCallback)(() => {
if (newItemText !== '') {
setItems([...items, {
id: uid,
isComplete: false,
text: newItemText
}]);
setUID(uid + 1);
setNewItemText('');
}
}, [newItemText, items, uid]);
const handleKeyPress = (0, React.useCallback)(event => {
if (event.key === 'Enter') {
handleClick();
}
}, [handleClick]);
const handleChange = (0, React.useCallback)(event => {
setNewItemText(event.currentTarget.value);
}, [setNewItemText]);
const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]);
const toggleItem = (0, React.useCallback)(itemToToggle => {
// Dont use indexOf()
// because editing props in DevTools creates a new Object.
const index = items.findIndex(item => item.id === itemToToggle.id);
setItems(items.slice(0, index).concat({ ...itemToToggle,
isComplete: !itemToToggle.isComplete
}).concat(items.slice(index + 1)));
}, [items]);
return /*#__PURE__*/React.createElement(React.Fragment, {
__source: {
fileName: _jsxFileName,
lineNumber: 102,
columnNumber: 5
}
}, /*#__PURE__*/React.createElement("h1", {
__source: {
fileName: _jsxFileName,
lineNumber: 103,
columnNumber: 7
}
}, "List"), /*#__PURE__*/React.createElement("input", {
type: "text",
placeholder: "New list item...",
value: newItemText,
onChange: handleChange,
onKeyPress: handleKeyPress,
__source: {
fileName: _jsxFileName,
lineNumber: 104,
columnNumber: 7
}
}), /*#__PURE__*/React.createElement("button", {
disabled: newItemText === '',
onClick: handleClick,
__source: {
fileName: _jsxFileName,
lineNumber: 111,
columnNumber: 7
}
}, /*#__PURE__*/React.createElement("span", {
role: "img",
"aria-label": "Add item",
__source: {
fileName: _jsxFileName,
lineNumber: 112,
columnNumber: 9
}
}, "Add")), /*#__PURE__*/React.createElement("ul", {
__source: {
fileName: _jsxFileName,
lineNumber: 116,
columnNumber: 7
}
}, items.map(item => /*#__PURE__*/React.createElement(ListItem, {
key: item.id,
item: item,
removeItem: removeItem,
toggleItem: toggleItem,
__source: {
fileName: _jsxFileName,
lineNumber: 118,
columnNumber: 11
}
}))));
}
//# sourceMappingURL=ToDoList.js.map?foo=bar¶m=some_value | 30.425 | 743 | 0.603939 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function Component() {
const countState = (0, _react.useState)(0);
const count = countState[0];
const setCount = countState[1];
const darkMode = useIsDarkMode();
const [isDarkMode] = darkMode;
(0, _react.useEffect)(() => {// ...
}, []);
const handleClick = () => setCount(count + 1);
return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 28,
columnNumber: 7
}
}, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 29,
columnNumber: 7
}
}, "Count: ", count), /*#__PURE__*/_react.default.createElement("button", {
onClick: handleClick,
__source: {
fileName: _jsxFileName,
lineNumber: 30,
columnNumber: 7
}
}, "Update count"));
}
function useIsDarkMode() {
const darkModeState = (0, _react.useState)(false);
const [isDarkMode] = darkModeState;
(0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event...
}, []);
return [isDarkMode, () => {}];
}
//# sourceMappingURL=ComponentUsingHooksIndirectly.js.map?foo=bar¶m=some_value | 42.107143 | 743 | 0.653129 |
Tricks-Web-Penetration-Tester | // @flow
import type {ComponentType} from "react";
import createGridComponent from './createGridComponent';
import type { Props, ScrollToAlign } from './createGridComponent';
const FixedSizeGrid: ComponentType<Props<$FlowFixMe>> = createGridComponent({
getColumnOffset: ({ columnWidth }: Props<any>, index: number): number =>
index * ((columnWidth: any): number),
getColumnWidth: ({ columnWidth }: Props<any>, index: number): number =>
((columnWidth: any): number),
getRowOffset: ({ rowHeight }: Props<any>, index: number): number =>
index * ((rowHeight: any): number),
getRowHeight: ({ rowHeight }: Props<any>, index: number): number =>
((rowHeight: any): number),
getEstimatedTotalHeight: ({ rowCount, rowHeight }: Props<any>) =>
((rowHeight: any): number) * rowCount,
getEstimatedTotalWidth: ({ columnCount, columnWidth }: Props<any>) =>
((columnWidth: any): number) * columnCount,
getOffsetForColumnAndAlignment: (
{ columnCount, columnWidth, width }: Props<any>,
columnIndex: number,
align: ScrollToAlign,
scrollLeft: number,
instanceProps: typeof undefined,
scrollbarSize: number
): number => {
const lastColumnOffset = Math.max(
0,
columnCount * ((columnWidth: any): number) - width
);
const maxOffset = Math.min(
lastColumnOffset,
columnIndex * ((columnWidth: any): number)
);
const minOffset = Math.max(
0,
columnIndex * ((columnWidth: any): number) -
width +
scrollbarSize +
((columnWidth: any): number)
);
if (align === 'smart') {
if (scrollLeft >= minOffset - width && scrollLeft <= maxOffset + width) {
align = 'auto';
} else {
align = 'center';
}
}
switch (align) {
case 'start':
return maxOffset;
case 'end':
return minOffset;
case 'center':
// "Centered" offset is usually the average of the min and max.
// But near the edges of the list, this doesn't hold true.
const middleOffset = Math.round(
minOffset + (maxOffset - minOffset) / 2
);
if (middleOffset < Math.ceil(width / 2)) {
return 0; // near the beginning
} else if (middleOffset > lastColumnOffset + Math.floor(width / 2)) {
return lastColumnOffset; // near the end
} else {
return middleOffset;
}
case 'auto':
default:
if (scrollLeft >= minOffset && scrollLeft <= maxOffset) {
return scrollLeft;
} else if (minOffset > maxOffset) {
// Because we only take into account the scrollbar size when calculating minOffset
// this value can be larger than maxOffset when at the end of the list
return minOffset;
} else if (scrollLeft < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getOffsetForRowAndAlignment: (
{ rowHeight, height, rowCount }: Props<any>,
rowIndex: number,
align: ScrollToAlign,
scrollTop: number,
instanceProps: typeof undefined,
scrollbarSize: number
): number => {
const lastRowOffset = Math.max(
0,
rowCount * ((rowHeight: any): number) - height
);
const maxOffset = Math.min(
lastRowOffset,
rowIndex * ((rowHeight: any): number)
);
const minOffset = Math.max(
0,
rowIndex * ((rowHeight: any): number) -
height +
scrollbarSize +
((rowHeight: any): number)
);
if (align === 'smart') {
if (scrollTop >= minOffset - height && scrollTop <= maxOffset + height) {
align = 'auto';
} else {
align = 'center';
}
}
switch (align) {
case 'start':
return maxOffset;
case 'end':
return minOffset;
case 'center':
// "Centered" offset is usually the average of the min and max.
// But near the edges of the list, this doesn't hold true.
const middleOffset = Math.round(
minOffset + (maxOffset - minOffset) / 2
);
if (middleOffset < Math.ceil(height / 2)) {
return 0; // near the beginning
} else if (middleOffset > lastRowOffset + Math.floor(height / 2)) {
return lastRowOffset; // near the end
} else {
return middleOffset;
}
case 'auto':
default:
if (scrollTop >= minOffset && scrollTop <= maxOffset) {
return scrollTop;
} else if (minOffset > maxOffset) {
// Because we only take into account the scrollbar size when calculating minOffset
// this value can be larger than maxOffset when at the end of the list
return minOffset;
} else if (scrollTop < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getColumnStartIndexForOffset: (
{ columnWidth, columnCount }: Props<any>,
scrollLeft: number
): number =>
Math.max(
0,
Math.min(
columnCount - 1,
Math.floor(scrollLeft / ((columnWidth: any): number))
)
),
getColumnStopIndexForStartIndex: (
{ columnWidth, columnCount, width }: Props<any>,
startIndex: number,
scrollLeft: number
): number => {
const left = startIndex * ((columnWidth: any): number);
const numVisibleColumns = Math.ceil(
(width + scrollLeft - left) / ((columnWidth: any): number)
);
return Math.max(
0,
Math.min(
columnCount - 1,
startIndex + numVisibleColumns - 1 // -1 is because stop index is inclusive
)
);
},
getRowStartIndexForOffset: (
{ rowHeight, rowCount }: Props<any>,
scrollTop: number
): number =>
Math.max(
0,
Math.min(rowCount - 1, Math.floor(scrollTop / ((rowHeight: any): number)))
),
getRowStopIndexForStartIndex: (
{ rowHeight, rowCount, height }: Props<any>,
startIndex: number,
scrollTop: number
): number => {
const top = startIndex * ((rowHeight: any): number);
const numVisibleRows = Math.ceil(
(height + scrollTop - top) / ((rowHeight: any): number)
);
return Math.max(
0,
Math.min(
rowCount - 1,
startIndex + numVisibleRows - 1 // -1 is because stop index is inclusive
)
);
},
initInstanceProps(props: Props<any>): any {
// Noop
},
shouldResetStyleCacheOnItemSizeChange: true,
validateProps: ({ columnWidth, rowHeight }: Props<any>): void => {
if (process.env.NODE_ENV !== 'production') {
if (typeof columnWidth !== 'number') {
throw Error(
'An invalid "columnWidth" prop has been specified. ' +
'Value should be a number. ' +
`"${
columnWidth === null ? 'null' : typeof columnWidth
}" was specified.`
);
}
if (typeof rowHeight !== 'number') {
throw Error(
'An invalid "rowHeight" prop has been specified. ' +
'Value should be a number. ' +
`"${rowHeight === null ? 'null' : typeof rowHeight}" was specified.`
);
}
}
},
});
export default FixedSizeGrid;
| 28.202429 | 92 | 0.579451 |
PenetrationTestingScripts | /**
* 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';
/* eslint-disable no-unused-vars */
type JestMockFn<TArguments: $ReadOnlyArray<any>, TReturn> = {
(...args: TArguments): TReturn,
/**
* An object for introspecting mock calls
*/
mock: {
/**
* An array that represents all calls that have been made into this mock
* function. Each call is represented by an array of arguments that were
* passed during the call.
*/
calls: Array<TArguments>,
/**
* An array that contains all the object instances that have been
* instantiated from this mock function.
*/
instances: Array<TReturn>,
/**
* An array that contains all the object results that have been
* returned by this mock function call
*/
results: Array<{isThrow: boolean, value: TReturn}>,
},
/**
* Resets all information stored in the mockFn.mock.calls and
* mockFn.mock.instances arrays. Often this is useful when you want to clean
* up a mock's usage data between two assertions.
*/
mockClear(): void,
/**
* Resets all information stored in the mock. This is useful when you want to
* completely restore a mock back to its initial state.
*/
mockReset(): void,
/**
* Removes the mock and restores the initial implementation. This is useful
* when you want to mock functions in certain test cases and restore the
* original implementation in others. Beware that mockFn.mockRestore only
* works when mock was created with jest.spyOn. Thus you have to take care of
* restoration yourself when manually assigning jest.fn().
*/
mockRestore(): void,
/**
* Accepts a function that should be used as the implementation of the mock.
* The mock itself will still record all calls that go into and instances
* that come from itself -- the only difference is that the implementation
* will also be executed when the mock is called.
*/
mockImplementation(
fn: (...args: TArguments) => TReturn
): JestMockFn<TArguments, TReturn>,
/**
* Accepts a function that will be used as an implementation of the mock for
* one call to the mocked function. Can be chained so that multiple function
* calls produce different results.
*/
mockImplementationOnce(
fn: (...args: TArguments) => TReturn
): JestMockFn<TArguments, TReturn>,
/**
* Accepts a string to use in test result output in place of "jest.fn()" to
* indicate which mock function is being referenced.
*/
mockName(name: string): JestMockFn<TArguments, TReturn>,
/**
* Just a simple sugar function for returning `this`
*/
mockReturnThis(): void,
/**
* Accepts a value that will be returned whenever the mock function is called.
*/
mockReturnValue(value: TReturn): JestMockFn<TArguments, TReturn>,
/**
* Sugar for only returning a value once inside your mock
*/
mockReturnValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>,
/**
* Sugar for jest.fn().mockImplementation(() => Promise.resolve(value))
*/
mockResolvedValue(value: TReturn): JestMockFn<TArguments, Promise<TReturn>>,
/**
* Sugar for jest.fn().mockImplementationOnce(() => Promise.resolve(value))
*/
mockResolvedValueOnce(
value: TReturn
): JestMockFn<TArguments, Promise<TReturn>>,
/**
* Sugar for jest.fn().mockImplementation(() => Promise.reject(value))
*/
mockRejectedValue(value: TReturn): JestMockFn<TArguments, Promise<any>>,
/**
* Sugar for jest.fn().mockImplementationOnce(() => Promise.reject(value))
*/
mockRejectedValueOnce(value: TReturn): JestMockFn<TArguments, Promise<any>>,
};
type JestAsymmetricEqualityType = {
/**
* A custom Jasmine equality tester
*/
asymmetricMatch(value: mixed): boolean,
};
type JestCallsType = {
allArgs(): mixed,
all(): mixed,
any(): boolean,
count(): number,
first(): mixed,
mostRecent(): mixed,
reset(): void,
};
type JestClockType = {
install(): void,
mockDate(date: Date): void,
tick(milliseconds?: number): void,
uninstall(): void,
};
type JestMatcherResult = {
message?: string | (() => string),
pass: boolean,
};
type JestMatcher = (
actual: any,
expected: any
) => JestMatcherResult | Promise<JestMatcherResult>;
type JestPromiseType = {
/**
* Use rejects to unwrap the reason of a rejected promise so any other
* matcher can be chained. If the promise is fulfilled the assertion fails.
*/
// eslint-disable-next-line no-use-before-define
rejects: JestExpectType,
/**
* Use resolves to unwrap the value of a fulfilled promise so any other
* matcher can be chained. If the promise is rejected the assertion fails.
*/
// eslint-disable-next-line no-use-before-define
resolves: JestExpectType,
};
/**
* Jest allows functions and classes to be used as test names in test() and
* describe()
*/
type JestTestName = string | Function;
/**
* Plugin: jest-styled-components
*/
type JestStyledComponentsMatcherValue =
| string
| JestAsymmetricEqualityType
| RegExp
| typeof undefined;
type JestStyledComponentsMatcherOptions = {
media?: string,
modifier?: string,
supports?: string,
};
type JestStyledComponentsMatchersType = {
toHaveStyleRule(
property: string,
value: JestStyledComponentsMatcherValue,
options?: JestStyledComponentsMatcherOptions
): void,
};
/**
* Plugin: jest-enzyme
*/
type EnzymeMatchersType = {
// 5.x
toBeEmpty(): void,
toBePresent(): void,
// 6.x
toBeChecked(): void,
toBeDisabled(): void,
toBeEmptyRender(): void,
toContainMatchingElement(selector: string): void,
toContainMatchingElements(n: number, selector: string): void,
toContainExactlyOneMatchingElement(selector: string): void,
toContainReact(element: React$Element<any>): void,
toExist(): void,
toHaveClassName(className: string): void,
toHaveHTML(html: string): void,
toHaveProp: ((propKey: string, propValue?: any) => void) &
((props: {}) => void),
toHaveRef(refName: string): void,
toHaveState: ((stateKey: string, stateValue?: any) => void) &
((state: {}) => void),
toHaveStyle: ((styleKey: string, styleValue?: any) => void) &
((style: {}) => void),
toHaveTagName(tagName: string): void,
toHaveText(text: string): void,
toHaveValue(value: any): void,
toIncludeText(text: string): void,
toMatchElement(
element: React$Element<any>,
options?: {ignoreProps?: boolean, verbose?: boolean}
): void,
toMatchSelector(selector: string): void,
// 7.x
toHaveDisplayName(name: string): void,
};
// DOM testing library extensions https://github.com/kentcdodds/dom-testing-library#custom-jest-matchers
type DomTestingLibraryType = {
toBeDisabled(): void,
toBeEmpty(): void,
toBeInTheDocument(): void,
toBeVisible(): void,
toContainElement(element: HTMLElement | null): void,
toContainHTML(htmlText: string): void,
toHaveAttribute(name: string, expectedValue?: string): void,
toHaveClass(...classNames: string[]): void,
toHaveFocus(): void,
toHaveFormValues(expectedValues: {[name: string]: any}): void,
toHaveStyle(css: string): void,
toHaveTextContent(
content: string | RegExp,
options?: {normalizeWhitespace: boolean}
): void,
toBeInTheDOM(): void,
};
// Jest JQuery Matchers: https://github.com/unindented/custom-jquery-matchers
type JestJQueryMatchersType = {
toExist(): void,
toHaveLength(len: number): void,
toHaveId(id: string): void,
toHaveClass(className: string): void,
toHaveTag(tag: string): void,
toHaveAttr(key: string, val?: any): void,
toHaveProp(key: string, val?: any): void,
toHaveText(text: string | RegExp): void,
toHaveData(key: string, val?: any): void,
toHaveValue(val: any): void,
toHaveCss(css: {[key: string]: any}): void,
toBeChecked(): void,
toBeDisabled(): void,
toBeEmpty(): void,
toBeHidden(): void,
toBeSelected(): void,
toBeVisible(): void,
toBeFocused(): void,
toBeInDom(): void,
toBeMatchedBy(sel: string): void,
toHaveDescendant(sel: string): void,
toHaveDescendantWithText(sel: string, text: string | RegExp): void,
};
// Jest Extended Matchers: https://github.com/jest-community/jest-extended
type JestExtendedMatchersType = {
/**
* Note: Currently unimplemented
* Passing assertion
*
* @param {String} message
*/
// pass(message: string): void;
/**
* Note: Currently unimplemented
* Failing assertion
*
* @param {String} message
*/
// fail(message: string): void;
/**
* Use .toBeEmpty when checking if a String '', Array [] or Object {} is empty.
*/
toBeEmpty(): void,
/**
* Use .toBeOneOf when checking if a value is a member of a given Array.
* @param {Array.<*>} members
*/
toBeOneOf(members: any[]): void,
/**
* Use `.toBeNil` when checking a value is `null` or `undefined`.
*/
toBeNil(): void,
/**
* Use `.toSatisfy` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean`.
* @param {Function} predicate
*/
toSatisfy(predicate: (n: any) => boolean): void,
/**
* Use `.toBeArray` when checking if a value is an `Array`.
*/
toBeArray(): void,
/**
* Use `.toBeArrayOfSize` when checking if a value is an `Array` of size x.
* @param {Number} x
*/
toBeArrayOfSize(x: number): void,
/**
* Use `.toIncludeAllMembers` when checking if an `Array` contains all of the same members of a given set.
* @param {Array.<*>} members
*/
toIncludeAllMembers(members: any[]): void,
/**
* Use `.toIncludeAnyMembers` when checking if an `Array` contains any of the members of a given set.
* @param {Array.<*>} members
*/
toIncludeAnyMembers(members: any[]): void,
/**
* Use `.toSatisfyAll` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean` for all values in an array.
* @param {Function} predicate
*/
toSatisfyAll(predicate: (n: any) => boolean): void,
/**
* Use `.toBeBoolean` when checking if a value is a `Boolean`.
*/
toBeBoolean(): void,
/**
* Use `.toBeTrue` when checking a value is equal (===) to `true`.
*/
toBeTrue(): void,
/**
* Use `.toBeFalse` when checking a value is equal (===) to `false`.
*/
toBeFalse(): void,
/**
* Use .toBeDate when checking if a value is a Date.
*/
toBeDate(): void,
/**
* Use `.toBeFunction` when checking if a value is a `Function`.
*/
toBeFunction(): void,
/**
* Use `.toHaveBeenCalledBefore` when checking if a `Mock` was called before another `Mock`.
*
* Note: Required Jest version >22
* Note: Your mock functions will have to be asynchronous to cause the timestamps inside of Jest to occur in a differentJS event loop, otherwise the mock timestamps will all be the same
*
* @param {Mock} mock
*/
toHaveBeenCalledBefore(mock: JestMockFn<any, any>): void,
/**
* Use `.toBeNumber` when checking if a value is a `Number`.
*/
toBeNumber(): void,
/**
* Use `.toBeNaN` when checking a value is `NaN`.
*/
toBeNaN(): void,
/**
* Use `.toBeFinite` when checking if a value is a `Number`, not `NaN` or `Infinity`.
*/
toBeFinite(): void,
/**
* Use `.toBePositive` when checking if a value is a positive `Number`.
*/
toBePositive(): void,
/**
* Use `.toBeNegative` when checking if a value is a negative `Number`.
*/
toBeNegative(): void,
/**
* Use `.toBeEven` when checking if a value is an even `Number`.
*/
toBeEven(): void,
/**
* Use `.toBeOdd` when checking if a value is an odd `Number`.
*/
toBeOdd(): void,
/**
* Use `.toBeWithin` when checking if a number is in between the given bounds of: start (inclusive) and end (exclusive).
*
* @param {Number} start
* @param {Number} end
*/
toBeWithin(start: number, end: number): void,
/**
* Use `.toBeObject` when checking if a value is an `Object`.
*/
toBeObject(): void,
/**
* Use `.toContainKey` when checking if an object contains the provided key.
*
* @param {String} key
*/
toContainKey(key: string): void,
/**
* Use `.toContainKeys` when checking if an object has all of the provided keys.
*
* @param {Array.<String>} keys
*/
toContainKeys(keys: string[]): void,
/**
* Use `.toContainAllKeys` when checking if an object only contains all of the provided keys.
*
* @param {Array.<String>} keys
*/
toContainAllKeys(keys: string[]): void,
/**
* Use `.toContainAnyKeys` when checking if an object contains at least one of the provided keys.
*
* @param {Array.<String>} keys
*/
toContainAnyKeys(keys: string[]): void,
/**
* Use `.toContainValue` when checking if an object contains the provided value.
*
* @param {*} value
*/
toContainValue(value: any): void,
/**
* Use `.toContainValues` when checking if an object contains all of the provided values.
*
* @param {Array.<*>} values
*/
toContainValues(values: any[]): void,
/**
* Use `.toContainAllValues` when checking if an object only contains all of the provided values.
*
* @param {Array.<*>} values
*/
toContainAllValues(values: any[]): void,
/**
* Use `.toContainAnyValues` when checking if an object contains at least one of the provided values.
*
* @param {Array.<*>} values
*/
toContainAnyValues(values: any[]): void,
/**
* Use `.toContainEntry` when checking if an object contains the provided entry.
*
* @param {Array.<String, String>} entry
*/
toContainEntry(entry: [string, string]): void,
/**
* Use `.toContainEntries` when checking if an object contains all of the provided entries.
*
* @param {Array.<Array.<String, String>>} entries
*/
toContainEntries(entries: [string, string][]): void,
/**
* Use `.toContainAllEntries` when checking if an object only contains all of the provided entries.
*
* @param {Array.<Array.<String, String>>} entries
*/
toContainAllEntries(entries: [string, string][]): void,
/**
* Use `.toContainAnyEntries` when checking if an object contains at least one of the provided entries.
*
* @param {Array.<Array.<String, String>>} entries
*/
toContainAnyEntries(entries: [string, string][]): void,
/**
* Use `.toBeExtensible` when checking if an object is extensible.
*/
toBeExtensible(): void,
/**
* Use `.toBeFrozen` when checking if an object is frozen.
*/
toBeFrozen(): void,
/**
* Use `.toBeSealed` when checking if an object is sealed.
*/
toBeSealed(): void,
/**
* Use `.toBeString` when checking if a value is a `String`.
*/
toBeString(): void,
/**
* Use `.toEqualCaseInsensitive` when checking if a string is equal (===) to another ignoring the casing of both strings.
*
* @param {String} string
*/
toEqualCaseInsensitive(string: string): void,
/**
* Use `.toStartWith` when checking if a `String` starts with a given `String` prefix.
*
* @param {String} prefix
*/
toStartWith(prefix: string): void,
/**
* Use `.toEndWith` when checking if a `String` ends with a given `String` suffix.
*
* @param {String} suffix
*/
toEndWith(suffix: string): void,
/**
* Use `.toInclude` when checking if a `String` includes the given `String` substring.
*
* @param {String} substring
*/
toInclude(substring: string): void,
/**
* Use `.toIncludeRepeated` when checking if a `String` includes the given `String` substring the correct number of times.
*
* @param {String} substring
* @param {Number} times
*/
toIncludeRepeated(substring: string, times: number): void,
/**
* Use `.toIncludeMultiple` when checking if a `String` includes all of the given substrings.
*
* @param {Array.<String>} substring
*/
toIncludeMultiple(substring: string[]): void,
};
interface JestExpectType {
not: JestExpectType &
EnzymeMatchersType &
DomTestingLibraryType &
JestJQueryMatchersType &
JestStyledComponentsMatchersType &
JestExtendedMatchersType;
/**
* If you have a mock function, you can use .lastCalledWith to test what
* arguments it was last called with.
*/
lastCalledWith(...args: Array<any>): void;
/**
* toBe just checks that a value is what you expect. It uses === to check
* strict equality.
*/
toBe(value: any): void;
/**
* Use .toBeCalledWith to ensure that a mock function was called with
* specific arguments.
*/
toBeCalledWith(...args: Array<any>): void;
/**
* Using exact equality with floating point numbers is a bad idea. Rounding
* means that intuitive things fail.
*/
toBeCloseTo(num: number, delta: any): void;
/**
* Use .toBeDefined to check that a variable is not undefined.
*/
toBeDefined(): void;
/**
* Use .toBeFalsy when you don't care what a value is, you just want to
* ensure a value is false in a boolean context.
*/
toBeFalsy(): void;
/**
* To compare floating point numbers, you can use toBeGreaterThan.
*/
toBeGreaterThan(number: number): void;
/**
* To compare floating point numbers, you can use toBeGreaterThanOrEqual.
*/
toBeGreaterThanOrEqual(number: number): void;
/**
* To compare floating point numbers, you can use toBeLessThan.
*/
toBeLessThan(number: number): void;
/**
* To compare floating point numbers, you can use toBeLessThanOrEqual.
*/
toBeLessThanOrEqual(number: number): void;
/**
* Use .toBeInstanceOf(Class) to check that an object is an instance of a
* class.
*/
toBeInstanceOf(cls: Class<any>): void;
/**
* .toBeNull() is the same as .toBe(null) but the error messages are a bit
* nicer.
*/
toBeNull(): void;
/**
* Use .toBeTruthy when you don't care what a value is, you just want to
* ensure a value is true in a boolean context.
*/
toBeTruthy(): void;
/**
* Use .toBeUndefined to check that a variable is undefined.
*/
toBeUndefined(): void;
/**
* Use .toContain when you want to check that an item is in a list. For
* testing the items in the list, this uses ===, a strict equality check.
*/
toContain(item: any): void;
/**
* Use .toContainEqual when you want to check that an item is in a list. For
* testing the items in the list, this matcher recursively checks the
* equality of all fields, rather than checking for object identity.
*/
toContainEqual(item: any): void;
/**
* Use .toEqual when you want to check that two objects have the same value.
* This matcher recursively checks the equality of all fields, rather than
* checking for object identity.
*/
toEqual(value: any): void;
/**
* Use .toHaveBeenCalled to ensure that a mock function got called.
*/
toHaveBeenCalled(): void;
toBeCalled(): void;
/**
* Use .toHaveBeenCalledTimes to ensure that a mock function got called exact
* number of times.
*/
toHaveBeenCalledTimes(number: number): void;
toBeCalledTimes(number: number): void;
/**
*
*/
toHaveBeenNthCalledWith(nthCall: number, ...args: Array<any>): void;
nthCalledWith(nthCall: number, ...args: Array<any>): void;
/**
*
*/
toHaveReturned(): void;
toReturn(): void;
/**
*
*/
toHaveReturnedTimes(number: number): void;
toReturnTimes(number: number): void;
/**
*
*/
toHaveReturnedWith(value: any): void;
toReturnWith(value: any): void;
/**
*
*/
toHaveLastReturnedWith(value: any): void;
lastReturnedWith(value: any): void;
/**
*
*/
toHaveNthReturnedWith(nthCall: number, value: any): void;
nthReturnedWith(nthCall: number, value: any): void;
/**
* Use .toHaveBeenCalledWith to ensure that a mock function was called with
* specific arguments.
*/
toHaveBeenCalledWith(...args: Array<any>): void;
/**
* Use .toHaveBeenLastCalledWith to ensure that a mock function was last called
* with specific arguments.
*/
toHaveBeenLastCalledWith(...args: Array<any>): void;
/**
* Check that an object has a .length property and it is set to a certain
* numeric value.
*/
toHaveLength(number: number): void;
/**
*
*/
toHaveProperty(propPath: string, value?: any): void;
/**
* Use .toMatch to check that a string matches a regular expression or string.
*/
toMatch(regexpOrString: RegExp | string): void;
/**
* Use .toMatchObject to check that a javascript object matches a subset of the properties of an object.
*/
toMatchObject(object: Object | Array<Object>): void;
/**
* Use .toStrictEqual to check that a javascript object matches a subset of the properties of an object.
*/
toStrictEqual(value: any): void;
/**
* This ensures that an Object matches the most recent snapshot.
*/
toMatchSnapshot(propertyMatchers?: any, name?: string): void;
/**
* This ensures that an Object matches the most recent snapshot.
*/
toMatchSnapshot(name: string): void;
toMatchInlineSnapshot(snapshot?: string): void;
toMatchInlineSnapshot(propertyMatchers?: any, snapshot?: string): void;
/**
* Use .toThrow to test that a function throws when it is called.
* If you want to test that a specific error gets thrown, you can provide an
* argument to toThrow. The argument can be a string for the error message,
* a class for the error, or a regex that should match the error.
*
* Alias: .toThrowError
*/
toThrow(message?: string | Error | Class<Error> | RegExp): void;
toThrowError(message?: string | Error | Class<Error> | RegExp): void;
/**
* Use .toThrowErrorMatchingSnapshot to test that a function throws a error
* matching the most recent snapshot when it is called.
*/
toThrowErrorMatchingSnapshot(): void;
toThrowErrorMatchingInlineSnapshot(snapshot?: string): void;
}
type JestObjectType = {
/**
* Disables automatic mocking in the module loader.
*
* After this method is called, all `require()`s will return the real
* versions of each module (rather than a mocked version).
*/
disableAutomock(): JestObjectType,
/**
* An un-hoisted version of disableAutomock
*/
autoMockOff(): JestObjectType,
/**
* Enables automatic mocking in the module loader.
*/
enableAutomock(): JestObjectType,
/**
* An un-hoisted version of enableAutomock
*/
autoMockOn(): JestObjectType,
/**
* Clears the mock.calls and mock.instances properties of all mocks.
* Equivalent to calling .mockClear() on every mocked function.
*/
clearAllMocks(): JestObjectType,
/**
* Resets the state of all mocks. Equivalent to calling .mockReset() on every
* mocked function.
*/
resetAllMocks(): JestObjectType,
/**
* Restores all mocks back to their original value.
*/
restoreAllMocks(): JestObjectType,
/**
* Removes any pending timers from the timer system.
*/
clearAllTimers(): void,
/**
* Returns the number of fake timers still left to run.
*/
getTimerCount(): number,
/**
* The same as `mock` but not moved to the top of the expectation by
* babel-jest.
*/
doMock(moduleName: string, moduleFactory?: any): JestObjectType,
/**
* The same as `unmock` but not moved to the top of the expectation by
* babel-jest.
*/
dontMock(moduleName: string): JestObjectType,
/**
* Returns a new, unused mock function. Optionally takes a mock
* implementation.
*/
fn<TArguments: $ReadOnlyArray<any>, TReturn>(
implementation?: (...args: TArguments) => TReturn
): JestMockFn<TArguments, TReturn>,
/**
* Determines if the given function is a mocked function.
*/
isMockFunction(fn: Function): boolean,
/**
* Given the name of a module, use the automatic mocking system to generate a
* mocked version of the module for you.
*/
genMockFromModule(moduleName: string): any,
/**
* Mocks a module with an auto-mocked version when it is being required.
*
* The second argument can be used to specify an explicit module factory that
* is being run instead of using Jest's automocking feature.
*
* The third argument can be used to create virtual mocks -- mocks of modules
* that don't exist anywhere in the system.
*/
mock(
moduleName: string,
moduleFactory?: any,
options?: Object
): JestObjectType,
/**
* Returns the actual module instead of a mock, bypassing all checks on
* whether the module should receive a mock implementation or not.
*/
requireActual(moduleName: string): any,
/**
* Returns a mock module instead of the actual module, bypassing all checks
* on whether the module should be required normally or not.
*/
requireMock(moduleName: string): any,
/**
* Resets the module registry - the cache of all required modules. This is
* useful to isolate modules where local state might conflict between tests.
*/
resetModules(): JestObjectType,
/**
* Creates a sandbox registry for the modules that are loaded inside the
* callback function. This is useful to isolate specific modules for every
* test so that local module state doesn't conflict between tests.
*/
isolateModules(fn: () => void): JestObjectType,
/**
* Exhausts the micro-task queue (usually interfaced in node via
* process.nextTick).
*/
runAllTicks(): void,
/**
* Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(),
* setInterval(), and setImmediate()).
*/
runAllTimers(): void,
/**
* Exhausts all tasks queued by setImmediate().
*/
runAllImmediates(): void,
/**
* Executes only the macro task queue (i.e. all tasks queued by setTimeout()
* or setInterval() and setImmediate()).
*/
advanceTimersByTime(msToRun: number): void,
/**
* Executes only the macro task queue (i.e. all tasks queued by setTimeout()
* or setInterval() and setImmediate()).
*
* Renamed to `advanceTimersByTime`.
*/
runTimersToTime(msToRun: number): void,
/**
* Executes only the macro-tasks that are currently pending (i.e., only the
* tasks that have been queued by setTimeout() or setInterval() up to this
* point)
*/
runOnlyPendingTimers(): void,
/**
* Explicitly supplies the mock object that the module system should return
* for the specified module. Note: It is recommended to use jest.mock()
* instead.
*/
setMock(moduleName: string, moduleExports: any): JestObjectType,
/**
* Indicates that the module system should never return a mocked version of
* the specified module from require() (e.g. that it should always return the
* real module).
*/
unmock(moduleName: string): JestObjectType,
/**
* Instructs Jest to use fake versions of the standard timer functions
* (setTimeout, setInterval, clearTimeout, clearInterval, nextTick,
* setImmediate and clearImmediate).
*/
useFakeTimers(): JestObjectType,
/**
* Instructs Jest to use the real versions of the standard timer functions.
*/
useRealTimers(): JestObjectType,
/**
* Creates a mock function similar to jest.fn but also tracks calls to
* object[methodName].
*/
spyOn(
object: Object,
methodName: string,
accessType?: 'get' | 'set'
): JestMockFn<any, any>,
/**
* Set the default timeout interval for tests and before/after hooks in milliseconds.
* Note: The default timeout interval is 5 seconds if this method is not called.
*/
setTimeout(timeout: number): JestObjectType,
};
type JestSpyType = {
calls: JestCallsType,
};
/** Runs this function after every test inside this context */
declare function afterEach(
fn: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void;
/** Runs this function before every test inside this context */
declare function beforeEach(
fn: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void;
/** Runs this function after all tests have finished inside this context */
declare function afterAll(
fn: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void;
/** Runs this function before any tests have started inside this context */
declare function beforeAll(
fn: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void;
/** A context for grouping tests together */
declare var describe: {
/**
* Creates a block that groups together several related tests in one "test suite"
*/
(name: JestTestName, fn: () => void): void,
/**
* Only run this describe block
*/
only(name: JestTestName, fn: () => void): void,
/**
* Skip running this describe block
*/
skip(name: JestTestName, fn: () => void): void,
/**
* each runs this test against array of argument arrays per each run
*
* @param {table} table of Test
*/
each(
...table: Array<Array<mixed> | mixed> | [Array<string>, string]
): (
name: JestTestName,
fn?: (...args: Array<any>) => ?Promise<mixed>,
timeout?: number
) => void,
};
/** An individual test unit */
declare var it: {
/**
* An individual test unit
*
* @param {JestTestName} Name of Test
* @param {Function} Test
* @param {number} Timeout for the test, in milliseconds.
*/
(
name: JestTestName,
fn?: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void,
/**
* Only run this test
*
* @param {JestTestName} Name of Test
* @param {Function} Test
* @param {number} Timeout for the test, in milliseconds.
*/
only(
name: JestTestName,
fn?: (done: () => void) => ?Promise<mixed>,
timeout?: number
): {
each(
...table: Array<Array<mixed> | mixed> | [Array<string>, string]
): (
name: JestTestName,
fn?: (...args: Array<any>) => ?Promise<mixed>,
timeout?: number
) => void,
},
/**
* Skip running this test
*
* @param {JestTestName} Name of Test
* @param {Function} Test
* @param {number} Timeout for the test, in milliseconds.
*/
skip(
name: JestTestName,
fn?: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void,
/**
* Highlight planned tests in the summary output
*
* @param {String} Name of Test to do
*/
todo(name: string): void,
/**
* Run the test concurrently
*
* @param {JestTestName} Name of Test
* @param {Function} Test
* @param {number} Timeout for the test, in milliseconds.
*/
concurrent(
name: JestTestName,
fn?: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void,
/**
* each runs this test against array of argument arrays per each run
*
* @param {table} table of Test
*/
each(
...table: Array<Array<mixed> | mixed> | [Array<string>, string]
): (
name: JestTestName,
fn?: (...args: Array<any>) => ?Promise<mixed>,
timeout?: number
) => void,
};
declare function fit(
name: JestTestName,
fn: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void;
/** An individual test unit */
declare var test: typeof it;
/** A disabled group of tests */
declare var xdescribe: typeof describe;
/** A focused group of tests */
declare var fdescribe: typeof describe;
/** A disabled individual test */
declare var xit: typeof it;
/** A disabled individual test */
declare var xtest: typeof it;
type JestPrettyFormatColors = {
comment: {close: string, open: string},
content: {close: string, open: string},
prop: {close: string, open: string},
tag: {close: string, open: string},
value: {close: string, open: string},
};
type JestPrettyFormatIndent = string => string;
// eslint-disable-next-line no-unused-vars
type JestPrettyFormatRefs = Array<any>;
type JestPrettyFormatPrint = any => string;
// eslint-disable-next-line no-unused-vars
type JestPrettyFormatStringOrNull = string | null;
type JestPrettyFormatOptions = {
callToJSON: boolean,
edgeSpacing: string,
escapeRegex: boolean,
highlight: boolean,
indent: number,
maxDepth: number,
min: boolean,
// eslint-disable-next-line no-use-before-define
plugins: JestPrettyFormatPlugins,
printFunctionName: boolean,
spacing: string,
theme: {
comment: string,
content: string,
prop: string,
tag: string,
value: string,
},
};
type JestPrettyFormatPlugin = {
print: (
val: any,
serialize: JestPrettyFormatPrint,
indent: JestPrettyFormatIndent,
opts: JestPrettyFormatOptions,
colors: JestPrettyFormatColors
) => string,
test: any => boolean,
};
type JestPrettyFormatPlugins = Array<JestPrettyFormatPlugin>;
/** The expect function is used every time you want to test a value */
declare var expect: {
/** The object that you want to make assertions against */
(
value: any
): JestExpectType &
JestPromiseType &
EnzymeMatchersType &
DomTestingLibraryType &
JestJQueryMatchersType &
JestStyledComponentsMatchersType &
JestExtendedMatchersType,
/** Add additional Jasmine matchers to Jest's roster */
extend(matchers: {[name: string]: JestMatcher}): void,
/** Add a module that formats application-specific data structures. */
addSnapshotSerializer(pluginModule: JestPrettyFormatPlugin): void,
assertions(expectedAssertions: number): void,
hasAssertions(): void,
any(value: mixed): JestAsymmetricEqualityType,
anything(): any,
arrayContaining(value: Array<mixed>): Array<mixed>,
objectContaining(value: Object): Object,
/** Matches any received string that contains the exact expected string. */
stringContaining(value: string): string,
stringMatching(value: string | RegExp): string,
not: {
arrayContaining: (value: $ReadOnlyArray<mixed>) => Array<mixed>,
objectContaining: (value: {}) => Object,
stringContaining: (value: string) => string,
stringMatching: (value: string | RegExp) => string,
},
};
/** Holds all functions related to manipulating test runner */
declare var jest: JestObjectType;
| 27.86661 | 187 | 0.666255 |
cybersecurity-penetration-testing | /**
* 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
*/
let React;
let ReactNoop;
let Scheduler;
let act;
let Suspense;
let SuspenseList;
let getCacheForType;
let caches;
let seededCache;
let assertLog;
beforeEach(() => {
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
const InternalTestUtils = require('internal-test-utils');
assertLog = InternalTestUtils.assertLog;
Suspense = React.Suspense;
if (gate(flags => flags.enableSuspenseList)) {
SuspenseList = React.unstable_SuspenseList;
}
getCacheForType = React.unstable_getCacheForType;
caches = [];
seededCache = null;
});
function createTextCache() {
if (seededCache !== null) {
// Trick to seed a cache before it exists.
// TODO: Need a built-in API to seed data before the initial render (i.e.
// not a refresh because nothing has mounted yet).
const cache = seededCache;
seededCache = null;
return cache;
}
const data = new Map();
const version = caches.length + 1;
const cache = {
version,
data,
resolve(text) {
const record = data.get(text);
if (record === undefined) {
const newRecord = {
status: 'resolved',
value: text,
};
data.set(text, newRecord);
} else if (record.status === 'pending') {
const thenable = record.value;
record.status = 'resolved';
record.value = text;
thenable.pings.forEach(t => t());
}
},
reject(text, error) {
const record = data.get(text);
if (record === undefined) {
const newRecord = {
status: 'rejected',
value: error,
};
data.set(text, newRecord);
} else if (record.status === 'pending') {
const thenable = record.value;
record.status = 'rejected';
record.value = error;
thenable.pings.forEach(t => t());
}
},
};
caches.push(cache);
return cache;
}
function readText(text) {
const textCache = getCacheForType(createTextCache);
const record = textCache.data.get(text);
if (record !== undefined) {
switch (record.status) {
case 'pending':
Scheduler.log(`Suspend! [${text}]`);
throw record.value;
case 'rejected':
Scheduler.log(`Error! [${text}]`);
throw record.value;
case 'resolved':
return textCache.version;
}
} else {
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.data.set(text, newRecord);
throw thenable;
}
}
function Text({text}) {
Scheduler.log(text);
return <span prop={text} />;
}
function AsyncText({text, showVersion}) {
const version = readText(text);
const fullText = showVersion ? `${text} [v${version}]` : text;
Scheduler.log(fullText);
return <span prop={fullText} />;
}
// function seedNextTextCache(text) {
// if (seededCache === null) {
// seededCache = createTextCache();
// }
// seededCache.resolve(text);
// }
function resolveMostRecentTextCache(text) {
if (caches.length === 0) {
throw Error('Cache does not exist.');
} else {
// Resolve the most recently created cache. An older cache can by
// resolved with `caches[index].resolve(text)`.
caches[caches.length - 1].resolve(text);
}
}
const resolveText = resolveMostRecentTextCache;
// @gate enableLegacyCache
// @gate enableSuspenseList
test('regression (#20932): return pointer is correct before entering deleted tree', async () => {
// Based on a production bug. Designed to trigger a very specific
// implementation path.
function Tail() {
return (
<Suspense fallback={<Text text="Loading Tail..." />}>
<Text text="Tail" />
</Suspense>
);
}
function App() {
return (
<SuspenseList revealOrder="forwards">
<Suspense fallback={<Text text="Loading Async..." />}>
<Async />
</Suspense>
<Tail />
</SuspenseList>
);
}
let setAsyncText;
function Async() {
const [c, _setAsyncText] = React.useState(0);
setAsyncText = _setAsyncText;
return <AsyncText text={c} />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['Suspend! [0]', 'Loading Async...', 'Loading Tail...']);
await act(() => {
resolveText(0);
});
assertLog([0, 'Tail']);
await act(() => {
setAsyncText(x => x + 1);
});
assertLog([
'Suspend! [1]',
'Loading Async...',
'Suspend! [1]',
'Loading Async...',
]);
});
| 23.185714 | 97 | 0.596889 |
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-Second-Edition | !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],e):e((t=t||self).ReactWindow={},t.React)}(this,function(t,e){"use strict";function r(){return(r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])}return t}).apply(this,arguments)}function o(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}function n(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var i=function(t,e){return t.length===e.length&&t.every(function(t,r){return o=t,n=e[r],o===n;var o,n})};function a(t,e){var r;void 0===e&&(e=i);var o,n=[],a=!1;return function(){for(var i=arguments.length,l=new Array(i),s=0;s<i;s++)l[s]=arguments[s];return a&&r===this&&e(l,n)?o:(o=t.apply(this,l),a=!0,r=this,n=l,o)}}var l="object"==typeof performance&&"function"==typeof performance.now?function(){return performance.now()}:function(){return Date.now()};function s(t){cancelAnimationFrame(t.id)}function c(t,e){var r=l();var o={id:requestAnimationFrame(function n(){l()-r>=e?t.call(null):o.id=requestAnimationFrame(n)})};return o}var u=-1;var f=null;function d(t){if(void 0===t&&(t=!1),null===f||t){var e=document.createElement("div"),r=e.style;r.width="50px",r.height="50px",r.overflow="scroll",r.direction="rtl";var o=document.createElement("div"),n=o.style;return n.width="100px",n.height="100px",e.appendChild(o),document.body.appendChild(e),e.scrollLeft>0?f="positive-descending":(e.scrollLeft=1,f=0===e.scrollLeft?"negative":"positive-ascending"),document.body.removeChild(e),f}return f}var h=150,m=function(t){var e=t.columnIndex;t.data;return t.rowIndex+":"+e};function p(t){var i,l,f=t.getColumnOffset,p=t.getColumnStartIndexForOffset,v=t.getColumnStopIndexForStartIndex,S=t.getColumnWidth,I=t.getEstimatedTotalHeight,w=t.getEstimatedTotalWidth,M=t.getOffsetForColumnAndAlignment,x=t.getOffsetForRowAndAlignment,_=t.getRowHeight,C=t.getRowOffset,R=t.getRowStartIndexForOffset,y=t.getRowStopIndexForStartIndex,T=t.initInstanceProps,O=t.shouldResetStyleCacheOnItemSizeChange,z=t.validateProps;return l=i=function(t){function i(e){var r;return(r=t.call(this,e)||this)._instanceProps=T(r.props,n(n(r))),r._resetIsScrollingTimeoutId=null,r._outerRef=void 0,r.state={instance:n(n(r)),isScrolling:!1,horizontalScrollDirection:"forward",scrollLeft:"number"==typeof r.props.initialScrollLeft?r.props.initialScrollLeft:0,scrollTop:"number"==typeof r.props.initialScrollTop?r.props.initialScrollTop:0,scrollUpdateWasRequested:!1,verticalScrollDirection:"forward"},r._callOnItemsRendered=void 0,r._callOnItemsRendered=a(function(t,e,o,n,i,a,l,s){return r.props.onItemsRendered({overscanColumnStartIndex:t,overscanColumnStopIndex:e,overscanRowStartIndex:o,overscanRowStopIndex:n,visibleColumnStartIndex:i,visibleColumnStopIndex:a,visibleRowStartIndex:l,visibleRowStopIndex:s})}),r._callOnScroll=void 0,r._callOnScroll=a(function(t,e,o,n,i){return r.props.onScroll({horizontalScrollDirection:o,scrollLeft:t,scrollTop:e,verticalScrollDirection:n,scrollUpdateWasRequested:i})}),r._getItemStyle=void 0,r._getItemStyle=function(t,e){var o,n,i=r.props,a=i.columnWidth,l=i.direction,s=i.rowHeight,c=r._getItemStyleCache(O&&a,O&&l,O&&s),u=t+":"+e;c.hasOwnProperty(u)?o=c[u]:c[u]=((n={position:"absolute"})["rtl"===l?"right":"left"]=f(r.props,e,r._instanceProps),n.top=C(r.props,t,r._instanceProps),n.height=_(r.props,t,r._instanceProps),n.width=S(r.props,e,r._instanceProps),o=n);return o},r._getItemStyleCache=void 0,r._getItemStyleCache=a(function(t,e,r){return{}}),r._onScroll=function(t){var e=t.currentTarget,o=e.clientHeight,n=e.clientWidth,i=e.scrollLeft,a=e.scrollTop,l=e.scrollHeight,s=e.scrollWidth;r.setState(function(t){if(t.scrollLeft===i&&t.scrollTop===a)return null;var e=r.props.direction,c=i;if("rtl"===e)switch(d()){case"negative":c=-i;break;case"positive-descending":c=s-n-i}c=Math.max(0,Math.min(c,s-n));var u=Math.max(0,Math.min(a,l-o));return{isScrolling:!0,horizontalScrollDirection:t.scrollLeft<i?"forward":"backward",scrollLeft:c,scrollTop:u,verticalScrollDirection:t.scrollTop<a?"forward":"backward",scrollUpdateWasRequested:!1}},r._resetIsScrollingDebounced)},r._outerRefSetter=function(t){var e=r.props.outerRef;r._outerRef=t,"function"==typeof e?e(t):null!=e&&"object"==typeof e&&e.hasOwnProperty("current")&&(e.current=t)},r._resetIsScrollingDebounced=function(){null!==r._resetIsScrollingTimeoutId&&s(r._resetIsScrollingTimeoutId),r._resetIsScrollingTimeoutId=c(r._resetIsScrolling,h)},r._resetIsScrolling=function(){r._resetIsScrollingTimeoutId=null,r.setState({isScrolling:!1},function(){r._getItemStyleCache(-1)})},r}o(i,t),i.getDerivedStateFromProps=function(t,e){return g(t,e),z(t),null};var l=i.prototype;return l.scrollTo=function(t){var e=t.scrollLeft,r=t.scrollTop;void 0!==e&&(e=Math.max(0,e)),void 0!==r&&(r=Math.max(0,r)),this.setState(function(t){return void 0===e&&(e=t.scrollLeft),void 0===r&&(r=t.scrollTop),t.scrollLeft===e&&t.scrollTop===r?null:{horizontalScrollDirection:t.scrollLeft<e?"forward":"backward",scrollLeft:e,scrollTop:r,scrollUpdateWasRequested:!0,verticalScrollDirection:t.scrollTop<r?"forward":"backward"}},this._resetIsScrollingDebounced)},l.scrollToItem=function(t){var e=t.align,r=void 0===e?"auto":e,o=t.columnIndex,n=t.rowIndex,i=this.props,a=i.columnCount,l=i.height,s=i.rowCount,c=i.width,f=this.state,d=f.scrollLeft,h=f.scrollTop,m=function(t){if(void 0===t&&(t=!1),-1===u||t){var e=document.createElement("div"),r=e.style;r.width="50px",r.height="50px",r.overflow="scroll",document.body.appendChild(e),u=e.offsetWidth-e.clientWidth,document.body.removeChild(e)}return u}();void 0!==o&&(o=Math.max(0,Math.min(o,a-1))),void 0!==n&&(n=Math.max(0,Math.min(n,s-1)));var p=I(this.props,this._instanceProps),g=w(this.props,this._instanceProps)>c?m:0,v=p>l?m:0;this.scrollTo({scrollLeft:void 0!==o?M(this.props,o,r,d,this._instanceProps,v):d,scrollTop:void 0!==n?x(this.props,n,r,h,this._instanceProps,g):h})},l.componentDidMount=function(){var t=this.props,e=t.initialScrollLeft,r=t.initialScrollTop;if(null!=this._outerRef){var o=this._outerRef;"number"==typeof e&&(o.scrollLeft=e),"number"==typeof r&&(o.scrollTop=r)}this._callPropsCallbacks()},l.componentDidUpdate=function(){var t=this.props.direction,e=this.state,r=e.scrollLeft,o=e.scrollTop;if(e.scrollUpdateWasRequested&&null!=this._outerRef){var n=this._outerRef;if("rtl"===t)switch(d()){case"negative":n.scrollLeft=-r;break;case"positive-ascending":n.scrollLeft=r;break;default:var i=n.clientWidth,a=n.scrollWidth;n.scrollLeft=a-i-r}else n.scrollLeft=Math.max(0,r);n.scrollTop=Math.max(0,o)}this._callPropsCallbacks()},l.componentWillUnmount=function(){null!==this._resetIsScrollingTimeoutId&&s(this._resetIsScrollingTimeoutId)},l.render=function(){var t=this.props,o=t.children,n=t.className,i=t.columnCount,a=t.direction,l=t.height,s=t.innerRef,c=t.innerElementType,u=t.innerTagName,f=t.itemData,d=t.itemKey,h=void 0===d?m:d,p=t.outerElementType,g=t.outerTagName,v=t.rowCount,S=t.style,M=t.useIsScrolling,x=t.width,_=this.state.isScrolling,C=this._getHorizontalRangeToRender(),R=C[0],y=C[1],T=this._getVerticalRangeToRender(),O=T[0],z=T[1],b=[];if(i>0&&v)for(var P=O;P<=z;P++)for(var W=R;W<=y;W++)b.push(e.createElement(o,{columnIndex:W,data:f,isScrolling:M?_:void 0,key:h({columnIndex:W,data:f,rowIndex:P}),rowIndex:P,style:this._getItemStyle(P,W)}));var D=I(this.props,this._instanceProps),F=w(this.props,this._instanceProps);return e.createElement(p||g||"div",{className:n,onScroll:this._onScroll,ref:this._outerRefSetter,style:r({position:"relative",height:l,width:x,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:a},S)},e.createElement(c||u||"div",{children:b,ref:s,style:{height:D,pointerEvents:_?"none":void 0,width:F}}))},l._callPropsCallbacks=function(){var t=this.props,e=t.columnCount,r=t.onItemsRendered,o=t.onScroll,n=t.rowCount;if("function"==typeof r&&e>0&&n>0){var i=this._getHorizontalRangeToRender(),a=i[0],l=i[1],s=i[2],c=i[3],u=this._getVerticalRangeToRender(),f=u[0],d=u[1],h=u[2],m=u[3];this._callOnItemsRendered(a,l,f,d,s,c,h,m)}if("function"==typeof o){var p=this.state,g=p.horizontalScrollDirection,v=p.scrollLeft,S=p.scrollTop,I=p.scrollUpdateWasRequested,w=p.verticalScrollDirection;this._callOnScroll(v,S,g,w,I)}},l._getHorizontalRangeToRender=function(){var t=this.props,e=t.columnCount,r=t.overscanColumnCount,o=t.overscanColumnsCount,n=t.overscanCount,i=t.rowCount,a=this.state,l=a.horizontalScrollDirection,s=a.isScrolling,c=a.scrollLeft,u=r||o||n||1;if(0===e||0===i)return[0,0,0,0];var f=p(this.props,c,this._instanceProps),d=v(this.props,f,c,this._instanceProps),h=s&&"backward"!==l?1:Math.max(1,u),m=s&&"forward"!==l?1:Math.max(1,u);return[Math.max(0,f-h),Math.max(0,Math.min(e-1,d+m)),f,d]},l._getVerticalRangeToRender=function(){var t=this.props,e=t.columnCount,r=t.overscanCount,o=t.overscanRowCount,n=t.overscanRowsCount,i=t.rowCount,a=this.state,l=a.isScrolling,s=a.verticalScrollDirection,c=a.scrollTop,u=o||n||r||1;if(0===e||0===i)return[0,0,0,0];var f=R(this.props,c,this._instanceProps),d=y(this.props,f,c,this._instanceProps),h=l&&"backward"!==s?1:Math.max(1,u),m=l&&"forward"!==s?1:Math.max(1,u);return[Math.max(0,f-h),Math.max(0,Math.min(i-1,d+m)),f,d]},i}(e.PureComponent),i.defaultProps={direction:"ltr",itemData:void 0,useIsScrolling:!1},l}var g=function(t,e){t.children,t.direction,t.height,t.innerTagName,t.outerTagName,t.overscanColumnsCount,t.overscanCount,t.overscanRowsCount,t.width,e.instance},v=function(t,e){var r=t.rowCount,o=e.rowMetadataMap,n=e.estimatedRowHeight,i=e.lastMeasuredRowIndex,a=0;if(i>=r&&(i=r-1),i>=0){var l=o[i];a=l.offset+l.size}return a+(r-i-1)*n},S=function(t,e){var r=t.columnCount,o=e.columnMetadataMap,n=e.estimatedColumnWidth,i=e.lastMeasuredColumnIndex,a=0;if(i>=r&&(i=r-1),i>=0){var l=o[i];a=l.offset+l.size}return a+(r-i-1)*n},I=function(t,e,r,o){var n,i,a;if("column"===t?(n=o.columnMetadataMap,i=e.columnWidth,a=o.lastMeasuredColumnIndex):(n=o.rowMetadataMap,i=e.rowHeight,a=o.lastMeasuredRowIndex),r>a){var l=0;if(a>=0){var s=n[a];l=s.offset+s.size}for(var c=a+1;c<=r;c++){var u=i(c);n[c]={offset:l,size:u},l+=u}"column"===t?o.lastMeasuredColumnIndex=r:o.lastMeasuredRowIndex=r}return n[r]},w=function(t,e,r,o){var n,i;return"column"===t?(n=r.columnMetadataMap,i=r.lastMeasuredColumnIndex):(n=r.rowMetadataMap,i=r.lastMeasuredRowIndex),(i>0?n[i].offset:0)>=o?M(t,e,r,i,0,o):x(t,e,r,Math.max(0,i),o)},M=function(t,e,r,o,n,i){for(;n<=o;){var a=n+Math.floor((o-n)/2),l=I(t,e,a,r).offset;if(l===i)return a;l<i?n=a+1:l>i&&(o=a-1)}return n>0?n-1:0},x=function(t,e,r,o,n){for(var i="column"===t?e.columnCount:e.rowCount,a=1;o<i&&I(t,e,o,r).offset<n;)o+=a,a*=2;return M(t,e,r,Math.min(o,i-1),Math.floor(o/2),n)},_=function(t,e,r,o,n,i,a){var l="column"===t?e.width:e.height,s=I(t,e,r,i),c="column"===t?S(e,i):v(e,i),u=Math.max(0,Math.min(c-l,s.offset)),f=Math.max(0,s.offset-l+a+s.size);switch("smart"===o&&(o=n>=f-l&&n<=u+l?"auto":"center"),o){case"start":return u;case"end":return f;case"center":return Math.round(f+(u-f)/2);case"auto":default:return n>=f&&n<=u?n:f>u?f:n<f?f:u}},C=p({getColumnOffset:function(t,e,r){return I("column",t,e,r).offset},getColumnStartIndexForOffset:function(t,e,r){return w("column",t,r,e)},getColumnStopIndexForStartIndex:function(t,e,r,o){for(var n=t.columnCount,i=t.width,a=I("column",t,e,o),l=r+i,s=a.offset+a.size,c=e;c<n-1&&s<l;)s+=I("column",t,++c,o).size;return c},getColumnWidth:function(t,e,r){return r.columnMetadataMap[e].size},getEstimatedTotalHeight:v,getEstimatedTotalWidth:S,getOffsetForColumnAndAlignment:function(t,e,r,o,n,i){return _("column",t,e,r,o,n,i)},getOffsetForRowAndAlignment:function(t,e,r,o,n,i){return _("row",t,e,r,o,n,i)},getRowOffset:function(t,e,r){return I("row",t,e,r).offset},getRowHeight:function(t,e,r){return r.rowMetadataMap[e].size},getRowStartIndexForOffset:function(t,e,r){return w("row",t,r,e)},getRowStopIndexForStartIndex:function(t,e,r,o){for(var n=t.rowCount,i=t.height,a=I("row",t,e,o),l=r+i,s=a.offset+a.size,c=e;c<n-1&&s<l;)s+=I("row",t,++c,o).size;return c},initInstanceProps:function(t,e){var r=t,o={columnMetadataMap:{},estimatedColumnWidth:r.estimatedColumnWidth||50,estimatedRowHeight:r.estimatedRowHeight||50,lastMeasuredColumnIndex:-1,lastMeasuredRowIndex:-1,rowMetadataMap:{}};return e.resetAfterColumnIndex=function(t,r){void 0===r&&(r=!0),e.resetAfterIndices({columnIndex:t,shouldForceUpdate:r})},e.resetAfterRowIndex=function(t,r){void 0===r&&(r=!0),e.resetAfterIndices({rowIndex:t,shouldForceUpdate:r})},e.resetAfterIndices=function(t){var r=t.columnIndex,n=t.rowIndex,i=t.shouldForceUpdate,a=void 0===i||i;"number"==typeof r&&(o.lastMeasuredColumnIndex=Math.min(o.lastMeasuredColumnIndex,r-1)),"number"==typeof n&&(o.lastMeasuredRowIndex=Math.min(o.lastMeasuredRowIndex,n-1)),e._getItemStyleCache(-1),a&&e.forceUpdate()},o},shouldResetStyleCacheOnItemSizeChange:!1,validateProps:function(t){t.columnWidth,t.rowHeight}}),R=150,y=function(t,e){return t};function T(t){var i,l,u=t.getItemOffset,f=t.getEstimatedTotalSize,h=t.getItemSize,m=t.getOffsetForIndexAndAlignment,p=t.getStartIndexForOffset,g=t.getStopIndexForStartIndex,v=t.initInstanceProps,S=t.shouldResetStyleCacheOnItemSizeChange,I=t.validateProps;return l=i=function(t){function i(e){var r;return(r=t.call(this,e)||this)._instanceProps=v(r.props,n(n(r))),r._outerRef=void 0,r._resetIsScrollingTimeoutId=null,r.state={instance:n(n(r)),isScrolling:!1,scrollDirection:"forward",scrollOffset:"number"==typeof r.props.initialScrollOffset?r.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},r._callOnItemsRendered=void 0,r._callOnItemsRendered=a(function(t,e,o,n){return r.props.onItemsRendered({overscanStartIndex:t,overscanStopIndex:e,visibleStartIndex:o,visibleStopIndex:n})}),r._callOnScroll=void 0,r._callOnScroll=a(function(t,e,o){return r.props.onScroll({scrollDirection:t,scrollOffset:e,scrollUpdateWasRequested:o})}),r._getItemStyle=void 0,r._getItemStyle=function(t){var e,o=r.props,n=o.direction,i=o.itemSize,a=o.layout,l=r._getItemStyleCache(S&&i,S&&a,S&&n);if(l.hasOwnProperty(t))e=l[t];else{var s,c=u(r.props,t,r._instanceProps),f=h(r.props,t,r._instanceProps),d="horizontal"===n||"horizontal"===a;l[t]=((s={position:"absolute"})["rtl"===n?"right":"left"]=d?c:0,s.top=d?0:c,s.height=d?"100%":f,s.width=d?f:"100%",e=s)}return e},r._getItemStyleCache=void 0,r._getItemStyleCache=a(function(t,e,r){return{}}),r._onScrollHorizontal=function(t){var e=t.currentTarget,o=e.clientWidth,n=e.scrollLeft,i=e.scrollWidth;r.setState(function(t){if(t.scrollOffset===n)return null;var e=r.props.direction,a=n;if("rtl"===e)switch(d()){case"negative":a=-n;break;case"positive-descending":a=i-o-n}return a=Math.max(0,Math.min(a,i-o)),{isScrolling:!0,scrollDirection:t.scrollOffset<n?"forward":"backward",scrollOffset:a,scrollUpdateWasRequested:!1}},r._resetIsScrollingDebounced)},r._onScrollVertical=function(t){var e=t.currentTarget,o=e.clientHeight,n=e.scrollHeight,i=e.scrollTop;r.setState(function(t){if(t.scrollOffset===i)return null;var e=Math.max(0,Math.min(i,n-o));return{isScrolling:!0,scrollDirection:t.scrollOffset<e?"forward":"backward",scrollOffset:e,scrollUpdateWasRequested:!1}},r._resetIsScrollingDebounced)},r._outerRefSetter=function(t){var e=r.props.outerRef;r._outerRef=t,"function"==typeof e?e(t):null!=e&&"object"==typeof e&&e.hasOwnProperty("current")&&(e.current=t)},r._resetIsScrollingDebounced=function(){null!==r._resetIsScrollingTimeoutId&&s(r._resetIsScrollingTimeoutId),r._resetIsScrollingTimeoutId=c(r._resetIsScrolling,R)},r._resetIsScrolling=function(){r._resetIsScrollingTimeoutId=null,r.setState({isScrolling:!1},function(){r._getItemStyleCache(-1,null)})},r}o(i,t),i.getDerivedStateFromProps=function(t,e){return O(t,e),I(t),null};var l=i.prototype;return l.scrollTo=function(t){t=Math.max(0,t),this.setState(function(e){return e.scrollOffset===t?null:{scrollDirection:e.scrollOffset<t?"forward":"backward",scrollOffset:t,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},l.scrollToItem=function(t,e){void 0===e&&(e="auto");var r=this.props.itemCount,o=this.state.scrollOffset;t=Math.max(0,Math.min(t,r-1)),this.scrollTo(m(this.props,t,e,o,this._instanceProps))},l.componentDidMount=function(){var t=this.props,e=t.direction,r=t.initialScrollOffset,o=t.layout;if("number"==typeof r&&null!=this._outerRef){var n=this._outerRef;"horizontal"===e||"horizontal"===o?n.scrollLeft=r:n.scrollTop=r}this._callPropsCallbacks()},l.componentDidUpdate=function(){var t=this.props,e=t.direction,r=t.layout,o=this.state,n=o.scrollOffset;if(o.scrollUpdateWasRequested&&null!=this._outerRef){var i=this._outerRef;if("horizontal"===e||"horizontal"===r)if("rtl"===e)switch(d()){case"negative":i.scrollLeft=-n;break;case"positive-ascending":i.scrollLeft=n;break;default:var a=i.clientWidth,l=i.scrollWidth;i.scrollLeft=l-a-n}else i.scrollLeft=n;else i.scrollTop=n}this._callPropsCallbacks()},l.componentWillUnmount=function(){null!==this._resetIsScrollingTimeoutId&&s(this._resetIsScrollingTimeoutId)},l.render=function(){var t=this.props,o=t.children,n=t.className,i=t.direction,a=t.height,l=t.innerRef,s=t.innerElementType,c=t.innerTagName,u=t.itemCount,d=t.itemData,h=t.itemKey,m=void 0===h?y:h,p=t.layout,g=t.outerElementType,v=t.outerTagName,S=t.style,I=t.useIsScrolling,w=t.width,M=this.state.isScrolling,x="horizontal"===i||"horizontal"===p,_=x?this._onScrollHorizontal:this._onScrollVertical,C=this._getRangeToRender(),R=C[0],T=C[1],O=[];if(u>0)for(var z=R;z<=T;z++)O.push(e.createElement(o,{data:d,key:m(z,d),index:z,isScrolling:I?M:void 0,style:this._getItemStyle(z)}));var b=f(this.props,this._instanceProps);return e.createElement(g||v||"div",{className:n,onScroll:_,ref:this._outerRefSetter,style:r({position:"relative",height:a,width:w,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:i},S)},e.createElement(s||c||"div",{children:O,ref:l,style:{height:x?"100%":b,pointerEvents:M?"none":void 0,width:x?b:"100%"}}))},l._callPropsCallbacks=function(){if("function"==typeof this.props.onItemsRendered&&this.props.itemCount>0){var t=this._getRangeToRender(),e=t[0],r=t[1],o=t[2],n=t[3];this._callOnItemsRendered(e,r,o,n)}if("function"==typeof this.props.onScroll){var i=this.state,a=i.scrollDirection,l=i.scrollOffset,s=i.scrollUpdateWasRequested;this._callOnScroll(a,l,s)}},l._getRangeToRender=function(){var t=this.props,e=t.itemCount,r=t.overscanCount,o=this.state,n=o.isScrolling,i=o.scrollDirection,a=o.scrollOffset;if(0===e)return[0,0,0,0];var l=p(this.props,a,this._instanceProps),s=g(this.props,l,a,this._instanceProps),c=n&&"backward"!==i?1:Math.max(1,r),u=n&&"forward"!==i?1:Math.max(1,r);return[Math.max(0,l-c),Math.max(0,Math.min(e-1,s+u)),l,s]},i}(e.PureComponent),i.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},l}var O=function(t,e){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,e.instance},z=function(t,e,r){var o=t.itemSize,n=r.itemMetadataMap,i=r.lastMeasuredIndex;if(e>i){var a=0;if(i>=0){var l=n[i];a=l.offset+l.size}for(var s=i+1;s<=e;s++){var c=o(s);n[s]={offset:a,size:c},a+=c}r.lastMeasuredIndex=e}return n[e]},b=function(t,e,r,o,n){for(;o<=r;){var i=o+Math.floor((r-o)/2),a=z(t,i,e).offset;if(a===n)return i;a<n?o=i+1:a>n&&(r=i-1)}return o>0?o-1:0},P=function(t,e,r,o){for(var n=t.itemCount,i=1;r<n&&z(t,r,e).offset<o;)r+=i,i*=2;return b(t,e,Math.min(r,n-1),Math.floor(r/2),o)},W=function(t,e){var r=t.itemCount,o=e.itemMetadataMap,n=e.estimatedItemSize,i=e.lastMeasuredIndex,a=0;if(i>=r&&(i=r-1),i>=0){var l=o[i];a=l.offset+l.size}return a+(r-i-1)*n},D=T({getItemOffset:function(t,e,r){return z(t,e,r).offset},getItemSize:function(t,e,r){return r.itemMetadataMap[e].size},getEstimatedTotalSize:W,getOffsetForIndexAndAlignment:function(t,e,r,o,n){var i=t.direction,a=t.height,l=t.layout,s=t.width,c="horizontal"===i||"horizontal"===l?s:a,u=z(t,e,n),f=W(t,n),d=Math.max(0,Math.min(f-c,u.offset)),h=Math.max(0,u.offset-c+u.size);switch("smart"===r&&(r=o>=h-c&&o<=d+c?"auto":"center"),r){case"start":return d;case"end":return h;case"center":return Math.round(h+(d-h)/2);case"auto":default:return o>=h&&o<=d?o:o<h?h:d}},getStartIndexForOffset:function(t,e,r){return function(t,e,r){var o=e.itemMetadataMap,n=e.lastMeasuredIndex;return(n>0?o[n].offset:0)>=r?b(t,e,n,0,r):P(t,e,Math.max(0,n),r)}(t,r,e)},getStopIndexForStartIndex:function(t,e,r,o){for(var n=t.direction,i=t.height,a=t.itemCount,l=t.layout,s=t.width,c="horizontal"===n||"horizontal"===l?s:i,u=z(t,e,o),f=r+c,d=u.offset+u.size,h=e;h<a-1&&d<f;)d+=z(t,++h,o).size;return h},initInstanceProps:function(t,e){var r={itemMetadataMap:{},estimatedItemSize:t.estimatedItemSize||50,lastMeasuredIndex:-1};return e.resetAfterIndex=function(t,o){void 0===o&&(o=!0),r.lastMeasuredIndex=Math.min(r.lastMeasuredIndex,t-1),e._getItemStyleCache(-1),o&&e.forceUpdate()},r},shouldResetStyleCacheOnItemSizeChange:!1,validateProps:function(t){t.itemSize}}),F=p({getColumnOffset:function(t,e){return e*t.columnWidth},getColumnWidth:function(t,e){return t.columnWidth},getRowOffset:function(t,e){return e*t.rowHeight},getRowHeight:function(t,e){return t.rowHeight},getEstimatedTotalHeight:function(t){var e=t.rowCount;return t.rowHeight*e},getEstimatedTotalWidth:function(t){var e=t.columnCount;return t.columnWidth*e},getOffsetForColumnAndAlignment:function(t,e,r,o,n,i){var a=t.columnCount,l=t.columnWidth,s=t.width,c=Math.max(0,a*l-s),u=Math.min(c,e*l),f=Math.max(0,e*l-s+i+l);switch("smart"===r&&(r=o>=f-s&&o<=u+s?"auto":"center"),r){case"start":return u;case"end":return f;case"center":var d=Math.round(f+(u-f)/2);return d<Math.ceil(s/2)?0:d>c+Math.floor(s/2)?c:d;case"auto":default:return o>=f&&o<=u?o:f>u?f:o<f?f:u}},getOffsetForRowAndAlignment:function(t,e,r,o,n,i){var a=t.rowHeight,l=t.height,s=t.rowCount,c=Math.max(0,s*a-l),u=Math.min(c,e*a),f=Math.max(0,e*a-l+i+a);switch("smart"===r&&(r=o>=f-l&&o<=u+l?"auto":"center"),r){case"start":return u;case"end":return f;case"center":var d=Math.round(f+(u-f)/2);return d<Math.ceil(l/2)?0:d>c+Math.floor(l/2)?c:d;case"auto":default:return o>=f&&o<=u?o:f>u?f:o<f?f:u}},getColumnStartIndexForOffset:function(t,e){var r=t.columnWidth,o=t.columnCount;return Math.max(0,Math.min(o-1,Math.floor(e/r)))},getColumnStopIndexForStartIndex:function(t,e,r){var o=t.columnWidth,n=t.columnCount,i=t.width,a=e*o,l=Math.ceil((i+r-a)/o);return Math.max(0,Math.min(n-1,e+l-1))},getRowStartIndexForOffset:function(t,e){var r=t.rowHeight,o=t.rowCount;return Math.max(0,Math.min(o-1,Math.floor(e/r)))},getRowStopIndexForStartIndex:function(t,e,r){var o=t.rowHeight,n=t.rowCount,i=t.height,a=e*o,l=Math.ceil((i+r-a)/o);return Math.max(0,Math.min(n-1,e+l-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.columnWidth,t.rowHeight}}),L=T({getItemOffset:function(t,e){return e*t.itemSize},getItemSize:function(t,e){return t.itemSize},getEstimatedTotalSize:function(t){var e=t.itemCount;return t.itemSize*e},getOffsetForIndexAndAlignment:function(t,e,r,o){var n=t.direction,i=t.height,a=t.itemCount,l=t.itemSize,s=t.layout,c=t.width,u="horizontal"===n||"horizontal"===s?c:i,f=Math.max(0,a*l-u),d=Math.min(f,e*l),h=Math.max(0,e*l-u+l);switch("smart"===r&&(r=o>=h-u&&o<=d+u?"auto":"center"),r){case"start":return d;case"end":return h;case"center":var m=Math.round(h+(d-h)/2);return m<Math.ceil(u/2)?0:m>f+Math.floor(u/2)?f:m;case"auto":default:return o>=h&&o<=d?o:o<h?h:d}},getStartIndexForOffset:function(t,e){var r=t.itemCount,o=t.itemSize;return Math.max(0,Math.min(r-1,Math.floor(e/o)))},getStopIndexForStartIndex:function(t,e,r){var o=t.direction,n=t.height,i=t.itemCount,a=t.itemSize,l=t.layout,s=t.width,c=e*a,u="horizontal"===o||"horizontal"===l?s:n,f=Math.ceil((u+r-c)/a);return Math.max(0,Math.min(i-1,e+f-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.itemSize}});function A(t,e){if(null==t)return{};var r,o,n={},i=Object.keys(t);for(o=0;o<i.length;o++)r=i[o],e.indexOf(r)>=0||(n[r]=t[r]);return n}function H(t,e){for(var r in t)if(!(r in e))return!0;for(var o in e)if(t[o]!==e[o])return!0;return!1}function k(t,e){var r=t.style,o=A(t,["style"]),n=e.style,i=A(e,["style"]);return!H(r,n)&&!H(o,i)}t.VariableSizeGrid=C,t.VariableSizeList=D,t.FixedSizeGrid=F,t.FixedSizeList=L,t.areEqual=k,t.shouldComponentUpdate=function(t,e){return!k(this.props,t)||H(this.state,e)},Object.defineProperty(t,"__esModule",{value:!0})});
//# sourceMappingURL=index-prod.umd.js.map
| 8,225.666667 | 24,635 | 0.74063 |
cybersecurity-penetration-testing | /**
* 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';
const React = require('react');
const ReactDOMClient = require('react-dom/client');
const ReactTestUtils = require('react-dom/test-utils');
const act = require('internal-test-utils').act;
// Helpers
const testAllPermutations = async function (testCases) {
for (let i = 0; i < testCases.length; i += 2) {
const renderWithChildren = testCases[i];
const expectedResultAfterRender = testCases[i + 1];
for (let j = 0; j < testCases.length; j += 2) {
const updateWithChildren = testCases[j];
const expectedResultAfterUpdate = testCases[j + 1];
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
await act(() => root.render(<div>{renderWithChildren}</div>));
expectChildren(container, expectedResultAfterRender);
await act(() => root.render(<div>{updateWithChildren}</div>));
expectChildren(container, expectedResultAfterUpdate);
}
}
};
const expectChildren = function (container, children) {
const outerNode = container.firstChild;
let textNode;
if (typeof children === 'string') {
textNode = outerNode.firstChild;
if (children === '') {
expect(textNode != null).toBe(false);
} else {
expect(textNode != null).toBe(true);
expect(textNode.nodeType).toBe(3);
expect(textNode.data).toBe(String(children));
}
} else {
let mountIndex = 0;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (typeof child === 'string') {
if (child === '') {
continue;
}
textNode = outerNode.childNodes[mountIndex];
expect(textNode.nodeType).toBe(3);
expect(textNode.data).toBe(child);
mountIndex++;
} else {
const elementDOMNode = outerNode.childNodes[mountIndex];
expect(elementDOMNode.tagName).toBe('DIV');
mountIndex++;
}
}
}
};
/**
* ReactMultiChild DOM integration test. In ReactDOM components, we make sure
* that single children that are strings are treated as "content" which is much
* faster to render and update.
*/
describe('ReactMultiChildText', () => {
jest.setTimeout(20000);
it('should correctly handle all possible children for render and update', async () => {
await expect(async () => {
// prettier-ignore
await testAllPermutations([
// basic values
undefined, [],
null, [],
false, [],
true, [],
0, '0',
1.2, '1.2',
'', [],
'foo', 'foo',
[], [],
[undefined], [],
[null], [],
[false], [],
[true], [],
[0], ['0'],
[1.2], ['1.2'],
[''], [],
['foo'], ['foo'],
[<div />], [<div />],
// two adjacent values
[true, 0], ['0'],
[0, 0], ['0', '0'],
[1.2, 0], ['1.2', '0'],
[0, ''], ['0', ''],
['foo', 0], ['foo', '0'],
[0, <div />], ['0', <div />],
[true, 1.2], ['1.2'],
[1.2, 0], ['1.2', '0'],
[1.2, 1.2], ['1.2', '1.2'],
[1.2, ''], ['1.2', ''],
['foo', 1.2], ['foo', '1.2'],
[1.2, <div />], ['1.2', <div />],
[true, ''], [''],
['', 0], ['', '0'],
[1.2, ''], ['1.2', ''],
['', ''], ['', ''],
['foo', ''], ['foo', ''],
['', <div />], ['', <div />],
[true, 'foo'], ['foo'],
['foo', 0], ['foo', '0'],
[1.2, 'foo'], ['1.2', 'foo'],
['foo', ''], ['foo', ''],
['foo', 'foo'], ['foo', 'foo'],
['foo', <div />], ['foo', <div />],
// values separated by an element
[true, <div />, true], [<div />],
[1.2, <div />, 1.2], ['1.2', <div />, '1.2'],
['', <div />, ''], ['', <div />, ''],
['foo', <div />, 'foo'], ['foo', <div />, 'foo'],
[true, 1.2, <div />, '', 'foo'], ['1.2', <div />, '', 'foo'],
[1.2, '', <div />, 'foo', true], ['1.2', '', <div />, 'foo'],
['', 'foo', <div />, true, 1.2], ['', 'foo', <div />, '1.2'],
[true, 1.2, '', <div />, 'foo', true, 1.2], ['1.2', '', <div />, 'foo', '1.2'],
['', 'foo', true, <div />, 1.2, '', 'foo'], ['', 'foo', <div />, '1.2', '', 'foo'],
// values inside arrays
[[true], [true]], [],
[[1.2], [1.2]], ['1.2', '1.2'],
[[''], ['']], ['', ''],
[['foo'], ['foo']], ['foo', 'foo'],
[[<div />], [<div />]], [<div />, <div />],
[[true, 1.2, <div />], '', 'foo'], ['1.2', <div />, '', 'foo'],
[1.2, '', [<div />, 'foo', true]], ['1.2', '', <div />, 'foo'],
['', ['foo', <div />, true], 1.2], ['', 'foo', <div />, '1.2'],
[true, [1.2, '', <div />, 'foo'], true, 1.2], ['1.2', '', <div />, 'foo', '1.2'],
['', 'foo', [true, <div />, 1.2, ''], 'foo'], ['', 'foo', <div />, '1.2', '', 'foo'],
// values inside elements
[<div>{true}{1.2}{<div />}</div>, '', 'foo'], [<div />, '', 'foo'],
[1.2, '', <div>{<div />}{'foo'}{true}</div>], ['1.2', '', <div />],
['', <div>{'foo'}{<div />}{true}</div>, 1.2], ['', <div />, '1.2'],
[true, <div>{1.2}{''}{<div />}{'foo'}</div>, true, 1.2], [<div />, '1.2'],
['', 'foo', <div>{true}{<div />}{1.2}{''}</div>, 'foo'], ['', 'foo', <div />, 'foo'],
]);
}).toErrorDev([
'Warning: Each child in a list should have a unique "key" prop.',
'Warning: Each child in a list should have a unique "key" prop.',
]);
});
it('should throw if rendering both HTML and children', () => {
expect(function () {
ReactTestUtils.renderIntoDocument(
<div dangerouslySetInnerHTML={{__html: 'abcdef'}}>ghjkl</div>,
);
}).toThrow();
});
it('should render between nested components and inline children', () => {
ReactTestUtils.renderIntoDocument(
<div>
<h1>
<span />
<span />
</h1>
</div>,
);
expect(function () {
ReactTestUtils.renderIntoDocument(
<div>
<h1>A</h1>
</div>,
);
}).not.toThrow();
expect(function () {
ReactTestUtils.renderIntoDocument(
<div>
<h1>{['A']}</h1>
</div>,
);
}).not.toThrow();
expect(function () {
ReactTestUtils.renderIntoDocument(
<div>
<h1>{['A', 'B']}</h1>
</div>,
);
}).not.toThrow();
});
});
| 29.25 | 93 | 0.452359 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function Component() {
const [count, setCount] = (0, _react.useState)(0);
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 5
}
}, /*#__PURE__*/_react.default.createElement("p", {
__source: {
fileName: _jsxFileName,
lineNumber: 17,
columnNumber: 7
}
}, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", {
onClick: () => setCount(count + 1),
__source: {
fileName: _jsxFileName,
lineNumber: 18,
columnNumber: 7
}
}, "Click me"));
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkV4YW1wbGUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJzZXRDb3VudCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50LCBzZXRDb3VudF0gPSB1c2VTdGF0ZSgwKTtcblxuICByZXR1cm4gKFxuICAgIDxkaXY+XG4gICAgICA8cD5Zb3UgY2xpY2tlZCB7Y291bnR9IHRpbWVzPC9wPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXsoKSA9PiBzZXRDb3VudChjb3VudCArIDEpfT5DbGljayBtZTwvYnV0dG9uPlxuICAgIDwvZGl2PlxuICApO1xufVxuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiIsImNvdW50Il0sIm1hcHBpbmdzIjoiQ0FBRDthNEJDQSxBV0RBIn1dXX19XX0= | 81.538462 | 1,460 | 0.800808 |
null | /**
* 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
*/
declare var $$$config: any;
export opaque type ClientManifest = mixed;
export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars
export opaque type ServerReference<T> = mixed; // eslint-disable-line no-unused-vars
export opaque type ClientReferenceMetadata: any = mixed;
export opaque type ServerReferenceId: any = mixed;
export opaque type ClientReferenceKey: any = mixed;
export const isClientReference = $$$config.isClientReference;
export const isServerReference = $$$config.isServerReference;
export const getClientReferenceKey = $$$config.getClientReferenceKey;
export const resolveClientReferenceMetadata =
$$$config.resolveClientReferenceMetadata;
export const getServerReferenceId = $$$config.getServerReferenceId;
export const getServerReferenceBoundArguments =
$$$config.getServerReferenceBoundArguments;
export const prepareHostDispatcher = $$$config.prepareHostDispatcher;
| 40.592593 | 84 | 0.794118 |
cybersecurity-penetration-testing | /**
* 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 type {DispatchConfig} from './ReactSyntheticEventType';
import type {
AnyNativeEvent,
PluginName,
LegacyPluginModule,
} from './PluginModuleType';
import type {TopLevelType} from './TopLevelEventTypes';
type NamesToPlugins = {
[key: PluginName]: LegacyPluginModule<AnyNativeEvent>,
};
type EventPluginOrder = null | Array<PluginName>;
/**
* Injectable ordering of event plugins.
*/
let eventPluginOrder: EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
const namesToPlugins: NamesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering(): void {
if (!eventPluginOrder) {
// Wait until an `eventPluginOrder` is injected.
return;
}
for (const pluginName in namesToPlugins) {
const pluginModule = namesToPlugins[pluginName];
// $FlowFixMe[incompatible-use] found when upgrading Flow
const pluginIndex = eventPluginOrder.indexOf(pluginName);
if (pluginIndex <= -1) {
throw new Error(
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
`the plugin ordering, \`${pluginName}\`.`,
);
}
if (plugins[pluginIndex]) {
continue;
}
if (!pluginModule.extractEvents) {
throw new Error(
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
`method, but \`${pluginName}\` does not.`,
);
}
plugins[pluginIndex] = pluginModule;
const publishedEvents = pluginModule.eventTypes;
for (const eventName in publishedEvents) {
if (
!publishEventForPlugin(
publishedEvents[eventName],
pluginModule,
eventName,
)
) {
throw new Error(
`EventPluginRegistry: Failed to publish event \`${eventName}\` for plugin \`${pluginName}\`.`,
);
}
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(
dispatchConfig: DispatchConfig,
pluginModule: LegacyPluginModule<AnyNativeEvent>,
eventName: string,
): boolean {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
throw new Error(
'EventPluginRegistry: More than one plugin attempted to publish the same ' +
`event name, \`${eventName}\`.`,
);
}
eventNameDispatchConfigs[eventName] = dispatchConfig;
const phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (const phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
const phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(
phasedRegistrationName,
pluginModule,
eventName,
);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(
dispatchConfig.registrationName,
pluginModule,
eventName,
);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(
registrationName: string,
pluginModule: LegacyPluginModule<AnyNativeEvent>,
eventName: string,
): void {
if (registrationNameModules[registrationName]) {
throw new Error(
'EventPluginRegistry: More than one plugin attempted to publish the same ' +
`registration name, \`${registrationName}\`.`,
);
}
registrationNameModules[registrationName] = pluginModule;
registrationNameDependencies[registrationName] =
pluginModule.eventTypes[eventName].dependencies;
if (__DEV__) {
const lowerCasedName = registrationName.toLowerCase();
possibleRegistrationNames[lowerCasedName] = registrationName;
if (registrationName === 'onDoubleClick') {
possibleRegistrationNames.ondblclick = registrationName;
}
}
}
/**
* Registers plugins so that they can extract and dispatch events.
*/
/**
* Ordered list of injected plugins.
*/
export const plugins: Array<LegacyPluginModule<AnyNativeEvent>> = [];
/**
* Mapping from event name to dispatch config
*/
export const eventNameDispatchConfigs: {
[eventName: string]: DispatchConfig,
} = {};
/**
* Mapping from registration name to plugin module
*/
export const registrationNameModules: {
[registrationName: string]: LegacyPluginModule<AnyNativeEvent>,
} = {};
/**
* Mapping from registration name to event name
*/
export const registrationNameDependencies: {
[registrationName: string]: Array<TopLevelType> | void,
} = {};
/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in __DEV__.
* @type {Object}
*/
export const possibleRegistrationNames: {
[lowerCasedName: string]: string,
} = __DEV__ ? {} : (null: any);
// Trust the developer to only use possibleRegistrationNames in __DEV__
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
*/
export function injectEventPluginOrder(
injectedEventPluginOrder: EventPluginOrder,
): void {
if (eventPluginOrder) {
throw new Error(
'EventPluginRegistry: Cannot inject event plugin ordering more than ' +
'once. You are likely trying to load more than one copy of React.',
);
}
// Clone the ordering so it cannot be dynamically mutated.
// $FlowFixMe[method-unbinding] found when upgrading Flow
eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
recomputePluginOrdering();
}
/**
* Injects plugins to be used by plugin event system. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
*/
export function injectEventPluginsByName(
injectedNamesToPlugins: NamesToPlugins,
): void {
let isOrderingDirty = false;
for (const pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
const pluginModule = injectedNamesToPlugins[pluginName];
if (
!namesToPlugins.hasOwnProperty(pluginName) ||
namesToPlugins[pluginName] !== pluginModule
) {
if (namesToPlugins[pluginName]) {
throw new Error(
'EventPluginRegistry: Cannot inject two different event plugins ' +
`using the same name, \`${pluginName}\`.`,
);
}
namesToPlugins[pluginName] = pluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
}
| 27.49434 | 104 | 0.698808 |