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
|
---|---|---|---|---|
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
*/
// This file uses workerize to load ./importFile.worker as a webworker and instanciates it,
// exposing flow typed functions that can be used on other files.
import * as importFileModule from './importFile';
import WorkerizedImportFile from './importFile.worker';
import type {TimelineData} from '../types';
type ImportFileModule = typeof importFileModule;
const workerizedImportFile: ImportFileModule = window.Worker
? WorkerizedImportFile()
: importFileModule;
export type ImportWorkerOutputData =
| {status: 'SUCCESS', processedData: TimelineData}
| {status: 'INVALID_PROFILE_ERROR', error: Error}
| {status: 'UNEXPECTED_ERROR', error: Error};
export type importFileFunction = (file: File) => ImportWorkerOutputData;
export const importFile = (file: File): Promise<ImportWorkerOutputData> =>
workerizedImportFile.importFile(file);
| 31.060606 | 91 | 0.752129 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireDefault(require("react"));
var _useTheme = _interopRequireDefault(require("./useTheme"));
var _jsxFileName = "";
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Component() {
const theme = (0, _useTheme.default)();
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 10
}
}, "theme: ", theme);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsS0FBSyxHQUFHLHdCQUFkO0FBRUEsc0JBQU87QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsZ0JBQWFBLEtBQWIsQ0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCc7XG5pbXBvcnQgdXNlVGhlbWUgZnJvbSAnLi91c2VUaGVtZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlVGhlbWUoKTtcblxuICByZXR1cm4gPGRpdj50aGVtZToge3RoZW1lfTwvZGl2Pjtcbn1cbiJdLCJ4X2ZhY2Vib29rX3NvdXJjZXMiOltbbnVsbCxbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJ0aGVtZSJdLCJtYXBwaW5ncyI6IkNBQUQ7Y2dCQ0EsQVVEQSJ9XV1dfQ== | 62.461538 | 1,048 | 0.861734 |
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 * as acorn from 'acorn-loose';
type ResolveContext = {
conditions: Array<string>,
parentURL: string | void,
};
type ResolveFunction = (
string,
ResolveContext,
ResolveFunction,
) => {url: string} | Promise<{url: string}>;
type GetSourceContext = {
format: string,
};
type GetSourceFunction = (
string,
GetSourceContext,
GetSourceFunction,
) => Promise<{source: Source}>;
type TransformSourceContext = {
format: string,
url: string,
};
type TransformSourceFunction = (
Source,
TransformSourceContext,
TransformSourceFunction,
) => Promise<{source: Source}>;
type LoadContext = {
conditions: Array<string>,
format: string | null | void,
importAssertions: Object,
};
type LoadFunction = (
string,
LoadContext,
LoadFunction,
) => Promise<{format: string, shortCircuit?: boolean, source: Source}>;
type Source = string | ArrayBuffer | Uint8Array;
let warnedAboutConditionsFlag = false;
let stashedGetSource: null | GetSourceFunction = null;
let stashedResolve: null | ResolveFunction = null;
export async function resolve(
specifier: string,
context: ResolveContext,
defaultResolve: ResolveFunction,
): Promise<{url: string}> {
// We stash this in case we end up needing to resolve export * statements later.
stashedResolve = defaultResolve;
if (!context.conditions.includes('react-server')) {
context = {
...context,
conditions: [...context.conditions, 'react-server'],
};
if (!warnedAboutConditionsFlag) {
warnedAboutConditionsFlag = true;
// eslint-disable-next-line react-internal/no-production-logging
console.warn(
'You did not run Node.js with the `--conditions react-server` flag. ' +
'Any "react-server" override will only work with ESM imports.',
);
}
}
return await defaultResolve(specifier, context, defaultResolve);
}
export async function getSource(
url: string,
context: GetSourceContext,
defaultGetSource: GetSourceFunction,
): Promise<{source: Source}> {
// We stash this in case we end up needing to resolve export * statements later.
stashedGetSource = defaultGetSource;
return defaultGetSource(url, context, defaultGetSource);
}
function addLocalExportedNames(names: Map<string, string>, node: any) {
switch (node.type) {
case 'Identifier':
names.set(node.name, node.name);
return;
case 'ObjectPattern':
for (let i = 0; i < node.properties.length; i++)
addLocalExportedNames(names, node.properties[i]);
return;
case 'ArrayPattern':
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i];
if (element) addLocalExportedNames(names, element);
}
return;
case 'Property':
addLocalExportedNames(names, node.value);
return;
case 'AssignmentPattern':
addLocalExportedNames(names, node.left);
return;
case 'RestElement':
addLocalExportedNames(names, node.argument);
return;
case 'ParenthesizedExpression':
addLocalExportedNames(names, node.expression);
return;
}
}
function transformServerModule(
source: string,
body: any,
url: string,
loader: LoadFunction,
): string {
// If the same local name is exported more than once, we only need one of the names.
const localNames: Map<string, string> = new Map();
const localTypes: Map<string, string> = new Map();
for (let i = 0; i < body.length; i++) {
const node = body[i];
switch (node.type) {
case 'ExportAllDeclaration':
// If export * is used, the other file needs to explicitly opt into "use server" too.
break;
case 'ExportDefaultDeclaration':
if (node.declaration.type === 'Identifier') {
localNames.set(node.declaration.name, 'default');
} else if (node.declaration.type === 'FunctionDeclaration') {
if (node.declaration.id) {
localNames.set(node.declaration.id.name, 'default');
localTypes.set(node.declaration.id.name, 'function');
} else {
// TODO: This needs to be rewritten inline because it doesn't have a local name.
}
}
continue;
case 'ExportNamedDeclaration':
if (node.declaration) {
if (node.declaration.type === 'VariableDeclaration') {
const declarations = node.declaration.declarations;
for (let j = 0; j < declarations.length; j++) {
addLocalExportedNames(localNames, declarations[j].id);
}
} else {
const name = node.declaration.id.name;
localNames.set(name, name);
if (node.declaration.type === 'FunctionDeclaration') {
localTypes.set(name, 'function');
}
}
}
if (node.specifiers) {
const specifiers = node.specifiers;
for (let j = 0; j < specifiers.length; j++) {
const specifier = specifiers[j];
localNames.set(specifier.local.name, specifier.exported.name);
}
}
continue;
}
}
if (localNames.size === 0) {
return source;
}
let newSrc = source + '\n\n;';
newSrc +=
'import {registerServerReference} from "react-server-dom-webpack/server";\n';
localNames.forEach(function (exported, local) {
if (localTypes.get(local) !== 'function') {
// We first check if the export is a function and if so annotate it.
newSrc += 'if (typeof ' + local + ' === "function") ';
}
newSrc += 'registerServerReference(' + local + ',';
newSrc += JSON.stringify(url) + ',';
newSrc += JSON.stringify(exported) + ');\n';
});
return newSrc;
}
function addExportNames(names: Array<string>, node: any) {
switch (node.type) {
case 'Identifier':
names.push(node.name);
return;
case 'ObjectPattern':
for (let i = 0; i < node.properties.length; i++)
addExportNames(names, node.properties[i]);
return;
case 'ArrayPattern':
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i];
if (element) addExportNames(names, element);
}
return;
case 'Property':
addExportNames(names, node.value);
return;
case 'AssignmentPattern':
addExportNames(names, node.left);
return;
case 'RestElement':
addExportNames(names, node.argument);
return;
case 'ParenthesizedExpression':
addExportNames(names, node.expression);
return;
}
}
function resolveClientImport(
specifier: string,
parentURL: string,
): {url: string} | Promise<{url: string}> {
// Resolve an import specifier as if it was loaded by the client. This doesn't use
// the overrides that this loader does but instead reverts to the default.
// This resolution algorithm will not necessarily have the same configuration
// as the actual client loader. It should mostly work and if it doesn't you can
// always convert to explicit exported names instead.
const conditions = ['node', 'import'];
if (stashedResolve === null) {
throw new Error(
'Expected resolve to have been called before transformSource',
);
}
return stashedResolve(specifier, {conditions, parentURL}, stashedResolve);
}
async function parseExportNamesInto(
body: any,
names: Array<string>,
parentURL: string,
loader: LoadFunction,
): Promise<void> {
for (let i = 0; i < body.length; i++) {
const node = body[i];
switch (node.type) {
case 'ExportAllDeclaration':
if (node.exported) {
addExportNames(names, node.exported);
continue;
} else {
const {url} = await resolveClientImport(node.source.value, parentURL);
const {source} = await loader(
url,
{format: 'module', conditions: [], importAssertions: {}},
loader,
);
if (typeof source !== 'string') {
throw new Error('Expected the transformed source to be a string.');
}
let childBody;
try {
childBody = acorn.parse(source, {
ecmaVersion: '2024',
sourceType: 'module',
}).body;
} catch (x) {
// eslint-disable-next-line react-internal/no-production-logging
console.error('Error parsing %s %s', url, x.message);
continue;
}
await parseExportNamesInto(childBody, names, url, loader);
continue;
}
case 'ExportDefaultDeclaration':
names.push('default');
continue;
case 'ExportNamedDeclaration':
if (node.declaration) {
if (node.declaration.type === 'VariableDeclaration') {
const declarations = node.declaration.declarations;
for (let j = 0; j < declarations.length; j++) {
addExportNames(names, declarations[j].id);
}
} else {
addExportNames(names, node.declaration.id);
}
}
if (node.specifiers) {
const specifiers = node.specifiers;
for (let j = 0; j < specifiers.length; j++) {
addExportNames(names, specifiers[j].exported);
}
}
continue;
}
}
}
async function transformClientModule(
body: any,
url: string,
loader: LoadFunction,
): Promise<string> {
const names: Array<string> = [];
await parseExportNamesInto(body, names, url, loader);
if (names.length === 0) {
return '';
}
let newSrc =
'import {registerClientReference} from "react-server-dom-webpack/server";\n';
for (let i = 0; i < names.length; i++) {
const name = names[i];
if (name === 'default') {
newSrc += 'export default ';
newSrc += 'registerClientReference(function() {';
newSrc +=
'throw new Error(' +
JSON.stringify(
`Attempted to call the default export of ${url} from the server` +
`but it's on the client. It's not possible to invoke a client function from ` +
`the server, it can only be rendered as a Component or passed to props of a` +
`Client Component.`,
) +
');';
} else {
newSrc += 'export const ' + name + ' = ';
newSrc += 'registerClientReference(function() {';
newSrc +=
'throw new Error(' +
JSON.stringify(
`Attempted to call ${name}() from the server but ${name} is on the client. ` +
`It's not possible to invoke a client function from the server, it can ` +
`only be rendered as a Component or passed to props of a Client Component.`,
) +
');';
}
newSrc += '},';
newSrc += JSON.stringify(url) + ',';
newSrc += JSON.stringify(name) + ');\n';
}
return newSrc;
}
async function loadClientImport(
url: string,
defaultTransformSource: TransformSourceFunction,
): Promise<{format: string, shortCircuit?: boolean, source: Source}> {
if (stashedGetSource === null) {
throw new Error(
'Expected getSource to have been called before transformSource',
);
}
// TODO: Validate that this is another module by calling getFormat.
const {source} = await stashedGetSource(
url,
{format: 'module'},
stashedGetSource,
);
const result = await defaultTransformSource(
source,
{format: 'module', url},
defaultTransformSource,
);
return {format: 'module', source: result.source};
}
async function transformModuleIfNeeded(
source: string,
url: string,
loader: LoadFunction,
): Promise<string> {
// Do a quick check for the exact string. If it doesn't exist, don't
// bother parsing.
if (
source.indexOf('use client') === -1 &&
source.indexOf('use server') === -1
) {
return source;
}
let body;
try {
body = acorn.parse(source, {
ecmaVersion: '2024',
sourceType: 'module',
}).body;
} catch (x) {
// eslint-disable-next-line react-internal/no-production-logging
console.error('Error parsing %s %s', url, x.message);
return source;
}
let useClient = false;
let useServer = 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') {
useClient = true;
}
if (node.directive === 'use server') {
useServer = true;
}
}
if (!useClient && !useServer) {
return source;
}
if (useClient && useServer) {
throw new Error(
'Cannot have both "use client" and "use server" directives in the same file.',
);
}
if (useClient) {
return transformClientModule(body, url, loader);
}
return transformServerModule(source, body, url, loader);
}
export async function transformSource(
source: Source,
context: TransformSourceContext,
defaultTransformSource: TransformSourceFunction,
): Promise<{source: Source}> {
const transformed = await defaultTransformSource(
source,
context,
defaultTransformSource,
);
if (context.format === 'module') {
const transformedSource = transformed.source;
if (typeof transformedSource !== 'string') {
throw new Error('Expected source to have been transformed to a string.');
}
const newSrc = await transformModuleIfNeeded(
transformedSource,
context.url,
(url: string, ctx: LoadContext, defaultLoad: LoadFunction) => {
return loadClientImport(url, defaultTransformSource);
},
);
return {source: newSrc};
}
return transformed;
}
export async function load(
url: string,
context: LoadContext,
defaultLoad: LoadFunction,
): Promise<{format: string, shortCircuit?: boolean, source: Source}> {
const result = await defaultLoad(url, context, defaultLoad);
if (result.format === 'module') {
if (typeof result.source !== 'string') {
throw new Error('Expected source to have been loaded into a string.');
}
const newSrc = await transformModuleIfNeeded(
result.source,
url,
defaultLoad,
);
return {format: 'module', source: newSrc};
}
return result;
}
| 28.698347 | 93 | 0.622347 |
Tricks-Web-Penetration-Tester | // @flow
import memoizeOne from 'memoize-one';
import * as React from 'react';
import { createElement, PureComponent } from 'react';
import { cancelTimeout, requestTimeout } from './timer';
import { getRTLOffsetType } from './domHelpers';
import type { TimeoutID } from './timer';
export type ScrollToAlign = 'auto' | 'smart' | 'center' | 'start' | 'end';
type itemSize = number | ((index: number) => number);
// TODO Deprecate directions "horizontal" and "vertical"
type Direction = 'ltr' | 'rtl' | 'horizontal' | 'vertical';
type Layout = 'horizontal' | 'vertical';
type RenderComponentProps<T> = {|
data: T,
index: number,
isScrolling?: boolean,
style: Object,
|};
type RenderComponent<T> = React$ComponentType<$Shape<RenderComponentProps<T>>>;
type ScrollDirection = 'forward' | 'backward';
type onItemsRenderedCallback = ({
overscanStartIndex: number,
overscanStopIndex: number,
visibleStartIndex: number,
visibleStopIndex: number,
}) => void;
type onScrollCallback = ({
scrollDirection: ScrollDirection,
scrollOffset: number,
scrollUpdateWasRequested: boolean,
}) => void;
type ScrollEvent = SyntheticEvent<HTMLDivElement>;
type ItemStyleCache = { [index: number]: Object };
type OuterProps = {|
children: React$Node,
className: string | void,
onScroll: ScrollEvent => void,
style: {
[string]: mixed,
},
|};
type InnerProps = {|
children: React$Node,
style: {
[string]: mixed,
},
|};
export type Props<T> = {|
children: RenderComponent<T>,
className?: string,
direction: Direction,
height: number | string,
initialScrollOffset?: number,
innerRef?: any,
innerElementType?: string | React.AbstractComponent<InnerProps, any>,
innerTagName?: string, // deprecated
itemCount: number,
itemData: T,
itemKey?: (index: number, data: T) => any,
itemSize: itemSize,
layout: Layout,
onItemsRendered?: onItemsRenderedCallback,
onScroll?: onScrollCallback,
outerRef?: any,
outerElementType?: string | React.AbstractComponent<OuterProps, any>,
outerTagName?: string, // deprecated
overscanCount: number,
style?: Object,
useIsScrolling: boolean,
width: number | string,
|};
type State = {|
instance: any,
isScrolling: boolean,
scrollDirection: ScrollDirection,
scrollOffset: number,
scrollUpdateWasRequested: boolean,
|};
type GetItemOffset = (
props: Props<any>,
index: number,
instanceProps: any
) => number;
type GetItemSize = (
props: Props<any>,
index: number,
instanceProps: any
) => number;
type GetEstimatedTotalSize = (props: Props<any>, instanceProps: any) => number;
type GetOffsetForIndexAndAlignment = (
props: Props<any>,
index: number,
align: ScrollToAlign,
scrollOffset: number,
instanceProps: any
) => number;
type GetStartIndexForOffset = (
props: Props<any>,
offset: number,
instanceProps: any
) => number;
type GetStopIndexForStartIndex = (
props: Props<any>,
startIndex: number,
scrollOffset: number,
instanceProps: any
) => number;
type InitInstanceProps = (props: Props<any>, instance: any) => any;
type ValidateProps = (props: Props<any>) => void;
const IS_SCROLLING_DEBOUNCE_INTERVAL = 150;
const defaultItemKey = (index: number, data: any) => index;
// In DEV mode, this Set helps us only log a warning once per component instance.
// This avoids spamming the console every time a render happens.
let devWarningsDirection = null;
let devWarningsTagName = null;
if (process.env.NODE_ENV !== 'production') {
if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') {
devWarningsDirection = new WeakSet();
devWarningsTagName = new WeakSet();
}
}
export default function createListComponent({
getItemOffset,
getEstimatedTotalSize,
getItemSize,
getOffsetForIndexAndAlignment,
getStartIndexForOffset,
getStopIndexForStartIndex,
initInstanceProps,
shouldResetStyleCacheOnItemSizeChange,
validateProps,
}: {|
getItemOffset: GetItemOffset,
getEstimatedTotalSize: GetEstimatedTotalSize,
getItemSize: GetItemSize,
getOffsetForIndexAndAlignment: GetOffsetForIndexAndAlignment,
getStartIndexForOffset: GetStartIndexForOffset,
getStopIndexForStartIndex: GetStopIndexForStartIndex,
initInstanceProps: InitInstanceProps,
shouldResetStyleCacheOnItemSizeChange: boolean,
validateProps: ValidateProps,
|}): React.ComponentType<Props<$FlowFixMe>> {
return class List<T> extends PureComponent<Props<T>, State> {
_instanceProps: any = initInstanceProps(this.props, this);
_outerRef: ?HTMLDivElement;
_resetIsScrollingTimeoutId: TimeoutID | null = null;
static defaultProps: {
direction: string,
itemData: void,
layout: string,
overscanCount: number,
useIsScrolling: boolean,
} = {
direction: 'ltr',
itemData: undefined,
layout: 'vertical',
overscanCount: 2,
useIsScrolling: false,
};
state: State = {
instance: this,
isScrolling: false,
scrollDirection: 'forward',
scrollOffset:
typeof this.props.initialScrollOffset === 'number'
? this.props.initialScrollOffset
: 0,
scrollUpdateWasRequested: false,
};
// Always use explicit constructor for React components.
// It produces less code after transpilation. (#26)
// eslint-disable-next-line no-useless-constructor
constructor(props: Props<T>) {
super(props);
}
static getDerivedStateFromProps(
nextProps: Props<T>,
prevState: State
): $Shape<State> | null {
validateSharedProps(nextProps, prevState);
validateProps(nextProps);
return null;
}
scrollTo(scrollOffset: number): void {
scrollOffset = Math.max(0, scrollOffset);
this.setState(prevState => {
if (prevState.scrollOffset === scrollOffset) {
return null;
}
return {
scrollDirection:
prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
scrollOffset: scrollOffset,
scrollUpdateWasRequested: true,
};
}, this._resetIsScrollingDebounced);
}
scrollToItem(index: number, align: ScrollToAlign = 'auto'): void {
const { itemCount } = this.props;
const { scrollOffset } = this.state;
index = Math.max(0, Math.min(index, itemCount - 1));
this.scrollTo(
getOffsetForIndexAndAlignment(
this.props,
index,
align,
scrollOffset,
this._instanceProps
)
);
}
componentDidMount() {
const { direction, initialScrollOffset, layout } = this.props;
if (typeof initialScrollOffset === 'number' && this._outerRef != null) {
const outerRef = ((this._outerRef: any): HTMLElement);
// TODO Deprecate direction "horizontal"
if (direction === 'horizontal' || layout === 'horizontal') {
outerRef.scrollLeft = initialScrollOffset;
} else {
outerRef.scrollTop = initialScrollOffset;
}
}
this._callPropsCallbacks();
}
componentDidUpdate() {
const { direction, layout } = this.props;
const { scrollOffset, scrollUpdateWasRequested } = this.state;
if (scrollUpdateWasRequested && this._outerRef != null) {
const outerRef = ((this._outerRef: any): HTMLElement);
// TODO Deprecate direction "horizontal"
if (direction === 'horizontal' || layout === 'horizontal') {
if (direction === 'rtl') {
// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// So we need to determine which browser behavior we're dealing with, and mimic it.
switch (getRTLOffsetType()) {
case 'negative':
outerRef.scrollLeft = -scrollOffset;
break;
case 'positive-ascending':
outerRef.scrollLeft = scrollOffset;
break;
default:
const { clientWidth, scrollWidth } = outerRef;
outerRef.scrollLeft = scrollWidth - clientWidth - scrollOffset;
break;
}
} else {
outerRef.scrollLeft = scrollOffset;
}
} else {
outerRef.scrollTop = scrollOffset;
}
}
this._callPropsCallbacks();
}
componentWillUnmount() {
if (this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(this._resetIsScrollingTimeoutId);
}
}
render(): any {
const {
children,
className,
direction,
height,
innerRef,
innerElementType,
innerTagName,
itemCount,
itemData,
itemKey = defaultItemKey,
layout,
outerElementType,
outerTagName,
style,
useIsScrolling,
width,
} = this.props;
const { isScrolling } = this.state;
// TODO Deprecate direction "horizontal"
const isHorizontal =
direction === 'horizontal' || layout === 'horizontal';
const onScroll = isHorizontal
? this._onScrollHorizontal
: this._onScrollVertical;
const [startIndex, stopIndex] = this._getRangeToRender();
const items = [];
if (itemCount > 0) {
for (let index = startIndex; index <= stopIndex; index++) {
items.push(
createElement(children, {
data: itemData,
key: itemKey(index, itemData),
index,
isScrolling: useIsScrolling ? isScrolling : undefined,
style: this._getItemStyle(index),
})
);
}
}
// Read this value AFTER items have been created,
// So their actual sizes (if variable) are taken into consideration.
const estimatedTotalSize = getEstimatedTotalSize(
this.props,
this._instanceProps
);
return createElement(
outerElementType || outerTagName || 'div',
{
className,
onScroll,
ref: this._outerRefSetter,
style: {
position: 'relative',
height,
width,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
direction,
...style,
},
},
createElement(innerElementType || innerTagName || 'div', {
children: items,
ref: innerRef,
style: {
height: isHorizontal ? '100%' : estimatedTotalSize,
pointerEvents: isScrolling ? 'none' : undefined,
width: isHorizontal ? estimatedTotalSize : '100%',
},
})
);
}
_callOnItemsRendered: ((
overscanStartIndex: number,
overscanStopIndex: number,
visibleStartIndex: number,
visibleStopIndex: number
) => void) = memoizeOne(
(
overscanStartIndex: number,
overscanStopIndex: number,
visibleStartIndex: number,
visibleStopIndex: number
) =>
((this.props.onItemsRendered: any): onItemsRenderedCallback)({
overscanStartIndex,
overscanStopIndex,
visibleStartIndex,
visibleStopIndex,
})
);
_callOnScroll: ((
scrollDirection: ScrollDirection,
scrollOffset: number,
scrollUpdateWasRequested: boolean
) => void) = memoizeOne(
(
scrollDirection: ScrollDirection,
scrollOffset: number,
scrollUpdateWasRequested: boolean
) =>
((this.props.onScroll: any): onScrollCallback)({
scrollDirection,
scrollOffset,
scrollUpdateWasRequested,
})
);
_callPropsCallbacks() {
if (typeof this.props.onItemsRendered === 'function') {
const { itemCount } = this.props;
if (itemCount > 0) {
const [
overscanStartIndex,
overscanStopIndex,
visibleStartIndex,
visibleStopIndex,
] = this._getRangeToRender();
this._callOnItemsRendered(
overscanStartIndex,
overscanStopIndex,
visibleStartIndex,
visibleStopIndex
);
}
}
if (typeof this.props.onScroll === 'function') {
const {
scrollDirection,
scrollOffset,
scrollUpdateWasRequested,
} = this.state;
this._callOnScroll(
scrollDirection,
scrollOffset,
scrollUpdateWasRequested
);
}
}
// Lazily create and cache item styles while scrolling,
// So that pure component sCU will prevent re-renders.
// We maintain this cache, and pass a style prop rather than index,
// So that List can clear cached styles and force item re-render if necessary.
_getItemStyle = (index: number): Object => {
const { direction, itemSize, layout } = this.props;
const itemStyleCache = this._getItemStyleCache(
shouldResetStyleCacheOnItemSizeChange && itemSize,
shouldResetStyleCacheOnItemSizeChange && layout,
shouldResetStyleCacheOnItemSizeChange && direction
);
let style;
if (itemStyleCache.hasOwnProperty(index)) {
style = itemStyleCache[index];
} else {
const offset = getItemOffset(this.props, index, this._instanceProps);
const size = getItemSize(this.props, index, this._instanceProps);
// TODO Deprecate direction "horizontal"
const isHorizontal =
direction === 'horizontal' || layout === 'horizontal';
itemStyleCache[index] = style = {
position: 'absolute',
// $FlowFixMe computed properties are unsupported
[direction === 'rtl' ? 'right' : 'left']: isHorizontal ? offset : 0,
top: !isHorizontal ? offset : 0,
height: !isHorizontal ? size : '100%',
width: isHorizontal ? size : '100%',
};
}
return style;
};
_getItemStyleCache: ((_: any, __: any, ___: any) => ItemStyleCache) =
memoizeOne((_: any, __: any, ___: any) => ({}));
_getRangeToRender(): [number, number, number, number] {
const { itemCount, overscanCount } = this.props;
const { isScrolling, scrollDirection, scrollOffset } = this.state;
if (itemCount === 0) {
return [0, 0, 0, 0];
}
const startIndex = getStartIndexForOffset(
this.props,
scrollOffset,
this._instanceProps
);
const stopIndex = getStopIndexForStartIndex(
this.props,
startIndex,
scrollOffset,
this._instanceProps
);
// Overscan by one item in each direction so that tab/focus works.
// If there isn't at least one extra item, tab loops back around.
const overscanBackward =
!isScrolling || scrollDirection === 'backward'
? Math.max(1, overscanCount)
: 1;
const overscanForward =
!isScrolling || scrollDirection === 'forward'
? Math.max(1, overscanCount)
: 1;
return [
Math.max(0, startIndex - overscanBackward),
Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)),
startIndex,
stopIndex,
];
}
_onScrollHorizontal = (event: ScrollEvent): void => {
const { clientWidth, scrollLeft, scrollWidth } = event.currentTarget;
this.setState(prevState => {
if (prevState.scrollOffset === scrollLeft) {
// Scroll position may have been updated by cDM/cDU,
// In which case we don't need to trigger another render,
// And we don't want to update state.isScrolling.
return null;
}
const { direction } = this.props;
let scrollOffset = scrollLeft;
if (direction === 'rtl') {
// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// It's also easier for this component if we convert offsets to the same format as they would be in for ltr.
// So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.
switch (getRTLOffsetType()) {
case 'negative':
scrollOffset = -scrollLeft;
break;
case 'positive-descending':
scrollOffset = scrollWidth - clientWidth - scrollLeft;
break;
}
}
// Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
scrollOffset = Math.max(
0,
Math.min(scrollOffset, scrollWidth - clientWidth)
);
return {
isScrolling: true,
scrollDirection:
prevState.scrollOffset < scrollLeft ? 'forward' : 'backward',
scrollOffset,
scrollUpdateWasRequested: false,
};
}, this._resetIsScrollingDebounced);
};
_onScrollVertical = (event: ScrollEvent): void => {
const { clientHeight, scrollHeight, scrollTop } = event.currentTarget;
this.setState(prevState => {
if (prevState.scrollOffset === scrollTop) {
// Scroll position may have been updated by cDM/cDU,
// In which case we don't need to trigger another render,
// And we don't want to update state.isScrolling.
return null;
}
// Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
const scrollOffset = Math.max(
0,
Math.min(scrollTop, scrollHeight - clientHeight)
);
return {
isScrolling: true,
scrollDirection:
prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
scrollOffset,
scrollUpdateWasRequested: false,
};
}, this._resetIsScrollingDebounced);
};
_outerRefSetter = (ref: any): void => {
const { outerRef } = this.props;
this._outerRef = ((ref: any): HTMLDivElement);
if (typeof outerRef === 'function') {
outerRef(ref);
} else if (
outerRef != null &&
typeof outerRef === 'object' &&
outerRef.hasOwnProperty('current')
) {
outerRef.current = ref;
}
};
_resetIsScrollingDebounced = () => {
if (this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(this._resetIsScrollingTimeoutId);
}
this._resetIsScrollingTimeoutId = requestTimeout(
this._resetIsScrolling,
IS_SCROLLING_DEBOUNCE_INTERVAL
);
};
_resetIsScrolling = () => {
this._resetIsScrollingTimeoutId = null;
this.setState({ isScrolling: false }, () => {
// Clear style cache after state update has been committed.
// This way we don't break pure sCU for items that don't use isScrolling param.
this._getItemStyleCache(-1, null);
});
};
};
}
// NOTE: I considered further wrapping individual items with a pure ListItem component.
// This would avoid ever calling the render function for the same index more than once,
// But it would also add the overhead of a lot of components/fibers.
// I assume people already do this (render function returning a class component),
// So my doing it would just unnecessarily double the wrappers.
const validateSharedProps = (
{
children,
direction,
height,
layout,
innerTagName,
outerTagName,
width,
}: Props<any>,
{ instance }: State
): void => {
if (process.env.NODE_ENV !== 'production') {
if (innerTagName != null || outerTagName != null) {
if (devWarningsTagName && !devWarningsTagName.has(instance)) {
devWarningsTagName.add(instance);
console.warn(
'The innerTagName and outerTagName props have been deprecated. ' +
'Please use the innerElementType and outerElementType props instead.'
);
}
}
// TODO Deprecate direction "horizontal"
const isHorizontal = direction === 'horizontal' || layout === 'horizontal';
switch (direction) {
case 'horizontal':
case 'vertical':
if (devWarningsDirection && !devWarningsDirection.has(instance)) {
devWarningsDirection.add(instance);
console.warn(
'The direction prop should be either "ltr" (default) or "rtl". ' +
'Please use the layout prop to specify "vertical" (default) or "horizontal" orientation.'
);
}
break;
case 'ltr':
case 'rtl':
// Valid values
break;
default:
throw Error(
'An invalid "direction" prop has been specified. ' +
'Value should be either "ltr" or "rtl". ' +
`"${direction}" was specified.`
);
}
switch (layout) {
case 'horizontal':
case 'vertical':
// Valid values
break;
default:
throw Error(
'An invalid "layout" prop has been specified. ' +
'Value should be either "horizontal" or "vertical". ' +
`"${layout}" was specified.`
);
}
if (children == null) {
throw Error(
'An invalid "children" prop has been specified. ' +
'Value should be a React component. ' +
`"${children === null ? 'null' : typeof children}" was specified.`
);
}
if (isHorizontal && typeof width !== 'number') {
throw Error(
'An invalid "width" prop has been specified. ' +
'Horizontal lists must specify a number for width. ' +
`"${width === null ? 'null' : typeof width}" was specified.`
);
} else if (!isHorizontal && typeof height !== 'number') {
throw Error(
'An invalid "height" prop has been specified. ' +
'Vertical lists must specify a number for height. ' +
`"${height === null ? 'null' : typeof height}" was specified.`
);
}
}
};
| 29.603022 | 132 | 0.607819 |
owtf | const React = window.React;
class HitBox extends React.Component {
state = {
x: 0,
y: 0,
};
static defaultProps = {
onMouseMove: n => n,
};
onMove = event => {
this.setState({x: event.clientX, y: event.clientY});
this.props.onMouseMove(event);
};
render() {
const {x, y} = this.state;
const boxStyle = {
padding: '10px 20px',
border: '1px solid #d9d9d9',
margin: '10px 0 20px',
};
return (
<div onMouseMove={this.onMove} style={boxStyle}>
<p>Trace your mouse over this box.</p>
<p>
Last movement: {x},{y}
</p>
</div>
);
}
}
export default HitBox;
| 16.307692 | 56 | 0.534125 |
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 ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');
let React;
let ReactDOM;
let ReactDOMClient;
let ReactDOMServer;
let ReactTestUtils;
let act;
let SuspenseList;
function initModules() {
// Reset warning cache.
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
act = require('internal-test-utils').act;
if (gate(flags => flags.enableSuspenseList)) {
SuspenseList = React.unstable_SuspenseList;
}
// Make them available to the helpers.
return {
ReactDOM,
ReactDOMServer,
ReactTestUtils,
};
}
const {itThrowsWhenRendering, resetModules, serverRender} =
ReactDOMServerIntegrationUtils(initModules);
describe('ReactDOMServerSuspense', () => {
beforeEach(() => {
resetModules();
});
function Text(props) {
return <div>{props.text}</div>;
}
function AsyncText(props) {
throw new Promise(() => {});
}
function getVisibleChildren(element) {
const children = [];
let node = element.firstChild;
while (node) {
if (node.nodeType === 1) {
if (
node.tagName !== 'SCRIPT' &&
node.tagName !== 'TEMPLATE' &&
node.tagName !== 'template' &&
!node.hasAttribute('hidden') &&
!node.hasAttribute('aria-hidden')
) {
const props = {};
const attributes = node.attributes;
for (let i = 0; i < attributes.length; i++) {
if (
attributes[i].name === 'id' &&
attributes[i].value.includes(':')
) {
// We assume this is a React added ID that's a non-visual implementation detail.
continue;
}
props[attributes[i].name] = attributes[i].value;
}
props.children = getVisibleChildren(node);
children.push(React.createElement(node.tagName.toLowerCase(), props));
}
} else if (node.nodeType === 3) {
children.push(node.data);
}
node = node.nextSibling;
}
return children.length === 0
? undefined
: children.length === 1
? children[0]
: children;
}
it('should render the children when no promise is thrown', async () => {
const c = await serverRender(
<div>
<React.Suspense fallback={<Text text="Fallback" />}>
<Text text="Children" />
</React.Suspense>
</div>,
);
expect(getVisibleChildren(c)).toEqual(<div>Children</div>);
});
it('should render the fallback when a promise thrown', async () => {
const c = await serverRender(
<div>
<React.Suspense fallback={<Text text="Fallback" />}>
<AsyncText text="Children" />
</React.Suspense>
</div>,
);
expect(getVisibleChildren(c)).toEqual(<div>Fallback</div>);
});
it('should work with nested suspense components', async () => {
const c = await serverRender(
<div>
<React.Suspense fallback={<Text text="Fallback" />}>
<div>
<Text text="Children" />
<React.Suspense fallback={<Text text="Fallback" />}>
<AsyncText text="Children" />
</React.Suspense>
</div>
</React.Suspense>
</div>,
);
expect(getVisibleChildren(c)).toEqual(
<div>
<div>Children</div>
<div>Fallback</div>
</div>,
);
});
// @gate enableSuspenseList
it('server renders a SuspenseList component and its children', async () => {
const example = (
<SuspenseList>
<React.Suspense fallback="Loading A">
<div>A</div>
</React.Suspense>
<React.Suspense fallback="Loading B">
<div>B</div>
</React.Suspense>
</SuspenseList>
);
const element = await serverRender(example);
const parent = element.parentNode;
const divA = parent.children[0];
expect(divA.tagName).toBe('DIV');
expect(divA.textContent).toBe('A');
const divB = parent.children[1];
expect(divB.tagName).toBe('DIV');
expect(divB.textContent).toBe('B');
await act(() => {
ReactDOMClient.hydrateRoot(parent, example);
});
const parent2 = element.parentNode;
const divA2 = parent2.children[0];
const divB2 = parent2.children[1];
expect(divA).toBe(divA2);
expect(divB).toBe(divB2);
});
// TODO: Remove this in favor of @gate pragma
if (__EXPERIMENTAL__) {
itThrowsWhenRendering(
'a suspending component outside a Suspense node',
async render => {
await render(
<div>
<React.Suspense />
<AsyncText text="Children" />
<React.Suspense />
</div>,
1,
);
},
'A component suspended while responding to synchronous input.',
);
itThrowsWhenRendering(
'a suspending component without a Suspense above',
async render => {
await render(
<div>
<AsyncText text="Children" />
</div>,
1,
);
},
'A component suspended while responding to synchronous input.',
);
}
it('does not get confused by throwing null', () => {
function Bad() {
// eslint-disable-next-line no-throw-literal
throw null;
}
let didError;
let error;
try {
ReactDOMServer.renderToString(<Bad />);
} catch (err) {
didError = true;
error = err;
}
expect(didError).toBe(true);
expect(error).toBe(null);
});
it('does not get confused by throwing undefined', () => {
function Bad() {
// eslint-disable-next-line no-throw-literal
throw undefined;
}
let didError;
let error;
try {
ReactDOMServer.renderToString(<Bad />);
} catch (err) {
didError = true;
error = err;
}
expect(didError).toBe(true);
expect(error).toBe(undefined);
});
it('does not get confused by throwing a primitive', () => {
function Bad() {
// eslint-disable-next-line no-throw-literal
throw 'foo';
}
let didError;
let error;
try {
ReactDOMServer.renderToString(<Bad />);
} catch (err) {
didError = true;
error = err;
}
expect(didError).toBe(true);
expect(error).toBe('foo');
});
});
| 24.723077 | 94 | 0.576791 |
owtf | const React = window.React;
function csv(string) {
return string.split(/\s*,\s*/);
}
export default function IssueList({issues}) {
if (!issues) {
return null;
}
if (typeof issues === 'string') {
issues = csv(issues);
}
let links = issues.reduce((memo, issue, i) => {
return memo.concat(
i > 0 && i < issues.length ? ', ' : null,
<a href={'https://github.com/facebook/react/issues/' + issue} key={issue}>
{issue}
</a>
);
}, []);
return <span>{links}</span>;
}
| 18.37037 | 80 | 0.549808 |
null | #!/usr/bin/env node
'use strict';
const {exec} = require('child-process-promise');
const {join} = require('path');
const puppeteer = require('puppeteer');
const server = require('pushstate-server');
const theme = require('../theme');
const {logPromise} = require('../utils');
const validate = async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://localhost:9000/fixtures/packaging');
try {
return await page.evaluate(() => {
const iframes = document.querySelectorAll('iframe');
if (iframes.length === 0) {
return 'No iframes were found.';
}
for (let i = 0; i < iframes.length; i++) {
const iframe = iframes[i];
// Don't include the <script> Babel tag
const container =
iframe.contentDocument.body.getElementsByTagName('div')[0];
if (container.textContent !== 'Hello World!') {
return `Unexpected fixture content, "${container.textContent}"`;
}
}
return null;
});
} finally {
await browser.close();
}
};
const run = async ({cwd}) => {
await logPromise(
exec('node build-all.js', {cwd: join(cwd, 'fixtures/packaging')}),
'Generating "packaging" fixture',
20000 // This takes roughly 20 seconds
);
let errorMessage;
let response;
try {
response = server.start({
port: 9000,
directory: cwd,
});
errorMessage = await logPromise(
validate(),
'Verifying "packaging" fixture'
);
} finally {
response.close();
}
if (errorMessage) {
console.error(
theme.error('✗'),
'Verifying "packaging" fixture\n ',
theme.error(errorMessage)
);
process.exit(1);
}
};
module.exports = run;
| 21.769231 | 74 | 0.598873 |
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.
*
* @emails react-core
*/
'use strict';
let formatProdErrorMessage;
describe('ReactErrorProd', () => {
beforeEach(() => {
jest.resetModules();
formatProdErrorMessage = require('shared/formatProdErrorMessage').default;
});
it('should throw with the correct number of `%s`s in the URL', () => {
expect(formatProdErrorMessage(124, 'foo', 'bar')).toEqual(
'Minified React error #124; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=124&args[]=foo&args[]=bar' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.',
);
expect(formatProdErrorMessage(20)).toEqual(
'Minified React error #20; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=20' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.',
);
expect(formatProdErrorMessage(77, '<div>', '&?bar')).toEqual(
'Minified React error #77; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=77&args[]=%3Cdiv%3E&args[]=%26%3Fbar' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.',
);
});
});
| 34.952381 | 102 | 0.656064 |
PenetrationTestingScripts | /* global chrome */
'use strict';
import setExtensionIconAndPopup from './setExtensionIconAndPopup';
function isRestrictedBrowserPage(url) {
return !url || new URL(url).protocol === 'chrome:';
}
function checkAndHandleRestrictedPageIfSo(tab) {
if (tab && isRestrictedBrowserPage(tab.url)) {
setExtensionIconAndPopup('restricted', tab.id);
}
}
// update popup page of any existing open tabs, if they are restricted browser pages.
// we can't update for any other types (prod,dev,outdated etc)
// as the content script needs to be injected at document_start itself for those kinds of detection
// TODO: Show a different popup page(to reload current page probably) for old tabs, opened before the extension is installed
if (__IS_CHROME__ || __IS_EDGE__) {
chrome.tabs.query({}, tabs => tabs.forEach(checkAndHandleRestrictedPageIfSo));
chrome.tabs.onCreated.addListener((tabId, changeInfo, tab) =>
checkAndHandleRestrictedPageIfSo(tab),
);
}
// Listen to URL changes on the active tab and update the DevTools icon.
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (__IS_FIREFOX__) {
// We don't properly detect protected URLs in Firefox at the moment.
// However, we can reset the DevTools icon to its loading state when the URL changes.
// It will be updated to the correct icon by the onMessage callback below.
if (tab.active && changeInfo.status === 'loading') {
setExtensionIconAndPopup('disabled', tabId);
}
} else {
// Don't reset the icon to the loading state for Chrome or Edge.
// The onUpdated callback fires more frequently for these browsers,
// often after onMessage has been called.
checkAndHandleRestrictedPageIfSo(tab);
}
});
| 38.340909 | 124 | 0.723121 |
owtf | import Fixture from '../../Fixture';
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
const React = window.React;
export default class TextAreaFixtures extends React.Component {
state = {value: ''};
onChange = event => {
this.setState({value: event.target.value});
};
render() {
return (
<FixtureSet title="Textareas">
<TestCase
title="Kitchen Sink"
description="Verify that the controlled textarea displays its value under 'Controlled Output', and that both textareas can be typed in">
<div>
<form className="container">
<fieldset>
<legend>Controlled</legend>
<textarea value={this.state.value} onChange={this.onChange} />
</fieldset>
<fieldset>
<legend>Uncontrolled</legend>
<textarea defaultValue="" />
</fieldset>
</form>
<div className="container">
<h4>Controlled Output:</h4>
<div className="output">{this.state.value}</div>
</div>
</div>
</TestCase>
<TestCase title="Placeholders">
<TestCase.ExpectedResult>
The textarea should be rendered with the placeholder "Hello, world"
</TestCase.ExpectedResult>
<div style={{margin: '10px 0px'}}>
<textarea placeholder="Hello, world" />
</div>
</TestCase>
<TestCase
title="Required Textareas"
affectedBrowsers="Firefox"
relatedIssues="16402">
<TestCase.Steps>
<li>View this test in Firefox</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
You should{' '}
<b>
<i>not</i>
</b>{' '}
see a red aura on initial page load, indicating the textarea is
invalid.
<br />
This aura looks roughly like:
<textarea style={{boxShadow: '0 0 1px 1px red', marginLeft: 8}} />
</TestCase.ExpectedResult>
<Fixture>
<form className="control-box">
<fieldset>
<legend>Empty value prop string</legend>
<textarea value="" required={true} />
</fieldset>
<fieldset>
<legend>No value prop</legend>
<textarea required={true} />
</fieldset>
<fieldset>
<legend>Empty defaultValue prop string</legend>
<textarea required={true} defaultValue="" />
</fieldset>
</form>
</Fixture>
</TestCase>
</FixtureSet>
);
}
}
| 31.505882 | 146 | 0.51412 |
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.
*
* @emails react-core
*/
'use strict';
// Polyfills for test environment
global.ReadableStream =
require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;
global.TextDecoder = require('util').TextDecoder;
// Don't wait before processing work on the server.
// TODO: we can replace this with FlightServer.act().
global.setTimeout = cb => cb();
let clientExports;
let webpackMap;
let webpackModules;
let webpackModuleLoading;
let React;
let ReactDOMServer;
let ReactServerDOMServer;
let ReactServerDOMClient;
let use;
describe('ReactFlightDOMEdge', () => {
beforeEach(() => {
jest.resetModules();
// Simulate the condition resolution
jest.mock('react', () => require('react/react.shared-subset'));
jest.mock('react-server-dom-webpack/server', () =>
require('react-server-dom-webpack/server.edge'),
);
const WebpackMock = require('./utils/WebpackMock');
clientExports = WebpackMock.clientExports;
webpackMap = WebpackMock.webpackMap;
webpackModules = WebpackMock.webpackModules;
webpackModuleLoading = WebpackMock.moduleLoading;
ReactServerDOMServer = require('react-server-dom-webpack/server');
jest.resetModules();
__unmockReact();
jest.unmock('react-server-dom-webpack/server');
jest.mock('react-server-dom-webpack/client', () =>
require('react-server-dom-webpack/client.edge'),
);
React = require('react');
ReactDOMServer = require('react-dom/server.edge');
ReactServerDOMClient = require('react-server-dom-webpack/client');
use = React.use;
});
function passThrough(stream) {
// Simulate more realistic network by splitting up and rejoining some chunks.
// This lets us test that we don't accidentally rely on particular bounds of the chunks.
return new ReadableStream({
async start(controller) {
const reader = stream.getReader();
let prevChunk = new Uint8Array(0);
function push() {
reader.read().then(({done, value}) => {
if (done) {
controller.enqueue(prevChunk);
controller.close();
return;
}
const chunk = new Uint8Array(prevChunk.length + value.length);
chunk.set(prevChunk, 0);
chunk.set(value, prevChunk.length);
if (chunk.length > 50) {
controller.enqueue(chunk.subarray(0, chunk.length - 50));
prevChunk = chunk.subarray(chunk.length - 50);
} else {
prevChunk = chunk;
}
push();
});
}
push();
},
});
}
async function readResult(stream) {
const reader = stream.getReader();
let result = '';
while (true) {
const {done, value} = await reader.read();
if (done) {
return result;
}
result += Buffer.from(value).toString('utf8');
}
}
it('should allow an alternative module mapping to be used for SSR', async () => {
function ClientComponent() {
return <span>Client Component</span>;
}
// The Client build may not have the same IDs as the Server bundles for the same
// component.
const ClientComponentOnTheClient = clientExports(ClientComponent);
const ClientComponentOnTheServer = clientExports(ClientComponent);
// In the SSR bundle this module won't exist. We simulate this by deleting it.
const clientId = webpackMap[ClientComponentOnTheClient.$$id].id;
delete webpackModules[clientId];
// Instead, we have to provide a translation from the client meta data to the SSR
// meta data.
const ssrMetadata = webpackMap[ClientComponentOnTheServer.$$id];
const translationMap = {
[clientId]: {
'*': ssrMetadata,
},
};
function App() {
return <ClientComponentOnTheClient />;
}
const stream = ReactServerDOMServer.renderToReadableStream(
<App />,
webpackMap,
);
const response = ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: translationMap,
moduleLoading: webpackModuleLoading,
},
});
function ClientRoot() {
return use(response);
}
const ssrStream = await ReactDOMServer.renderToReadableStream(
<ClientRoot />,
);
const result = await readResult(ssrStream);
expect(result).toEqual('<span>Client Component</span>');
});
it('should encode long string in a compact format', async () => {
const testString = '"\n\t'.repeat(500) + '🙃';
const testString2 = 'hello'.repeat(400);
const stream = ReactServerDOMServer.renderToReadableStream({
text: testString,
text2: testString2,
});
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
// The content should be compact an unescaped
expect(serializedContent.length).toBeLessThan(4000);
expect(serializedContent).not.toContain('\\n');
expect(serializedContent).not.toContain('\\t');
expect(serializedContent).not.toContain('\\"');
expect(serializedContent).toContain('\t');
const result = await ReactServerDOMClient.createFromReadableStream(
stream2,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
// Should still match the result when parsed
expect(result.text).toBe(testString);
expect(result.text2).toBe(testString2);
});
it('should encode repeated objects in a compact format by deduping', async () => {
const obj = {
this: {is: 'a large objected'},
with: {many: 'properties in it'},
};
const props = {
items: new Array(30).fill(obj),
};
const stream = ReactServerDOMServer.renderToReadableStream(props);
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
expect(serializedContent.length).toBeLessThan(400);
const result = await ReactServerDOMClient.createFromReadableStream(
stream2,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
// Should still match the result when parsed
expect(result).toEqual(props);
expect(result.items[5]).toBe(result.items[10]); // two random items are the same instance
// TODO: items[0] is not the same as the others in this case
});
it('should execute repeated server components only once', async () => {
const str = 'this is a long return value';
let timesRendered = 0;
function ServerComponent() {
timesRendered++;
return str;
}
const element = <ServerComponent />;
const children = new Array(30).fill(element);
const resolvedChildren = new Array(30).fill(str);
const stream = ReactServerDOMServer.renderToReadableStream(children);
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
expect(serializedContent.length).toBeLessThan(400);
expect(timesRendered).toBeLessThan(5);
const result = await ReactServerDOMClient.createFromReadableStream(
stream2,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
// Should still match the result when parsed
expect(result).toEqual(resolvedChildren);
});
// @gate enableBinaryFlight
it('should be able to serialize any kind of typed array', async () => {
const buffer = new Uint8Array([
123, 4, 10, 5, 100, 255, 244, 45, 56, 67, 43, 124, 67, 89, 100, 20,
]).buffer;
const buffers = [
buffer,
new Int8Array(buffer, 1),
new Uint8Array(buffer, 2),
new Uint8ClampedArray(buffer, 2),
new Int16Array(buffer, 2),
new Uint16Array(buffer, 2),
new Int32Array(buffer, 4),
new Uint32Array(buffer, 4),
new Float32Array(buffer, 4),
new Float64Array(buffer, 0),
new BigInt64Array(buffer, 0),
new BigUint64Array(buffer, 0),
new DataView(buffer, 3),
];
const stream = passThrough(
ReactServerDOMServer.renderToReadableStream(buffers),
);
const result = await ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
expect(result).toEqual(buffers);
});
});
| 30.155235 | 93 | 0.644107 |
null | 'use strict';
const Sequencer = require('@jest/test-sequencer').default;
class CustomSequencer extends Sequencer {
sort(tests) {
if (process.env.CIRCLE_NODE_TOTAL) {
// In CI, parallelize tests across multiple tasks.
const nodeTotal = parseInt(process.env.CIRCLE_NODE_TOTAL, 10);
const nodeIndex = parseInt(process.env.CIRCLE_NODE_INDEX, 10);
tests = tests
.sort((a, b) => (a.path < b.path ? -1 : 1))
.filter((_, i) => i % nodeTotal === nodeIndex);
}
return tests;
}
}
module.exports = CustomSequencer;
| 27.15 | 68 | 0.633452 |
Python-Penetration-Testing-for-Developers | 'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-server-dom-turbopack-server.node.unbundled.production.min.js');
} else {
module.exports = require('./cjs/react-server-dom-turbopack-server.node.unbundled.development.js');
}
| 33.625 | 103 | 0.724638 |
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 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireDefault(require("react"));
var _useTheme = _interopRequireDefault(require("./useTheme"));
var _jsxFileName = "";
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Component() {
const theme = (0, _useTheme.default)();
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 10
}
}, "theme: ", theme);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsS0FBSyxHQUFHLHdCQUFkO0FBRUEsc0JBQU87QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsZ0JBQWFBLEtBQWIsQ0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCc7XG5pbXBvcnQgdXNlVGhlbWUgZnJvbSAnLi91c2VUaGVtZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlVGhlbWUoKTtcblxuICByZXR1cm4gPGRpdj50aGVtZToge3RoZW1lfTwvZGl2Pjtcbn1cbiJdLCJ4X3JlYWN0X3NvdXJjZXMiOltbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJ0aGVtZSJdLCJtYXBwaW5ncyI6IkNBQUQ7Y2dCQ0EsQVVEQSJ9XV19fV19 | 65.230769 | 1,120 | 0.868681 |
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';
let React;
let ReactDOM;
describe('BeforeInputEventPlugin', () => {
let container;
function loadReactDOM(envSimulator) {
jest.resetModules();
if (envSimulator) {
envSimulator();
}
return require('react-dom');
}
function simulateIE11() {
document.documentMode = 11;
window.CompositionEvent = {};
}
function simulateWebkit() {
window.CompositionEvent = {};
window.TextEvent = {};
}
function simulateComposition() {
window.CompositionEvent = {};
}
function simulateNoComposition() {
// no composition event in Window - will use fallback
}
function simulateEvent(elem, type, data) {
const event = new Event(type, {bubbles: true});
Object.assign(event, data);
elem.dispatchEvent(event);
}
function simulateKeyboardEvent(elem, type, data) {
const {char, value, ...rest} = data;
const event = new KeyboardEvent(type, {
bubbles: true,
...rest,
});
if (char) {
event.char = char;
}
if (value) {
elem.value = value;
}
elem.dispatchEvent(event);
}
function simulatePaste(elem) {
const pasteEvent = new Event('paste', {
bubbles: true,
});
pasteEvent.clipboardData = {
dropEffect: null,
effectAllowed: null,
files: null,
items: null,
types: null,
};
elem.dispatchEvent(pasteEvent);
}
beforeEach(() => {
React = require('react');
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
delete document.documentMode;
delete window.CompositionEvent;
delete window.TextEvent;
delete window.opera;
document.body.removeChild(container);
container = null;
});
function keyCode(char) {
return char.charCodeAt(0);
}
const scenarios = [
{
eventSimulator: simulateEvent,
eventSimulatorArgs: [
'compositionstart',
{detail: {data: 'test'}, data: 'test'},
],
},
{
eventSimulator: simulateEvent,
eventSimulatorArgs: [
'compositionupdate',
{detail: {data: 'test string'}, data: 'test string'},
],
},
{
eventSimulator: simulateEvent,
eventSimulatorArgs: [
'compositionend',
{detail: {data: 'test string 3'}, data: 'test string 3'},
],
},
{
eventSimulator: simulateEvent,
eventSimulatorArgs: ['textInput', {data: 'abcß'}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keypress', {which: keyCode('a')}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keypress', {which: keyCode(' ')}, ' '],
},
{
eventSimulator: simulateEvent,
eventSimulatorArgs: ['textInput', {data: ' '}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keypress', {which: keyCode('a'), ctrlKey: true}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keypress', {which: keyCode('b'), altKey: true}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: [
'keypress',
{which: keyCode('c'), altKey: true, ctrlKey: true},
],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: [
'keypress',
{which: keyCode('X'), char: '\uD83D\uDE0A'},
],
},
{
eventSimulator: simulateEvent,
eventSimulatorArgs: ['textInput', {data: '\uD83D\uDE0A'}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keydown', {keyCode: 229, value: 'foo'}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keydown', {keyCode: 9, value: 'foobar'}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keydown', {keyCode: 229, value: 'foofoo'}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keyup', {keyCode: 9, value: 'fooBARfoo'}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keydown', {keyCode: 229, value: 'foofoo'}],
},
{
eventSimulator: simulateKeyboardEvent,
eventSimulatorArgs: ['keypress', {keyCode: 60, value: 'Barfoofoo'}],
},
{
eventSimulator: simulatePaste,
eventSimulatorArgs: [],
},
];
const environments = [
{
emulator: simulateWebkit,
assertions: [
{
run: ({
beforeInputEvent,
compositionStartEvent,
spyOnBeforeInput,
spyOnCompositionStart,
}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
expect(spyOnCompositionStart).toHaveBeenCalledTimes(1);
expect(compositionStartEvent.type).toBe('compositionstart');
expect(compositionStartEvent.data).toBe('test');
},
},
{
run: ({
beforeInputEvent,
compositionUpdateEvent,
spyOnBeforeInput,
spyOnCompositionUpdate,
}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
expect(spyOnCompositionUpdate).toHaveBeenCalledTimes(1);
expect(compositionUpdateEvent.type).toBe('compositionupdate');
expect(compositionUpdateEvent.data).toBe('test string');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('compositionend');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('test string 3');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('textInput');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('abcß');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe(' ');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('textInput');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('\uD83D\uDE0A');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
],
},
{
emulator: simulateIE11,
assertions: [
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('a');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe(' ');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('c');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('\uD83D\uDE0A');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
],
},
{
emulator: simulateNoComposition,
assertions: [
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('a');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe(' ');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('c');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('\uD83D\uDE0A');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keydown');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('bar');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keyup');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('BAR');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('Bar');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
],
},
{
emulator: simulateComposition,
assertions: [
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('compositionend');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('test string 3');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('a');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe(' ');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('c');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(1);
expect(beforeInputEvent.nativeEvent.type).toBe('keypress');
expect(beforeInputEvent.type).toBe('beforeinput');
expect(beforeInputEvent.data).toBe('\uD83D\uDE0A');
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
{
run: ({beforeInputEvent, spyOnBeforeInput}) => {
expect(spyOnBeforeInput).toHaveBeenCalledTimes(0);
expect(beforeInputEvent).toBeNull();
},
},
],
},
];
const testInputComponent = (env, scenes) => {
let beforeInputEvent;
let compositionStartEvent;
let compositionUpdateEvent;
let spyOnBeforeInput;
let spyOnCompositionStart;
let spyOnCompositionUpdate;
ReactDOM = loadReactDOM(env.emulator);
const node = ReactDOM.render(
<input
type="text"
onBeforeInput={e => {
spyOnBeforeInput();
beforeInputEvent = e;
}}
onCompositionStart={e => {
spyOnCompositionStart();
compositionStartEvent = e;
}}
onCompositionUpdate={e => {
spyOnCompositionUpdate();
compositionUpdateEvent = e;
}}
/>,
container,
);
scenes.forEach((s, id) => {
beforeInputEvent = null;
compositionStartEvent = null;
compositionUpdateEvent = null;
spyOnBeforeInput = jest.fn();
spyOnCompositionStart = jest.fn();
spyOnCompositionUpdate = jest.fn();
s.eventSimulator.apply(null, [node, ...s.eventSimulatorArgs]);
env.assertions[id].run({
beforeInputEvent,
compositionStartEvent,
compositionUpdateEvent,
spyOnBeforeInput,
spyOnCompositionStart,
spyOnCompositionUpdate,
});
});
};
const testContentEditableComponent = (env, scenes) => {
let beforeInputEvent;
let compositionStartEvent;
let compositionUpdateEvent;
let spyOnBeforeInput;
let spyOnCompositionStart;
let spyOnCompositionUpdate;
ReactDOM = loadReactDOM(env.emulator);
const node = ReactDOM.render(
<div
contentEditable={true}
onBeforeInput={e => {
spyOnBeforeInput();
beforeInputEvent = e;
}}
onCompositionStart={e => {
spyOnCompositionStart();
compositionStartEvent = e;
}}
onCompositionUpdate={e => {
spyOnCompositionUpdate();
compositionUpdateEvent = e;
}}
/>,
container,
);
scenes.forEach((s, id) => {
beforeInputEvent = null;
compositionStartEvent = null;
compositionUpdateEvent = null;
spyOnBeforeInput = jest.fn();
spyOnCompositionStart = jest.fn();
spyOnCompositionUpdate = jest.fn();
s.eventSimulator.apply(null, [node, ...s.eventSimulatorArgs]);
env.assertions[id].run({
beforeInputEvent,
compositionStartEvent,
compositionUpdateEvent,
spyOnBeforeInput,
spyOnCompositionStart,
spyOnCompositionUpdate,
});
});
};
it('should extract onBeforeInput when simulating in Webkit on input[type=text]', () => {
testInputComponent(environments[0], scenarios);
});
it('should extract onBeforeInput when simulating in Webkit on contenteditable', () => {
testContentEditableComponent(environments[0], scenarios);
});
it('should extract onBeforeInput when simulating in IE11 on input[type=text]', () => {
testInputComponent(environments[1], scenarios);
});
it('should extract onBeforeInput when simulating in IE11 on contenteditable', () => {
testContentEditableComponent(environments[1], scenarios);
});
it('should extract onBeforeInput when simulating in env with no CompositionEvent on input[type=text]', () => {
testInputComponent(environments[2], scenarios);
});
// in an environment using composition fallback onBeforeInput will not work
// as expected on a contenteditable as keydown and keyup events are translated
// to keypress events
it('should extract onBeforeInput when simulating in env with only CompositionEvent on input[type=text]', () => {
testInputComponent(environments[3], scenarios);
});
it('should extract onBeforeInput when simulating in env with only CompositionEvent on contenteditable', () => {
testContentEditableComponent(environments[3], scenarios);
});
});
| 31.905771 | 114 | 0.573239 |
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
*/
import type Agent from 'react-devtools-shared/src/backend/agent';
import {isReactNativeEnvironment} from 'react-devtools-shared/src/backend/utils';
import Overlay from './Overlay';
const SHOW_DURATION = 2000;
let timeoutID: TimeoutID | null = null;
let overlay: Overlay | null = null;
function hideOverlayNative(agent: Agent): void {
agent.emit('hideNativeHighlight');
}
function hideOverlayWeb(): void {
timeoutID = null;
if (overlay !== null) {
overlay.remove();
overlay = null;
}
}
export function hideOverlay(agent: Agent): void {
return isReactNativeEnvironment()
? hideOverlayNative(agent)
: hideOverlayWeb();
}
function showOverlayNative(elements: Array<HTMLElement>, agent: Agent): void {
agent.emit('showNativeHighlight', elements);
}
function showOverlayWeb(
elements: Array<HTMLElement>,
componentName: string | null,
agent: Agent,
hideAfterTimeout: boolean,
): void {
if (timeoutID !== null) {
clearTimeout(timeoutID);
}
if (overlay === null) {
overlay = new Overlay(agent);
}
overlay.inspect(elements, componentName);
if (hideAfterTimeout) {
timeoutID = setTimeout(() => hideOverlay(agent), SHOW_DURATION);
}
}
export function showOverlay(
elements: Array<HTMLElement>,
componentName: string | null,
agent: Agent,
hideAfterTimeout: boolean,
): void {
return isReactNativeEnvironment()
? showOverlayNative(elements, agent)
: showOverlayWeb(elements, componentName, agent, hideAfterTimeout);
}
| 21.72 | 81 | 0.709924 |
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 {Rect} from '../geometry';
import type {Surface, ViewRefs} from '../Surface';
import type {
Interaction,
ClickInteraction,
MouseDownInteraction,
MouseMoveInteraction,
MouseUpInteraction,
} from '../useCanvasInteraction';
import {VerticalScrollOverflowView} from './VerticalScrollOverflowView';
import {rectContainsPoint, rectEqualToRect} from '../geometry';
import {View} from '../View';
import {BORDER_SIZE, COLORS} from '../../content-views/constants';
const SCROLL_BAR_SIZE = 14;
const HIDDEN_RECT = {
origin: {
x: 0,
y: 0,
},
size: {
width: 0,
height: 0,
},
};
export class VerticalScrollBarView extends View {
_contentHeight: number = 0;
_isScrolling: boolean = false;
_scrollBarRect: Rect = HIDDEN_RECT;
_scrollThumbRect: Rect = HIDDEN_RECT;
_verticalScrollOverflowView: VerticalScrollOverflowView;
constructor(
surface: Surface,
frame: Rect,
verticalScrollOverflowView: VerticalScrollOverflowView,
) {
super(surface, frame);
this._verticalScrollOverflowView = verticalScrollOverflowView;
}
desiredSize(): {+height: number, +width: number} {
return {
width: SCROLL_BAR_SIZE,
height: 0, // No desired height
};
}
getMaxScrollThumbY(): number {
const {height} = this.frame.size;
const maxScrollThumbY = height - this._scrollThumbRect.size.height;
return maxScrollThumbY;
}
setContentHeight(contentHeight: number) {
this._contentHeight = contentHeight;
const {height, width} = this.frame.size;
const proposedScrollThumbRect = {
origin: {
x: this.frame.origin.x,
y: this._scrollThumbRect.origin.y,
},
size: {
width,
height: height * (height / contentHeight),
},
};
if (!rectEqualToRect(this._scrollThumbRect, proposedScrollThumbRect)) {
this._scrollThumbRect = proposedScrollThumbRect;
this.setNeedsDisplay();
}
}
setScrollThumbY(value: number) {
const {height} = this.frame.size;
const maxScrollThumbY = this.getMaxScrollThumbY();
const newScrollThumbY = Math.max(0, Math.min(maxScrollThumbY, value));
this._scrollThumbRect = {
...this._scrollThumbRect,
origin: {
x: this.frame.origin.x,
y: newScrollThumbY,
},
};
const maxContentOffset = this._contentHeight - height;
const contentScrollOffset =
(newScrollThumbY / maxScrollThumbY) * maxContentOffset * -1;
this._verticalScrollOverflowView.setScrollOffset(
contentScrollOffset,
maxScrollThumbY,
);
}
draw(context: CanvasRenderingContext2D, viewRefs: ViewRefs) {
const {x, y} = this.frame.origin;
const {width, height} = this.frame.size;
// TODO Use real color
context.fillStyle = COLORS.REACT_RESIZE_BAR;
context.fillRect(x, y, width, height);
// TODO Use real color
context.fillStyle = COLORS.SCROLL_CARET;
context.fillRect(
this._scrollThumbRect.origin.x,
this._scrollThumbRect.origin.y,
this._scrollThumbRect.size.width,
this._scrollThumbRect.size.height,
);
// TODO Use real color
context.fillStyle = COLORS.REACT_RESIZE_BAR_BORDER;
context.fillRect(x, y, BORDER_SIZE, height);
}
handleInteraction(interaction: Interaction, viewRefs: ViewRefs) {
switch (interaction.type) {
case 'click':
this._handleClick(interaction, viewRefs);
break;
case 'mousedown':
this._handleMouseDown(interaction, viewRefs);
break;
case 'mousemove':
this._handleMouseMove(interaction, viewRefs);
break;
case 'mouseup':
this._handleMouseUp(interaction, viewRefs);
break;
}
}
_handleClick(interaction: ClickInteraction, viewRefs: ViewRefs) {
const {location} = interaction.payload;
if (rectContainsPoint(location, this.frame)) {
if (rectContainsPoint(location, this._scrollThumbRect)) {
// Ignore clicks on the track thumb directly.
return;
}
const currentScrollThumbY = this._scrollThumbRect.origin.y;
const y = location.y;
const {height} = this.frame.size;
// Scroll up or down about one viewport worth of content:
const deltaY = (height / this._contentHeight) * height * 0.8;
this.setScrollThumbY(
y > currentScrollThumbY
? this._scrollThumbRect.origin.y + deltaY
: this._scrollThumbRect.origin.y - deltaY,
);
}
}
_handleMouseDown(interaction: MouseDownInteraction, viewRefs: ViewRefs) {
const {location} = interaction.payload;
if (!rectContainsPoint(location, this._scrollThumbRect)) {
return;
}
viewRefs.activeView = this;
this.currentCursor = 'default';
this._isScrolling = true;
this.setNeedsDisplay();
}
_handleMouseMove(interaction: MouseMoveInteraction, viewRefs: ViewRefs) {
const {event, location} = interaction.payload;
if (rectContainsPoint(location, this.frame)) {
if (viewRefs.hoveredView !== this) {
viewRefs.hoveredView = this;
}
this.currentCursor = 'default';
}
if (viewRefs.activeView === this) {
this.currentCursor = 'default';
this.setScrollThumbY(this._scrollThumbRect.origin.y + event.movementY);
}
}
_handleMouseUp(interaction: MouseUpInteraction, viewRefs: ViewRefs) {
if (viewRefs.activeView === this) {
viewRefs.activeView = null;
}
if (this._isScrolling) {
this._isScrolling = false;
this.setNeedsDisplay();
}
}
}
| 25.168182 | 77 | 0.65827 |
owtf | import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import ControlledFormFixture from './ControlledFormFixture';
const React = window.React;
export default class FormStateCases extends React.Component {
render() {
return (
<FixtureSet title="Form State">
<TestCase
title="Form state autofills from browser"
description="Form start should autofill/autocomplete if user has autocomplete/autofill information saved. The user may need to set-up autofill or autocomplete with their specific browser.">
<TestCase.Steps>
<li>
Set up autofill/autocomplete for your browser.
<br />
Instructions:
<ul>
<li>
<SafeLink
href="https://support.google.com/chrome/answer/142893?co=GENIE.Platform%3DDesktop&hl=en"
text="Google Chrome"
/>
</li>
<li>
<SafeLink
href="https://support.mozilla.org/en-US/kb/autofill-logins-firefox"
text="Mozilla FireFox"
/>
</li>
<li>
<SafeLink
href="https://support.microsoft.com/en-us/help/4027718/microsoft-edge-automatically-fill-info"
text="Microsoft Edge"
/>
</li>
</ul>
</li>
<li>Click into any input.</li>
<li>Select any autofill option.</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
Autofill options should appear when clicking into fields. Selected
autofill options should change state (shown underneath, under
"States").
</TestCase.ExpectedResult>
<ControlledFormFixture />
</TestCase>
</FixtureSet>
);
}
}
const SafeLink = ({text, href}) => {
return (
<a target="_blank" rel="noreferrer" href={href}>
{text}
</a>
);
};
| 33.163934 | 199 | 0.530005 |
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.
*/
import * as Scheduler from 'scheduler';
import ReactCurrentDispatcher from '../ReactCurrentDispatcher';
import ReactCurrentCache from '../ReactCurrentCache';
import ReactCurrentActQueue from '../ReactCurrentActQueue';
import ReactCurrentOwner from '../ReactCurrentOwner';
import ReactDebugCurrentFrame from '../ReactDebugCurrentFrame';
import ReactCurrentBatchConfig from '../ReactCurrentBatchConfig';
import {enableServerContext} from 'shared/ReactFeatureFlags';
import {ContextRegistry} from '../ReactServerContextRegistry';
const ReactSharedInternalsClient = {
ReactCurrentDispatcher,
ReactCurrentCache,
ReactCurrentOwner,
ReactCurrentBatchConfig,
// Re-export the schedule API(s) for UMD bundles.
// This avoids introducing a dependency on a new UMD global in a minor update,
// Since that would be a breaking change (e.g. for all existing CodeSandboxes).
// This re-export is only required for UMD bundles;
// CJS bundles use the shared NPM package.
Scheduler,
};
if (__DEV__) {
ReactSharedInternalsClient.ReactCurrentActQueue = ReactCurrentActQueue;
ReactSharedInternalsClient.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
}
if (enableServerContext) {
ReactSharedInternalsClient.ContextRegistry = ContextRegistry;
}
export default ReactSharedInternalsClient;
| 34.52381 | 81 | 0.788062 |
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 StrictMode;
let ReactNative;
let createReactNativeComponentClass;
let UIManager;
let TextInputState;
let ReactNativePrivateInterface;
const DISPATCH_COMMAND_REQUIRES_HOST_COMPONENT =
"Warning: dispatchCommand was called with a ref that isn't a " +
'native component. Use React.forwardRef to get access to the underlying native component';
const SEND_ACCESSIBILITY_EVENT_REQUIRES_HOST_COMPONENT =
"Warning: sendAccessibilityEvent was called with a ref that isn't a " +
'native component. Use React.forwardRef to get access to the underlying native component';
describe('ReactNative', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
StrictMode = React.StrictMode;
ReactNative = require('react-native-renderer');
ReactNativePrivateInterface = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface');
UIManager =
require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface').UIManager;
createReactNativeComponentClass =
require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface')
.ReactNativeViewConfigRegistry.register;
TextInputState =
require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface').TextInputState;
});
it('should be able to create and render a native component', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
ReactNative.render(<View foo="test" />, 1);
expect(UIManager.createView).toBeCalled();
expect(UIManager.setChildren).toBeCalled();
expect(UIManager.manageChildren).not.toBeCalled();
expect(UIManager.updateView).not.toBeCalled();
});
it('should be able to create and update a native component', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
ReactNative.render(<View foo="foo" />, 11);
expect(UIManager.createView).toHaveBeenCalledTimes(1);
expect(UIManager.setChildren).toHaveBeenCalledTimes(1);
expect(UIManager.manageChildren).not.toBeCalled();
expect(UIManager.updateView).not.toBeCalled();
ReactNative.render(<View foo="bar" />, 11);
expect(UIManager.createView).toHaveBeenCalledTimes(1);
expect(UIManager.setChildren).toHaveBeenCalledTimes(1);
expect(UIManager.manageChildren).not.toBeCalled();
expect(UIManager.updateView).toBeCalledWith(3, 'RCTView', {foo: 'bar'});
});
it('should not call UIManager.updateView after render for properties that have not changed', () => {
const Text = createReactNativeComponentClass('RCTText', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTText',
}));
ReactNative.render(<Text foo="a">1</Text>, 11);
expect(UIManager.updateView).not.toBeCalled();
// If no properties have changed, we shouldn't call updateView.
ReactNative.render(<Text foo="a">1</Text>, 11);
expect(UIManager.updateView).not.toBeCalled();
// Only call updateView for the changed property (and not for text).
ReactNative.render(<Text foo="b">1</Text>, 11);
expect(UIManager.updateView).toHaveBeenCalledTimes(1);
// Only call updateView for the changed text (and no other properties).
ReactNative.render(<Text foo="b">2</Text>, 11);
expect(UIManager.updateView).toHaveBeenCalledTimes(2);
// Call updateView for both changed text and properties.
ReactNative.render(<Text foo="c">3</Text>, 11);
expect(UIManager.updateView).toHaveBeenCalledTimes(4);
});
it('should call dispatchCommand for native refs', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
UIManager.dispatchViewManagerCommand.mockClear();
let viewRef;
ReactNative.render(
<View
ref={ref => {
viewRef = ref;
}}
/>,
11,
);
expect(UIManager.dispatchViewManagerCommand).not.toBeCalled();
ReactNative.dispatchCommand(viewRef, 'updateCommand', [10, 20]);
expect(UIManager.dispatchViewManagerCommand).toHaveBeenCalledTimes(1);
expect(UIManager.dispatchViewManagerCommand).toHaveBeenCalledWith(
expect.any(Number),
'updateCommand',
[10, 20],
);
});
it('should warn and no-op if calling dispatchCommand on non native refs', () => {
class BasicClass extends React.Component {
render() {
return <React.Fragment />;
}
}
UIManager.dispatchViewManagerCommand.mockReset();
let viewRef;
ReactNative.render(
<BasicClass
ref={ref => {
viewRef = ref;
}}
/>,
11,
);
expect(UIManager.dispatchViewManagerCommand).not.toBeCalled();
expect(() => {
ReactNative.dispatchCommand(viewRef, 'updateCommand', [10, 20]);
}).toErrorDev([DISPATCH_COMMAND_REQUIRES_HOST_COMPONENT], {
withoutStack: true,
});
expect(UIManager.dispatchViewManagerCommand).not.toBeCalled();
});
it('should call sendAccessibilityEvent for native refs', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
ReactNativePrivateInterface.legacySendAccessibilityEvent.mockClear();
let viewRef;
ReactNative.render(
<View
ref={ref => {
viewRef = ref;
}}
/>,
11,
);
expect(
ReactNativePrivateInterface.legacySendAccessibilityEvent,
).not.toBeCalled();
ReactNative.sendAccessibilityEvent(viewRef, 'focus');
expect(
ReactNativePrivateInterface.legacySendAccessibilityEvent,
).toHaveBeenCalledTimes(1);
expect(
ReactNativePrivateInterface.legacySendAccessibilityEvent,
).toHaveBeenCalledWith(expect.any(Number), 'focus');
});
it('should warn and no-op if calling sendAccessibilityEvent on non native refs', () => {
class BasicClass extends React.Component {
render() {
return <React.Fragment />;
}
}
UIManager.sendAccessibilityEvent.mockReset();
let viewRef;
ReactNative.render(
<BasicClass
ref={ref => {
viewRef = ref;
}}
/>,
11,
);
expect(UIManager.sendAccessibilityEvent).not.toBeCalled();
expect(() => {
ReactNative.sendAccessibilityEvent(viewRef, 'updateCommand', [10, 20]);
}).toErrorDev([SEND_ACCESSIBILITY_EVENT_REQUIRES_HOST_COMPONENT], {
withoutStack: true,
});
expect(UIManager.sendAccessibilityEvent).not.toBeCalled();
});
it('should not call UIManager.updateView from ref.setNativeProps for properties that have not changed', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
UIManager.updateView.mockReset();
let viewRef;
ReactNative.render(
<View
foo="bar"
ref={ref => {
viewRef = ref;
}}
/>,
11,
);
expect(UIManager.updateView).not.toBeCalled();
viewRef.setNativeProps({});
expect(UIManager.updateView).not.toBeCalled();
viewRef.setNativeProps({foo: 'baz'});
expect(UIManager.updateView).toHaveBeenCalledTimes(1);
expect(UIManager.updateView).toHaveBeenCalledWith(
expect.any(Number),
'RCTView',
{foo: 'baz'},
);
});
it('should call UIManager.measure on ref.measure', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
UIManager.measure.mockClear();
let viewRef;
ReactNative.render(
<View
ref={ref => {
viewRef = ref;
}}
/>,
11,
);
expect(UIManager.measure).not.toBeCalled();
const successCallback = jest.fn();
viewRef.measure(successCallback);
expect(UIManager.measure).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledWith(10, 10, 100, 100, 0, 0);
});
it('should call UIManager.measureInWindow on ref.measureInWindow', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
UIManager.measureInWindow.mockClear();
let viewRef;
ReactNative.render(
<View
ref={ref => {
viewRef = ref;
}}
/>,
11,
);
expect(UIManager.measureInWindow).not.toBeCalled();
const successCallback = jest.fn();
viewRef.measureInWindow(successCallback);
expect(UIManager.measureInWindow).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledWith(10, 10, 100, 100);
});
it('should support reactTag in ref.measureLayout', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
UIManager.measureLayout.mockClear();
let viewRef;
let otherRef;
ReactNative.render(
<View>
<View
foo="bar"
ref={ref => {
viewRef = ref;
}}
/>
<View
ref={ref => {
otherRef = ref;
}}
/>
</View>,
11,
);
expect(UIManager.measureLayout).not.toBeCalled();
const successCallback = jest.fn();
const failureCallback = jest.fn();
viewRef.measureLayout(
ReactNative.findNodeHandle(otherRef),
successCallback,
failureCallback,
);
expect(UIManager.measureLayout).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledWith(1, 1, 100, 100);
});
it('should support ref in ref.measureLayout of host components', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
UIManager.measureLayout.mockClear();
let viewRef;
let otherRef;
ReactNative.render(
<View>
<View
foo="bar"
ref={ref => {
viewRef = ref;
}}
/>
<View
ref={ref => {
otherRef = ref;
}}
/>
</View>,
11,
);
expect(UIManager.measureLayout).not.toBeCalled();
const successCallback = jest.fn();
const failureCallback = jest.fn();
viewRef.measureLayout(otherRef, successCallback, failureCallback);
expect(UIManager.measureLayout).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledTimes(1);
expect(successCallback).toHaveBeenCalledWith(1, 1, 100, 100);
});
it('returns the correct instance and calls it in the callback', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
let a;
let b;
const c = ReactNative.render(
<View foo="foo" ref={v => (a = v)} />,
11,
function () {
b = this;
},
);
expect(a).toBeTruthy();
expect(a).toBe(b);
expect(a).toBe(c);
});
it('renders and reorders children', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {title: true},
uiViewClassName: 'RCTView',
}));
class Component extends React.Component {
render() {
const chars = this.props.chars.split('');
return (
<View>
{chars.map(text => (
<View key={text} title={text} />
))}
</View>
);
}
}
// Mini multi-child stress test: lots of reorders, some adds, some removes.
const before = 'abcdefghijklmnopqrst';
const after = 'mxhpgwfralkeoivcstzy';
ReactNative.render(<Component chars={before} />, 11);
expect(UIManager.__dumpHierarchyForJestTestsOnly()).toMatchSnapshot();
ReactNative.render(<Component chars={after} />, 11);
expect(UIManager.__dumpHierarchyForJestTestsOnly()).toMatchSnapshot();
});
it('calls setState with no arguments', () => {
let mockArgs;
class Component extends React.Component {
componentDidMount() {
this.setState({}, (...args) => (mockArgs = args));
}
render() {
return false;
}
}
ReactNative.render(<Component />, 11);
expect(mockArgs.length).toEqual(0);
});
it('should not throw when <View> is used inside of a <Text> ancestor', () => {
const Image = createReactNativeComponentClass('RCTImage', () => ({
validAttributes: {},
uiViewClassName: 'RCTImage',
}));
const Text = createReactNativeComponentClass('RCTText', () => ({
validAttributes: {},
uiViewClassName: 'RCTText',
}));
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {},
uiViewClassName: 'RCTView',
}));
ReactNative.render(
<Text>
<View />
</Text>,
11,
);
// Non-View things (e.g. Image) are fine
ReactNative.render(
<Text>
<Image />
</Text>,
11,
);
});
it('should throw for text not inside of a <Text> ancestor', () => {
const ScrollView = createReactNativeComponentClass('RCTScrollView', () => ({
validAttributes: {},
uiViewClassName: 'RCTScrollView',
}));
const Text = createReactNativeComponentClass('RCTText', () => ({
validAttributes: {},
uiViewClassName: 'RCTText',
}));
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {},
uiViewClassName: 'RCTView',
}));
expect(() => ReactNative.render(<View>this should warn</View>, 11)).toThrow(
'Text strings must be rendered within a <Text> component.',
);
expect(() =>
ReactNative.render(
<Text>
<ScrollView>hi hello hi</ScrollView>
</Text>,
11,
),
).toThrow('Text strings must be rendered within a <Text> component.');
});
it('should not throw for text inside of an indirect <Text> ancestor', () => {
const Text = createReactNativeComponentClass('RCTText', () => ({
validAttributes: {},
uiViewClassName: 'RCTText',
}));
const Indirection = () => 'Hi';
ReactNative.render(
<Text>
<Indirection />
</Text>,
11,
);
});
it('findHostInstance_DEPRECATED should warn if used to find a host component inside StrictMode', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
let parent = undefined;
let child = undefined;
class ContainsStrictModeChild extends React.Component {
render() {
return (
<StrictMode>
<View ref={n => (child = n)} />
</StrictMode>
);
}
}
ReactNative.render(<ContainsStrictModeChild ref={n => (parent = n)} />, 11);
let match;
expect(
() => (match = ReactNative.findHostInstance_DEPRECATED(parent)),
).toErrorDev([
'Warning: findHostInstance_DEPRECATED is deprecated in StrictMode. ' +
'findHostInstance_DEPRECATED was passed an instance of ContainsStrictModeChild which renders StrictMode children. ' +
'Instead, add a ref directly to the element you want to reference. ' +
'Learn more about using refs safely here: ' +
'https://reactjs.org/link/strict-mode-find-node' +
'\n in RCTView (at **)' +
'\n in ContainsStrictModeChild (at **)',
]);
expect(match).toBe(child);
});
it('findHostInstance_DEPRECATED should warn if passed a component that is inside StrictMode', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
let parent = undefined;
let child = undefined;
class IsInStrictMode extends React.Component {
render() {
return <View ref={n => (child = n)} />;
}
}
ReactNative.render(
<StrictMode>
<IsInStrictMode ref={n => (parent = n)} />
</StrictMode>,
11,
);
let match;
expect(
() => (match = ReactNative.findHostInstance_DEPRECATED(parent)),
).toErrorDev([
'Warning: findHostInstance_DEPRECATED is deprecated in StrictMode. ' +
'findHostInstance_DEPRECATED was passed an instance of IsInStrictMode which is inside StrictMode. ' +
'Instead, add a ref directly to the element you want to reference. ' +
'Learn more about using refs safely here: ' +
'https://reactjs.org/link/strict-mode-find-node' +
'\n in RCTView (at **)' +
'\n in IsInStrictMode (at **)',
]);
expect(match).toBe(child);
});
it('findNodeHandle should warn if used to find a host component inside StrictMode', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
let parent = undefined;
let child = undefined;
class ContainsStrictModeChild extends React.Component {
render() {
return (
<StrictMode>
<View ref={n => (child = n)} />
</StrictMode>
);
}
}
ReactNative.render(<ContainsStrictModeChild ref={n => (parent = n)} />, 11);
let match;
expect(() => (match = ReactNative.findNodeHandle(parent))).toErrorDev([
'Warning: findNodeHandle is deprecated in StrictMode. ' +
'findNodeHandle was passed an instance of ContainsStrictModeChild which renders StrictMode children. ' +
'Instead, add a ref directly to the element you want to reference. ' +
'Learn more about using refs safely here: ' +
'https://reactjs.org/link/strict-mode-find-node' +
'\n in RCTView (at **)' +
'\n in ContainsStrictModeChild (at **)',
]);
expect(match).toBe(child._nativeTag);
});
it('findNodeHandle should warn if passed a component that is inside StrictMode', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
let parent = undefined;
let child = undefined;
class IsInStrictMode extends React.Component {
render() {
return <View ref={n => (child = n)} />;
}
}
ReactNative.render(
<StrictMode>
<IsInStrictMode ref={n => (parent = n)} />
</StrictMode>,
11,
);
let match;
expect(() => (match = ReactNative.findNodeHandle(parent))).toErrorDev([
'Warning: findNodeHandle is deprecated in StrictMode. ' +
'findNodeHandle was passed an instance of IsInStrictMode which is inside StrictMode. ' +
'Instead, add a ref directly to the element you want to reference. ' +
'Learn more about using refs safely here: ' +
'https://reactjs.org/link/strict-mode-find-node' +
'\n in RCTView (at **)' +
'\n in IsInStrictMode (at **)',
]);
expect(match).toBe(child._nativeTag);
});
it('blur on host component calls TextInputState', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
const viewRef = React.createRef();
ReactNative.render(<View ref={viewRef} />, 11);
expect(TextInputState.blurTextInput).not.toBeCalled();
viewRef.current.blur();
expect(TextInputState.blurTextInput).toHaveBeenCalledTimes(1);
expect(TextInputState.blurTextInput).toHaveBeenCalledWith(viewRef.current);
});
it('focus on host component calls TextInputState', () => {
const View = createReactNativeComponentClass('RCTView', () => ({
validAttributes: {foo: true},
uiViewClassName: 'RCTView',
}));
const viewRef = React.createRef();
ReactNative.render(<View ref={viewRef} />, 11);
expect(TextInputState.focusTextInput).not.toBeCalled();
viewRef.current.focus();
expect(TextInputState.focusTextInput).toHaveBeenCalledTimes(1);
expect(TextInputState.focusTextInput).toHaveBeenCalledWith(viewRef.current);
});
});
| 28.76824 | 125 | 0.627001 |
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';
// Fix JSDOM. setAttribute is supposed to throw on things that can't be implicitly toStringed.
const setAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function (name, value) {
// eslint-disable-next-line react-internal/safe-string-coercion
return setAttribute.call(this, name, '' + value);
};
describe('ReactDOMSelect', () => {
let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
const noop = function () {};
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
});
it('should allow setting `defaultValue`', () => {
const stub = (
<select defaultValue="giraffe">
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.value).toBe('giraffe');
// Changing `defaultValue` should do nothing.
ReactDOM.render(
<select defaultValue="gorilla">{options}</select>,
container,
);
expect(node.value).toEqual('giraffe');
});
it('should not throw with `defaultValue` and without children', () => {
const stub = <select defaultValue="dummy" />;
expect(() => {
ReactTestUtils.renderIntoDocument(stub);
}).not.toThrow();
});
it('should not control when using `defaultValue`', () => {
const el = (
<select defaultValue="giraffe">
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const container = document.createElement('div');
const node = ReactDOM.render(el, container);
expect(node.value).toBe('giraffe');
node.value = 'monkey';
ReactDOM.render(el, container);
// Uncontrolled selects shouldn't change the value after first mounting
expect(node.value).toEqual('monkey');
});
it('should allow setting `defaultValue` with multiple', () => {
const stub = (
<select multiple={true} defaultValue={['giraffe', 'gorilla']}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
// Changing `defaultValue` should do nothing.
ReactDOM.render(
<select multiple={true} defaultValue={['monkey']}>
{options}
</select>,
container,
);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
});
it('should allow setting `value`', () => {
const stub = (
<select value="giraffe" onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.value).toBe('giraffe');
// Changing the `value` prop should change the selected option.
ReactDOM.render(
<select value="gorilla" onChange={noop}>
{options}
</select>,
container,
);
expect(node.value).toEqual('gorilla');
});
it('should default to the first non-disabled option', () => {
const stub = (
<select defaultValue="">
<option disabled={true}>Disabled</option>
<option disabled={true}>Still Disabled</option>
<option>0</option>
<option disabled={true}>Also Disabled</option>
</select>
);
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false);
expect(node.options[2].selected).toBe(true);
});
it('should allow setting `value` to __proto__', () => {
const stub = (
<select value="__proto__" onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="__proto__">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.value).toBe('__proto__');
// Changing the `value` prop should change the selected option.
ReactDOM.render(
<select value="gorilla" onChange={noop}>
{options}
</select>,
container,
);
expect(node.value).toEqual('gorilla');
});
it('should not throw with `value` and without children', () => {
const stub = <select value="dummy" onChange={noop} />;
expect(() => {
ReactTestUtils.renderIntoDocument(stub);
}).not.toThrow();
});
it('should allow setting `value` with multiple', () => {
const stub = (
<select multiple={true} value={['giraffe', 'gorilla']} onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
// Changing the `value` prop should change the selected options.
ReactDOM.render(
<select multiple={true} value={['monkey']} onChange={noop}>
{options}
</select>,
container,
);
expect(node.options[0].selected).toBe(true); // monkey
expect(node.options[1].selected).toBe(false); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
});
it('should allow setting `value` to __proto__ with multiple', () => {
const stub = (
<select multiple={true} value={['__proto__', 'gorilla']} onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="__proto__">A __proto__!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // __proto__
expect(node.options[2].selected).toBe(true); // gorilla
// Changing the `value` prop should change the selected options.
ReactDOM.render(
<select multiple={true} value={['monkey']} onChange={noop}>
{options}
</select>,
container,
);
expect(node.options[0].selected).toBe(true); // monkey
expect(node.options[1].selected).toBe(false); // __proto__
expect(node.options[2].selected).toBe(false); // gorilla
});
it('should not select other options automatically', () => {
const stub = (
<select multiple={true} value={['12']} onChange={noop}>
<option value="1">one</option>
<option value="2">two</option>
<option value="12">twelve</option>
</select>
);
const node = ReactTestUtils.renderIntoDocument(stub);
expect(node.options[0].selected).toBe(false); // one
expect(node.options[1].selected).toBe(false); // two
expect(node.options[2].selected).toBe(true); // twelve
});
it('should reset child options selected when they are changed and `value` is set', () => {
const stub = <select multiple={true} value={['a', 'b']} onChange={noop} />;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
ReactDOM.render(
<select multiple={true} value={['a', 'b']} onChange={noop}>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>,
container,
);
expect(node.options[0].selected).toBe(true); // a
expect(node.options[1].selected).toBe(true); // b
expect(node.options[2].selected).toBe(false); // c
});
it('should allow setting `value` with `objectToString`', () => {
const objectToString = {
animal: 'giraffe',
toString: function () {
return this.animal;
},
};
const el = (
<select multiple={true} value={[objectToString]} onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const container = document.createElement('div');
const node = ReactDOM.render(el, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
// Changing the `value` prop should change the selected options.
objectToString.animal = 'monkey';
const el2 = (
<select multiple={true} value={[objectToString]}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
ReactDOM.render(el2, container);
expect(node.options[0].selected).toBe(true); // monkey
expect(node.options[1].selected).toBe(false); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
});
it('should allow switching to multiple', () => {
const stub = (
<select defaultValue="giraffe">
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
// When making it multiple, giraffe and gorilla should be selected
ReactDOM.render(
<select multiple={true} defaultValue={['giraffe', 'gorilla']}>
{options}
</select>,
container,
);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
});
it('should allow switching from multiple', () => {
const stub = (
<select multiple={true} defaultValue={['giraffe', 'gorilla']}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
// When removing multiple, defaultValue is applied again, being omitted
// means that "monkey" will be selected
ReactDOM.render(
<select defaultValue="gorilla">{options}</select>,
container,
);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(false); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
});
it('does not select an item when size is initially set to greater than 1', () => {
const stub = (
<select size="2">
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const container = document.createElement('div');
const select = ReactDOM.render(stub, container);
expect(select.options[0].selected).toBe(false);
expect(select.options[1].selected).toBe(false);
expect(select.options[2].selected).toBe(false);
expect(select.value).toBe('');
expect(select.selectedIndex).toBe(-1);
});
it('should remember value when switching to uncontrolled', () => {
const stub = (
<select value={'giraffe'} onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
ReactDOM.render(<select>{options}</select>, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
});
it('should remember updated value when switching to uncontrolled', () => {
const stub = (
<select value={'giraffe'} onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const options = stub.props.children;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
ReactDOM.render(
<select value="gorilla" onChange={noop}>
{options}
</select>,
container,
);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(false); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
ReactDOM.render(<select>{options}</select>, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(false); // giraffe
expect(node.options[2].selected).toBe(true); // gorilla
});
it('should support server-side rendering', () => {
const stub = (
<select value="giraffe" onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const container = document.createElement('div');
container.innerHTML = ReactDOMServer.renderToString(stub);
const options = container.firstChild.options;
expect(options[0].value).toBe('monkey');
expect(options[0].selected).toBe(false);
expect(options[1].value).toBe('giraffe');
expect(options[1].selected).toBe(true);
expect(options[2].value).toBe('gorilla');
expect(options[2].selected).toBe(false);
});
it('should support server-side rendering with defaultValue', () => {
const stub = (
<select defaultValue="giraffe">
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const container = document.createElement('div');
container.innerHTML = ReactDOMServer.renderToString(stub);
const options = container.firstChild.options;
expect(options[0].value).toBe('monkey');
expect(options[0].selected).toBe(false);
expect(options[1].value).toBe('giraffe');
expect(options[1].selected).toBe(true);
expect(options[2].value).toBe('gorilla');
expect(options[2].selected).toBe(false);
});
it('should support server-side rendering with dangerouslySetInnerHTML', () => {
const stub = (
<select defaultValue="giraffe">
<option
value="monkey"
dangerouslySetInnerHTML={{
__html: 'A monkey!',
}}>
{undefined}
</option>
<option
value="giraffe"
dangerouslySetInnerHTML={{
__html: 'A giraffe!',
}}>
{null}
</option>
<option
value="gorilla"
dangerouslySetInnerHTML={{
__html: 'A gorilla!',
}}
/>
</select>
);
const container = document.createElement('div');
container.innerHTML = ReactDOMServer.renderToString(stub);
const options = container.firstChild.options;
expect(options[0].value).toBe('monkey');
expect(options[0].selected).toBe(false);
expect(options[1].value).toBe('giraffe');
expect(options[1].selected).toBe(true);
expect(options[2].value).toBe('gorilla');
expect(options[2].selected).toBe(false);
});
it('should support server-side rendering with multiple', () => {
const stub = (
<select multiple={true} value={['giraffe', 'gorilla']} onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const container = document.createElement('div');
container.innerHTML = ReactDOMServer.renderToString(stub);
const options = container.firstChild.options;
expect(options[0].value).toBe('monkey');
expect(options[0].selected).toBe(false);
expect(options[1].value).toBe('giraffe');
expect(options[1].selected).toBe(true);
expect(options[2].value).toBe('gorilla');
expect(options[2].selected).toBe(true);
});
it('should not control defaultValue if re-adding options', () => {
const container = document.createElement('div');
const node = ReactDOM.render(
<select multiple={true} defaultValue={['giraffe']}>
<option key="monkey" value="monkey">
A monkey!
</option>
<option key="giraffe" value="giraffe">
A giraffe!
</option>
<option key="gorilla" value="gorilla">
A gorilla!
</option>
</select>,
container,
);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
ReactDOM.render(
<select multiple={true} defaultValue={['giraffe']}>
<option key="monkey" value="monkey">
A monkey!
</option>
<option key="gorilla" value="gorilla">
A gorilla!
</option>
</select>,
container,
);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(false); // gorilla
ReactDOM.render(
<select multiple={true} defaultValue={['giraffe']}>
<option key="monkey" value="monkey">
A monkey!
</option>
<option key="giraffe" value="giraffe">
A giraffe!
</option>
<option key="gorilla" value="gorilla">
A gorilla!
</option>
</select>,
container,
);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(false); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
});
it('should support options with dynamic children', () => {
const container = document.createElement('div');
let node;
function App({value}) {
return (
<select value={value} ref={n => (node = n)} onChange={noop}>
<option key="monkey" value="monkey">
A monkey {value === 'monkey' ? 'is chosen' : null}!
</option>
<option key="giraffe" value="giraffe">
A giraffe {value === 'giraffe' && 'is chosen'}!
</option>
<option key="gorilla" value="gorilla">
A gorilla {value === 'gorilla' && 'is chosen'}!
</option>
</select>
);
}
ReactDOM.render(<App value="monkey" />, container);
expect(node.options[0].selected).toBe(true); // monkey
expect(node.options[1].selected).toBe(false); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
ReactDOM.render(<App value="giraffe" />, container);
expect(node.options[0].selected).toBe(false); // monkey
expect(node.options[1].selected).toBe(true); // giraffe
expect(node.options[2].selected).toBe(false); // gorilla
});
it('should warn if value is null', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<select value={null}>
<option value="test" />
</select>,
),
).toErrorDev(
'`value` prop on `select` should not be null. ' +
'Consider using an empty string to clear the component or `undefined` ' +
'for uncontrolled components.',
);
ReactTestUtils.renderIntoDocument(
<select value={null}>
<option value="test" />
</select>,
);
});
it('should warn if selected is set on <option>', () => {
function App() {
return (
<select>
<option selected={true} />
<option selected={true} />
</select>
);
}
expect(() => ReactTestUtils.renderIntoDocument(<App />)).toErrorDev(
'Use the `defaultValue` or `value` props on <select> instead of ' +
'setting `selected` on <option>.',
);
ReactTestUtils.renderIntoDocument(<App />);
});
it('should warn if value is null and multiple is true', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<select value={null} multiple={true}>
<option value="test" />
</select>,
),
).toErrorDev(
'`value` prop on `select` should not be null. ' +
'Consider using an empty array when `multiple` is ' +
'set to `true` to clear the component or `undefined` ' +
'for uncontrolled components.',
);
ReactTestUtils.renderIntoDocument(
<select value={null} multiple={true}>
<option value="test" />
</select>,
);
});
it('should refresh state on change', () => {
const stub = (
<select value="giraffe" onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const container = document.createElement('div');
document.body.appendChild(container);
try {
const node = ReactDOM.render(stub, container);
node.dispatchEvent(
new Event('change', {bubbles: true, cancelable: false}),
);
expect(node.value).toBe('giraffe');
} finally {
document.body.removeChild(container);
}
});
it('should warn if value and defaultValue props are specified', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<select value="giraffe" defaultValue="giraffe" readOnly={true}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
),
).toErrorDev(
'Select elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled select ' +
'element and remove one of these props. More info: ' +
'https://reactjs.org/link/controlled-components',
);
ReactTestUtils.renderIntoDocument(
<select value="giraffe" defaultValue="giraffe" readOnly={true}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
});
it('should not warn about missing onChange in uncontrolled textareas', () => {
const container = document.createElement('div');
ReactDOM.render(<select />, container);
ReactDOM.unmountComponentAtNode(container);
ReactDOM.render(<select value={undefined} />, container);
});
it('should be able to safely remove select onChange', () => {
function changeView() {
ReactDOM.unmountComponentAtNode(container);
}
const container = document.createElement('div');
const stub = (
<select value="giraffe" onChange={changeView}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>
);
const node = ReactDOM.render(stub, container);
expect(() => ReactTestUtils.Simulate.change(node)).not.toThrow();
});
it('should select grandchild options nested inside an optgroup', () => {
const stub = (
<select value="b" onChange={noop}>
<optgroup label="group">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</optgroup>
</select>
);
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // a
expect(node.options[1].selected).toBe(true); // b
expect(node.options[2].selected).toBe(false); // c
});
it('should allow controlling `value` in a nested render', () => {
let selectNode;
class Parent extends React.Component {
state = {
value: 'giraffe',
};
componentDidMount() {
this._renderNested();
}
componentDidUpdate() {
this._renderNested();
}
_handleChange(event) {
this.setState({value: event.target.value});
}
_renderNested() {
ReactDOM.render(
<select
onChange={this._handleChange.bind(this)}
ref={n => (selectNode = n)}
value={this.state.value}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
this._nestingContainer,
);
}
render() {
return <div ref={n => (this._nestingContainer = n)} />;
}
}
const container = document.createElement('div');
document.body.appendChild(container);
ReactDOM.render(<Parent />, container);
expect(selectNode.value).toBe('giraffe');
selectNode.value = 'gorilla';
let nativeEvent = document.createEvent('Event');
nativeEvent.initEvent('input', true, true);
selectNode.dispatchEvent(nativeEvent);
expect(selectNode.value).toEqual('gorilla');
nativeEvent = document.createEvent('Event');
nativeEvent.initEvent('change', true, true);
selectNode.dispatchEvent(nativeEvent);
expect(selectNode.value).toEqual('gorilla');
document.body.removeChild(container);
});
it('should not select first option by default when multiple is set and no defaultValue is set', () => {
const stub = (
<select multiple={true} onChange={noop}>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
);
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
expect(node.options[0].selected).toBe(false); // a
expect(node.options[1].selected).toBe(false); // b
expect(node.options[2].selected).toBe(false); // c
});
describe('When given a Symbol value', () => {
it('treats initial Symbol value as missing', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={Symbol('foobar')}>
<option value={Symbol('foobar')}>A Symbol!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('A Symbol!');
});
it('treats updated Symbol value as missing', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select onChange={noop} value="monkey">
<option value={Symbol('foobar')}>A Symbol!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('monkey');
node = ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={Symbol('foobar')}>
<option value={Symbol('foobar')}>A Symbol!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
expect(node.value).toBe('A Symbol!');
});
it('treats initial Symbol defaultValue as an empty string', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select defaultValue={Symbol('foobar')}>
<option value={Symbol('foobar')}>A Symbol!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('A Symbol!');
});
it('treats updated Symbol defaultValue as an empty string', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select defaultValue="monkey">
<option value={Symbol('foobar')}>A Symbol!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('monkey');
node = ReactTestUtils.renderIntoDocument(
<select defaultValue={Symbol('foobar')}>
<option value={Symbol('foobar')}>A Symbol!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
expect(node.value).toBe('A Symbol!');
});
});
describe('When given a function value', () => {
it('treats initial function value as missing', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={() => {}}>
<option value={() => {}}>A function!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('A function!');
});
it('treats initial function defaultValue as an empty string', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select defaultValue={() => {}}>
<option value={() => {}}>A function!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('A function!');
});
it('treats updated function value as an empty string', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select onChange={noop} value="monkey">
<option value={() => {}}>A function!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('monkey');
node = ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={() => {}}>
<option value={() => {}}>A function!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
expect(node.value).toBe('A function!');
});
it('treats updated function defaultValue as an empty string', () => {
let node;
expect(() => {
node = ReactTestUtils.renderIntoDocument(
<select defaultValue="monkey">
<option value={() => {}}>A function!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
}).toErrorDev('Invalid value for prop `value`');
expect(node.value).toBe('monkey');
node = ReactTestUtils.renderIntoDocument(
<select defaultValue={() => {}}>
<option value={() => {}}>A function!</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
expect(node.value).toBe('A function!');
});
});
describe('When given a Temporal.PlainDate-like value', () => {
class TemporalLike {
valueOf() {
// Throwing here is the behavior of ECMAScript "Temporal" date/time API.
// See https://tc39.es/proposal-temporal/docs/plaindate.html#valueOf
throw new TypeError('prod message');
}
toString() {
return '2020-01-01';
}
}
it('throws when given a Temporal.PlainDate-like value (select)', () => {
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={new TemporalLike()}>
<option value="2020-01-01">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'Form field values (value, checked, defaultValue, or defaultChecked props)' +
' must be strings, not TemporalLike. ' +
'This value must be coerced to a string before using it here.',
);
});
it('throws when given a Temporal.PlainDate-like value (option)', () => {
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value="2020-01-01">
<option value={new TemporalLike()}>
like a Temporal.PlainDate
</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'The provided `value` attribute is an unsupported type TemporalLike.' +
' This value must be coerced to a string before using it here.',
);
});
it('throws when given a Temporal.PlainDate-like value (both)', () => {
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={new TemporalLike()}>
<option value={new TemporalLike()}>
like a Temporal.PlainDate
</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'The provided `value` attribute is an unsupported type TemporalLike.' +
' This value must be coerced to a string before using it here.',
);
});
it('throws with updated Temporal.PlainDate-like value (select)', () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value="monkey">
<option value="2020-01-01">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={new TemporalLike()}>
<option value="2020-01-01">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'Form field values (value, checked, defaultValue, or defaultChecked props)' +
' must be strings, not TemporalLike. ' +
'This value must be coerced to a string before using it here.',
);
});
it('throws with updated Temporal.PlainDate-like value (option)', () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value="2020-01-01">
<option value="donkey">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value="2020-01-01">
<option value={new TemporalLike()}>
like a Temporal.PlainDate
</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'The provided `value` attribute is an unsupported type TemporalLike.' +
' This value must be coerced to a string before using it here.',
);
});
it('throws with updated Temporal.PlainDate-like value (both)', () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value="donkey">
<option value="donkey">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={new TemporalLike()}>
<option value={new TemporalLike()}>
like a Temporal.PlainDate
</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'The provided `value` attribute is an unsupported type TemporalLike.' +
' This value must be coerced to a string before using it here.',
);
});
it('throws when given a Temporal.PlainDate-like defaultValue (select)', () => {
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} defaultValue={new TemporalLike()}>
<option value="2020-01-01">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'Form field values (value, checked, defaultValue, or defaultChecked props)' +
' must be strings, not TemporalLike. ' +
'This value must be coerced to a string before using it here.',
);
});
it('throws when given a Temporal.PlainDate-like defaultValue (option)', () => {
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} defaultValue="2020-01-01">
<option value={new TemporalLike()}>
like a Temporal.PlainDate
</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'The provided `value` attribute is an unsupported type TemporalLike.' +
' This value must be coerced to a string before using it here.',
);
});
it('throws when given a Temporal.PlainDate-like value (both)', () => {
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} defaultValue={new TemporalLike()}>
<option value={new TemporalLike()}>
like a Temporal.PlainDate
</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'The provided `value` attribute is an unsupported type TemporalLike.' +
' This value must be coerced to a string before using it here.',
);
});
it('throws with updated Temporal.PlainDate-like defaultValue (select)', () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} defaultValue="monkey">
<option value="2020-01-01">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} defaultValue={new TemporalLike()}>
<option value="2020-01-01">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'Form field values (value, checked, defaultValue, or defaultChecked props)' +
' must be strings, not TemporalLike. ' +
'This value must be coerced to a string before using it here.',
);
});
it('throws with updated Temporal.PlainDate-like defaultValue (both)', () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} defaultValue="monkey">
<option value="donkey">like a Temporal.PlainDate</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
const test = () => {
ReactTestUtils.renderIntoDocument(
<select onChange={noop} value={new TemporalLike()}>
<option value={new TemporalLike()}>
like a Temporal.PlainDate
</option>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
</select>,
);
};
expect(() =>
expect(test).toThrowError(new TypeError('prod message')),
).toErrorDev(
'The provided `value` attribute is an unsupported type TemporalLike.' +
' This value must be coerced to a string before using it here.',
);
});
it('should not warn about missing onChange if value is not set', () => {
expect(() => {
ReactTestUtils.renderIntoDocument(
<select>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
}).not.toThrow();
});
it('should not throw an error about missing onChange if value is undefined', () => {
expect(() => {
ReactTestUtils.renderIntoDocument(
<select value={undefined}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
}).not.toThrow();
});
it('should not warn about missing onChange if onChange is set', () => {
const change = jest.fn();
expect(() => {
ReactTestUtils.renderIntoDocument(
<select value="monkey" onChange={change}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
}).not.toThrow();
});
it('should not warn about missing onChange if disabled is true', () => {
expect(() => {
ReactTestUtils.renderIntoDocument(
<select value="monkey" disabled={true}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
}).not.toThrow();
});
it('should warn about missing onChange if value is false', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<select value={false}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
),
).toErrorDev(
'Warning: You provided a `value` prop to a form ' +
'field without an `onChange` handler. This will render a read-only ' +
'field. If the field should be mutable use `defaultValue`. ' +
'Otherwise, set `onChange`.',
);
});
it('should warn about missing onChange if value is 0', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<select value={0}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
),
).toErrorDev(
'Warning: You provided a `value` prop to a form ' +
'field without an `onChange` handler. This will render a read-only ' +
'field. If the field should be mutable use `defaultValue`. ' +
'Otherwise, set `onChange`.',
);
});
it('should warn about missing onChange if value is "0"', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<select value="0">
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
),
).toErrorDev(
'Warning: You provided a `value` prop to a form ' +
'field without an `onChange` handler. This will render a read-only ' +
'field. If the field should be mutable use `defaultValue`. ' +
'Otherwise, set `onChange`.',
);
});
it('should warn about missing onChange if value is ""', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<select value="">
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
),
).toErrorDev(
'Warning: You provided a `value` prop to a form ' +
'field without an `onChange` handler. This will render a read-only ' +
'field. If the field should be mutable use `defaultValue`. ' +
'Otherwise, set `onChange`.',
);
});
});
});
| 33.223246 | 105 | 0.591079 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = require("react");
/**
* 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.
*
*
*/
const A = /*#__PURE__*/(0, _react.createContext)(1);
const B = /*#__PURE__*/(0, _react.createContext)(2);
function Component() {
const a = (0, _react.useContext)(A);
const b = (0, _react.useContext)(B); // prettier-ignore
const c = (0, _react.useContext)(A),
d = (0, _react.useContext)(B); // eslint-disable-line one-var
return a + b + c + d;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZS5qcyJdLCJuYW1lcyI6WyJBIiwiQiIsIkNvbXBvbmVudCIsImEiLCJiIiwiYyIsImQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7QUFUQTs7Ozs7Ozs7QUFXQSxNQUFBQSxDQUFBLGdCQUFBLDBCQUFBLENBQUEsQ0FBQTtBQUNBLE1BQUFDLENBQUEsZ0JBQUEsMEJBQUEsQ0FBQSxDQUFBOztBQUVBLFNBQUFDLFNBQUEsR0FBQTtBQUNBLFFBQUFDLENBQUEsR0FBQSx1QkFBQUgsQ0FBQSxDQUFBO0FBQ0EsUUFBQUksQ0FBQSxHQUFBLHVCQUFBSCxDQUFBLENBQUEsQ0FGQSxDQUlBOztBQUNBLFFBQUFJLENBQUEsR0FBQSx1QkFBQUwsQ0FBQSxDQUFBO0FBQUEsUUFBQU0sQ0FBQSxHQUFBLHVCQUFBTCxDQUFBLENBQUEsQ0FMQSxDQUtBOztBQUVBLFNBQUFFLENBQUEsR0FBQUMsQ0FBQSxHQUFBQyxDQUFBLEdBQUFDLENBQUE7QUFDQSIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQge2NyZWF0ZUNvbnRleHQsIHVzZUNvbnRleHR9IGZyb20gJ3JlYWN0JztcblxuY29uc3QgQSA9IGNyZWF0ZUNvbnRleHQoMSk7XG5jb25zdCBCID0gY3JlYXRlQ29udGV4dCgyKTtcblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgYSA9IHVzZUNvbnRleHQoQSk7XG4gIGNvbnN0IGIgPSB1c2VDb250ZXh0KEIpO1xuXG4gIC8vIHByZXR0aWVyLWlnbm9yZVxuICBjb25zdCBjID0gdXNlQ29udGV4dChBKSwgZCA9IHVzZUNvbnRleHQoQik7IC8vIGVzbGludC1kaXNhYmxlLWxpbmUgb25lLXZhclxuXG4gIHJldHVybiBhICsgYiArIGMgKyBkO1xufVxuIl19 | 70.833333 | 1,448 | 0.873259 |
owtf | import PropTypes from 'prop-types';
import semver from 'semver';
export function semverString(props, propName, componentName) {
let version = props[propName];
let error = PropTypes.string(...arguments);
if (!error && version != null && !semver.valid(version))
error = new Error(
`\`${propName}\` should be a valid "semantic version" matching ` +
'an existing React version'
);
return error || null;
}
| 26.1875 | 72 | 0.663594 |
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 './src/ReactNoopFlightClient';
| 21.727273 | 66 | 0.698795 |
PenetrationTestingScripts | /* global chrome */
export function setBrowserSelectionFromReact() {
// This is currently only called on demand when you press "view DOM".
// In the future, if Chrome adds an inspect() that doesn't switch tabs,
// we could make this happen automatically when you select another component.
chrome.devtools.inspectedWindow.eval(
'(window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 !== $0) ?' +
'(inspect(window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0), true) :' +
'false',
(didSelectionChange, evalError) => {
if (evalError) {
console.error(evalError);
}
},
);
}
export function setReactSelectionFromBrowser(bridge) {
// When the user chooses a different node in the browser Elements tab,
// copy it over to the hook object so that we can sync the selection.
chrome.devtools.inspectedWindow.eval(
'(window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 !== $0) ?' +
'(window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 = $0, true) :' +
'false',
(didSelectionChange, evalError) => {
if (evalError) {
console.error(evalError);
} else if (didSelectionChange) {
if (!bridge) {
console.error(
'Browser element selection changed, but bridge was not initialized',
);
return;
}
// Remember to sync the selection next time we show Components tab.
bridge.send('syncSelectionFromNativeElementsPanel');
}
},
);
}
| 33.697674 | 100 | 0.631791 |
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.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactTestRenderer;
let Scheduler;
let waitForAll;
let waitFor;
describe('ReactTestRendererAsync', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactTestRenderer = require('react-test-renderer');
Scheduler = require('scheduler');
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
waitFor = InternalTestUtils.waitFor;
});
it('flushAll flushes all work', async () => {
function Foo(props) {
return props.children;
}
const renderer = ReactTestRenderer.create(<Foo>Hi</Foo>, {
isConcurrent: true,
});
// Before flushing, nothing has mounted.
expect(renderer.toJSON()).toEqual(null);
// Flush initial mount.
await waitForAll([]);
expect(renderer.toJSON()).toEqual('Hi');
// Update
renderer.update(<Foo>Bye</Foo>);
// Not yet updated.
expect(renderer.toJSON()).toEqual('Hi');
// Flush update.
await waitForAll([]);
expect(renderer.toJSON()).toEqual('Bye');
});
it('flushAll returns array of yielded values', async () => {
function Child(props) {
Scheduler.log(props.children);
return props.children;
}
function Parent(props) {
return (
<>
<Child>{'A:' + props.step}</Child>
<Child>{'B:' + props.step}</Child>
<Child>{'C:' + props.step}</Child>
</>
);
}
const renderer = ReactTestRenderer.create(<Parent step={1} />, {
isConcurrent: true,
});
await waitForAll(['A:1', 'B:1', 'C:1']);
expect(renderer.toJSON()).toEqual(['A:1', 'B:1', 'C:1']);
renderer.update(<Parent step={2} />);
await waitForAll(['A:2', 'B:2', 'C:2']);
expect(renderer.toJSON()).toEqual(['A:2', 'B:2', 'C:2']);
});
it('flushThrough flushes until the expected values is yielded', async () => {
function Child(props) {
Scheduler.log(props.children);
return props.children;
}
function Parent(props) {
return (
<>
<Child>{'A:' + props.step}</Child>
<Child>{'B:' + props.step}</Child>
<Child>{'C:' + props.step}</Child>
</>
);
}
let renderer;
React.startTransition(() => {
renderer = ReactTestRenderer.create(<Parent step={1} />, {
isConcurrent: true,
});
});
// Flush the first two siblings
await waitFor(['A:1', 'B:1']);
// Did not commit yet.
expect(renderer.toJSON()).toEqual(null);
// Flush the remaining work
await waitForAll(['C:1']);
expect(renderer.toJSON()).toEqual(['A:1', 'B:1', 'C:1']);
});
it('supports high priority interruptions', async () => {
function Child(props) {
Scheduler.log(props.children);
return props.children;
}
class Example extends React.Component {
componentDidMount() {
expect(this.props.step).toEqual(2);
}
componentDidUpdate() {
throw Error('Unexpected update');
}
render() {
return (
<>
<Child>{'A:' + this.props.step}</Child>
<Child>{'B:' + this.props.step}</Child>
</>
);
}
}
let renderer;
React.startTransition(() => {
renderer = ReactTestRenderer.create(<Example step={1} />, {
isConcurrent: true,
});
});
// Flush the some of the changes, but don't commit
await waitFor(['A:1']);
expect(renderer.toJSON()).toEqual(null);
// Interrupt with higher priority properties
renderer.unstable_flushSync(() => {
renderer.update(<Example step={2} />);
});
// Only the higher priority properties have been committed
expect(renderer.toJSON()).toEqual(['A:2', 'B:2']);
});
});
| 24.687898 | 79 | 0.576885 |
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
*/
// Renderers that don't support persistence
// can re-export everything from this module.
function shim(...args: any): empty {
throw new Error(
'The current renderer does not support persistence. ' +
'This error is likely caused by a bug in React. ' +
'Please file an issue.',
);
}
// Persistence (when unsupported)
export const supportsPersistence = false;
export const cloneInstance = shim;
export const createContainerChildSet = shim;
export const appendChildToContainerChildSet = shim;
export const finalizeContainerChildren = shim;
export const replaceContainerChildren = shim;
export const cloneHiddenInstance = shim;
export const cloneHiddenTextInstance = shim;
| 28.866667 | 66 | 0.744134 |
owtf | import React from 'react';
import useTime from './useTime';
export default function Clock() {
const time = useTime();
return <p>Time: {time}</p>;
}
| 16.222222 | 33 | 0.662338 |
Python-Penetration-Testing-Cookbook | /**
* 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 LRU from 'lru-cache';
import {
convertInspectedElementBackendToFrontend,
hydrateHelper,
inspectElement as inspectElementAPI,
} from 'react-devtools-shared/src/backendAPI';
import {fillInPath} from 'react-devtools-shared/src/hydration';
import type {LRUCache} from 'react-devtools-shared/src/frontend/types';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type {
InspectElementError,
InspectElementFullData,
InspectElementHydratedPath,
} from 'react-devtools-shared/src/backend/types';
import UserError from 'react-devtools-shared/src/errors/UserError';
import UnknownHookError from 'react-devtools-shared/src/errors/UnknownHookError';
import type {
Element,
InspectedElement as InspectedElementFrontend,
InspectedElementResponseType,
InspectedElementPath,
} from 'react-devtools-shared/src/frontend/types';
// Maps element ID to inspected data.
// We use an LRU for this rather than a WeakMap because of how the "no-change" optimization works.
// When the frontend polls the backend for an update on the element that's currently inspected,
// the backend will send a "no-change" message if the element hasn't updated (rendered) since the last time it was asked.
// In this case, the frontend cache should reuse the previous (cached) value.
// Using a WeakMap keyed on Element generally works well for this, since Elements are mutable and stable in the Store.
// This doens't work properly though when component filters are changed,
// because this will cause the Store to dump all roots and re-initialize the tree (recreating the Element objects).
// So instead we key on Element ID (which is stable in this case) and use an LRU for eviction.
const inspectedElementCache: LRUCache<number, InspectedElementFrontend> =
new LRU({
max: 25,
});
type InspectElementReturnType = [
InspectedElementFrontend,
InspectedElementResponseType,
];
export function inspectElement(
bridge: FrontendBridge,
element: Element,
path: InspectedElementPath | null,
rendererID: number,
shouldListenToPauseEvents: boolean = false,
): Promise<InspectElementReturnType> {
const {id} = element;
// This could indicate that the DevTools UI has been closed and reopened.
// The in-memory cache will be clear but the backend still thinks we have cached data.
// In this case, we need to tell it to resend the full data.
const forceFullData = !inspectedElementCache.has(id);
return inspectElementAPI(
bridge,
forceFullData,
id,
path,
rendererID,
shouldListenToPauseEvents,
).then((data: any) => {
const {type} = data;
let inspectedElement;
switch (type) {
case 'error': {
const {message, stack, errorType} = ((data: any): InspectElementError);
// create a different error class for each error type
// and keep useful information from backend.
let error;
if (errorType === 'user') {
error = new UserError(message);
} else if (errorType === 'unknown-hook') {
error = new UnknownHookError(message);
} else {
error = new Error(message);
}
// The backend's stack (where the error originated) is more meaningful than this stack.
error.stack = stack || error.stack;
throw error;
}
case 'no-change':
// This is a no-op for the purposes of our cache.
inspectedElement = inspectedElementCache.get(id);
if (inspectedElement != null) {
return [inspectedElement, type];
}
// We should only encounter this case in the event of a bug.
throw Error(`Cached data for element "${id}" not found`);
case 'not-found':
// This is effectively a no-op.
// If the Element is still in the Store, we can eagerly remove it from the Map.
inspectedElementCache.del(id);
throw Error(`Element "${id}" not found`);
case 'full-data':
const fullData = ((data: any): InspectElementFullData);
// New data has come in.
// We should replace the data in our local mutable copy.
inspectedElement = convertInspectedElementBackendToFrontend(
fullData.value,
);
inspectedElementCache.set(id, inspectedElement);
return [inspectedElement, type];
case 'hydrated-path':
const hydratedPathData = ((data: any): InspectElementHydratedPath);
const {value} = hydratedPathData;
// A path has been hydrated.
// Merge it with the latest copy we have locally and resolve with the merged value.
inspectedElement = inspectedElementCache.get(id) || null;
if (inspectedElement !== null) {
// Clone element
inspectedElement = {...inspectedElement};
// Merge hydrated data
if (path != null) {
fillInPath(
inspectedElement,
value,
path,
hydrateHelper(value, path),
);
}
inspectedElementCache.set(id, inspectedElement);
return [inspectedElement, type];
}
break;
default:
// Should never happen.
if (__DEV__) {
console.error(
`Unexpected inspected element response data: "${type}"`,
);
}
break;
}
throw Error(`Unable to inspect element with id "${id}"`);
});
}
export function clearCacheForTests(): void {
inspectedElementCache.reset();
}
| 32.168605 | 121 | 0.666374 |
owtf | 'use strict';
// This is a server to host data-local resources like databases and RSC
const path = require('path');
const register = require('react-server-dom-webpack/node-register');
register();
const babelRegister = require('@babel/register');
babelRegister({
babelrc: false,
ignore: [
/\/(build|node_modules)\//,
function (file) {
if ((path.dirname(file) + '/').startsWith(__dirname + '/')) {
// Ignore everything in this folder
// because it's a mix of CJS and ESM
// and working with raw code is easier.
return true;
}
return false;
},
],
presets: ['@babel/preset-react'],
plugins: ['@babel/transform-modules-commonjs'],
});
if (typeof fetch === 'undefined') {
// Patch fetch for earlier Node versions.
global.fetch = require('undici').fetch;
}
const express = require('express');
const bodyParser = require('body-parser');
const busboy = require('busboy');
const app = express();
const compress = require('compression');
const {Readable} = require('node:stream');
app.use(compress());
// Application
const {readFile} = require('fs').promises;
const React = require('react');
async function renderApp(res, returnValue, formState) {
const {renderToPipeableStream} = await import(
'react-server-dom-webpack/server'
);
// const m = require('../src/App.js');
const m = await import('../src/App.js');
let moduleMap;
let mainCSSChunks;
if (process.env.NODE_ENV === 'development') {
// Read the module map from the HMR server in development.
moduleMap = await (
await fetch('http://localhost:3000/react-client-manifest.json')
).json();
mainCSSChunks = (
await (
await fetch('http://localhost:3000/entrypoint-manifest.json')
).json()
).main.css;
} else {
// Read the module map from the static build in production.
moduleMap = JSON.parse(
await readFile(
path.resolve(__dirname, `../build/react-client-manifest.json`),
'utf8'
)
);
mainCSSChunks = JSON.parse(
await readFile(
path.resolve(__dirname, `../build/entrypoint-manifest.json`),
'utf8'
)
).main.css;
}
const App = m.default.default || m.default;
const root = [
// Prepend the App's tree with stylesheets required for this entrypoint.
mainCSSChunks.map(filename =>
React.createElement('link', {
rel: 'stylesheet',
href: filename,
precedence: 'default',
})
),
React.createElement(App),
];
// For client-invoked server actions we refresh the tree and return a return value.
const payload = {root, returnValue, formState};
const {pipe} = renderToPipeableStream(payload, moduleMap);
pipe(res);
}
app.get('/', async function (req, res) {
await renderApp(res, null, null);
});
app.post('/', bodyParser.text(), async function (req, res) {
const {
renderToPipeableStream,
decodeReply,
decodeReplyFromBusboy,
decodeAction,
decodeFormState,
} = await import('react-server-dom-webpack/server');
const serverReference = req.get('rsc-action');
if (serverReference) {
// This is the client-side case
const [filepath, name] = serverReference.split('#');
const action = (await import(filepath))[name];
// Validate that this is actually a function we intended to expose and
// not the client trying to invoke arbitrary functions. In a real app,
// you'd have a manifest verifying this before even importing it.
if (action.$$typeof !== Symbol.for('react.server.reference')) {
throw new Error('Invalid action');
}
let args;
if (req.is('multipart/form-data')) {
// Use busboy to streamingly parse the reply from form-data.
const bb = busboy({headers: req.headers});
const reply = decodeReplyFromBusboy(bb);
req.pipe(bb);
args = await reply;
} else {
args = await decodeReply(req.body);
}
const result = action.apply(null, args);
try {
// Wait for any mutations
await result;
} catch (x) {
// We handle the error on the client
}
// Refresh the client and return the value
renderApp(res, result, null);
} else {
// This is the progressive enhancement case
const UndiciRequest = require('undici').Request;
const fakeRequest = new UndiciRequest('http://localhost', {
method: 'POST',
headers: {'Content-Type': req.headers['content-type']},
body: Readable.toWeb(req),
duplex: 'half',
});
const formData = await fakeRequest.formData();
const action = await decodeAction(formData);
try {
// Wait for any mutations
const result = await action();
const formState = decodeFormState(result, formData);
renderApp(res, null, formState);
} catch (x) {
const {setServerState} = await import('../src/ServerState.js');
setServerState('Error: ' + x.message);
renderApp(res, null, null);
}
}
});
app.get('/todos', function (req, res) {
res.json([
{
id: 1,
text: 'Shave yaks',
},
{
id: 2,
text: 'Eat kale',
},
]);
});
app.listen(3001, () => {
console.log('Regional Flight Server listening on port 3001...');
});
app.on('error', function (error) {
if (error.syscall !== 'listen') {
throw error;
}
switch (error.code) {
case 'EACCES':
console.error('port 3001 requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error('Port 3001 is already in use');
process.exit(1);
break;
default:
throw error;
}
});
| 26.73399 | 85 | 0.624445 |
owtf | var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './input',
output: {
filename: 'output.js',
},
resolve: {
root: path.resolve('../../../../build/oss-experimental/'),
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
],
};
| 17.4 | 62 | 0.53951 |
owtf | import React, {useContext, useState, Suspense} from 'react';
import Chrome from './Chrome';
import Page from './Page';
import Page2 from './Page2';
import Theme from './Theme';
function LoadingIndicator() {
let theme = useContext(Theme);
return <div className={theme + '-loading'}>Loading...</div>;
}
function Content() {
let [CurrentPage, switchPage] = useState(() => Page);
return (
<div>
<h1>Hello World</h1>
<a className="link" onClick={() => switchPage(() => Page)}>
Page 1
</a>
{' | '}
<a className="link" onClick={() => switchPage(() => Page2)}>
Page 2
</a>
<Suspense fallback={<LoadingIndicator />}>
<CurrentPage />
</Suspense>
</div>
);
}
export default function App({assets}) {
return (
<Chrome title="Hello World" assets={assets}>
<Content />
</Chrome>
);
}
| 21.615385 | 66 | 0.574347 |
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 typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.native-oss';
export const debugRenderPhaseSideEffectsForStrictMode = false;
export const enableDebugTracing = false;
export const enableAsyncDebugInfo = false;
export const enableSchedulingProfiler = false;
export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
export const enableProfilerTimer = __PROFILE__;
export const enableProfilerCommitHooks = __PROFILE__;
export const enableProfilerNestedUpdatePhase = __PROFILE__;
export const enableProfilerNestedUpdateScheduledHook = false;
export const enableUpdaterTracking = __PROFILE__;
export const enableCache = false;
export const enableLegacyCache = false;
export const enableCacheElement = false;
export const enableFetchInstrumentation = false;
export const enableFormActions = true; // Doesn't affect Native
export const enableBinaryFlight = true;
export const enableTaint = true;
export const enablePostpone = false;
export const disableJavaScriptURLs = false;
export const disableCommentsAsDOMContainers = true;
export const disableInputAttributeSyncing = false;
export const disableIEWorkarounds = true;
export const enableSchedulerDebugging = false;
export const enableScopeAPI = false;
export const enableCreateEventHandleAPI = false;
export const enableSuspenseCallback = false;
export const disableLegacyContext = false;
export const enableTrustedTypesIntegration = false;
export const disableTextareaChildren = false;
export const disableModulePatternComponents = false;
export const enableSuspenseAvoidThisFallback = false;
export const enableSuspenseAvoidThisFallbackFizz = false;
export const enableCPUSuspense = false;
export const enableUseMemoCacheHook = false;
export const enableUseEffectEventHook = false;
export const enableClientRenderFallbackOnTextMismatch = true;
export const enableComponentStackLocations = false;
export const enableLegacyFBSupport = false;
export const enableFilterEmptyStringAttributesDOM = false;
export const enableGetInspectorDataForInstanceInProduction = false;
export const enableRetryLaneExpiration = false;
export const retryLaneExpirationMs = 5000;
export const syncLaneExpirationMs = 250;
export const transitionLaneExpirationMs = 5000;
export const createRootStrictEffectsByDefault = false;
export const enableUseRefAccessWarning = false;
export const disableSchedulerTimeoutInWorkLoop = false;
export const enableLazyContextPropagation = false;
export const enableLegacyHidden = false;
export const forceConcurrentByDefaultForTesting = false;
export const enableUnifiedSyncLane = true;
export const allowConcurrentByDefault = false;
export const enableCustomElementPropertySupport = false;
export const consoleManagedByDevToolsDuringStrictMode = false;
export const enableServerContext = false;
export const enableTransitionTracing = false;
export const enableFloat = true;
export const useModernStrictMode = false;
export const enableDO_NOT_USE_disableStrictPassiveEffect = false;
export const enableFizzExternalRuntime = false;
export const enableDeferRootSchedulingToMicrotask = true;
export const enableAsyncActions = false;
export const alwaysThrottleRetries = true;
export const useMicrotasksForSchedulingInFabric = false;
export const passChildrenWhenCloningPersistedNodes = false;
export const enableUseDeferredValueInitialArg = __EXPERIMENTAL__;
// Flow magic to verify the exports of this file match the original version.
((((null: any): ExportsType): FeatureFlagsType): ExportsType);
| 39.913043 | 76 | 0.831517 |
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 typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.test-renderer';
export const debugRenderPhaseSideEffectsForStrictMode = false;
export const enableDebugTracing = false;
export const enableAsyncDebugInfo = false;
export const enableSchedulingProfiler = false;
export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
export const enableProfilerTimer = __PROFILE__;
export const enableProfilerCommitHooks = __PROFILE__;
export const enableProfilerNestedUpdatePhase = __PROFILE__;
export const enableProfilerNestedUpdateScheduledHook = false;
export const enableUpdaterTracking = false;
export const enableCache = true;
export const enableLegacyCache = false;
export const enableCacheElement = true;
export const enableFetchInstrumentation = false;
export const enableFormActions = true; // Doesn't affect Test Renderer
export const enableBinaryFlight = true;
export const enableTaint = true;
export const enablePostpone = false;
export const disableJavaScriptURLs = false;
export const disableCommentsAsDOMContainers = true;
export const disableInputAttributeSyncing = false;
export const disableIEWorkarounds = true;
export const enableSchedulerDebugging = false;
export const enableScopeAPI = false;
export const enableCreateEventHandleAPI = false;
export const enableSuspenseCallback = false;
export const disableLegacyContext = false;
export const enableTrustedTypesIntegration = false;
export const disableTextareaChildren = false;
export const disableModulePatternComponents = false;
export const enableComponentStackLocations = false;
export const enableLegacyFBSupport = false;
export const enableFilterEmptyStringAttributesDOM = false;
export const enableGetInspectorDataForInstanceInProduction = false;
export const enableSuspenseAvoidThisFallback = false;
export const enableSuspenseAvoidThisFallbackFizz = false;
export const enableCPUSuspense = false;
export const enableUseMemoCacheHook = true;
export const enableUseEffectEventHook = false;
export const enableClientRenderFallbackOnTextMismatch = true;
export const createRootStrictEffectsByDefault = false;
export const enableUseRefAccessWarning = false;
export const enableRetryLaneExpiration = false;
export const retryLaneExpirationMs = 5000;
export const syncLaneExpirationMs = 250;
export const transitionLaneExpirationMs = 5000;
export const disableSchedulerTimeoutInWorkLoop = false;
export const enableLazyContextPropagation = false;
export const enableLegacyHidden = false;
export const forceConcurrentByDefaultForTesting = false;
export const enableUnifiedSyncLane = true;
export const allowConcurrentByDefault = true;
export const consoleManagedByDevToolsDuringStrictMode = false;
export const enableServerContext = false;
export const enableTransitionTracing = false;
export const enableFloat = true;
export const useModernStrictMode = false;
export const enableDO_NOT_USE_disableStrictPassiveEffect = false;
export const enableDeferRootSchedulingToMicrotask = true;
export const enableAsyncActions = true;
export const alwaysThrottleRetries = true;
export const useMicrotasksForSchedulingInFabric = false;
export const passChildrenWhenCloningPersistedNodes = false;
export const enableUseDeferredValueInitialArg = __EXPERIMENTAL__;
// Flow magic to verify the exports of this file match the original version.
((((null: any): ExportsType): FeatureFlagsType): ExportsType);
| 40.067416 | 76 | 0.832512 |
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 {Thenable} from 'shared/ReactTypes.js';
import type {Response as FlightResponse} from 'react-client/src/ReactFlightClient';
import type {ReactServerValue} from 'react-client/src/ReactFlightReplyClient';
import {
createResponse,
getRoot,
reportGlobalError,
processBinaryChunk,
close,
} from 'react-client/src/ReactFlightClient';
import {
processReply,
createServerReference,
} from 'react-client/src/ReactFlightReplyClient';
type CallServerCallback = <A, T>(string, args: A) => Promise<T>;
export type Options = {
callServer?: CallServerCallback,
};
function createResponseFromOptions(options: void | Options) {
return createResponse(
null,
null,
options && options.callServer ? options.callServer : undefined,
undefined, // nonce
);
}
function startReadingFromStream(
response: FlightResponse,
stream: ReadableStream,
): void {
const reader = stream.getReader();
function progress({
done,
value,
}: {
done: boolean,
value: ?any,
...
}): void | Promise<void> {
if (done) {
close(response);
return;
}
const buffer: Uint8Array = (value: any);
processBinaryChunk(response, buffer);
return reader.read().then(progress).catch(error);
}
function error(e: any) {
reportGlobalError(response, e);
}
reader.read().then(progress).catch(error);
}
function createFromReadableStream<T>(
stream: ReadableStream,
options?: Options,
): Thenable<T> {
const response: FlightResponse = createResponseFromOptions(options);
startReadingFromStream(response, stream);
return getRoot(response);
}
function createFromFetch<T>(
promiseForResponse: Promise<Response>,
options?: Options,
): Thenable<T> {
const response: FlightResponse = createResponseFromOptions(options);
promiseForResponse.then(
function (r) {
startReadingFromStream(response, (r.body: any));
},
function (e) {
reportGlobalError(response, e);
},
);
return getRoot(response);
}
function encodeReply(
value: ReactServerValue,
): Promise<
string | URLSearchParams | FormData,
> /* We don't use URLSearchParams yet but maybe */ {
return new Promise((resolve, reject) => {
processReply(value, '', resolve, reject);
});
}
export {
createFromFetch,
createFromReadableStream,
encodeReply,
createServerReference,
};
| 21.839286 | 83 | 0.700039 |
PenTestScripts | /**
* 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
*/
// This is a host config that's used for the `react-server` package on npm.
// It is only used by third-party renderers.
//
// Its API lets you pass the host config as an argument.
// However, inside the `react-server` we treat host config as a module.
// This file is a shim between two worlds.
//
// It works because the `react-server` bundle is wrapped in something like:
//
// module.exports = function ($$$config) {
// /* renderer code */
// }
//
// So `$$$config` looks like a global variable, but it's
// really an argument to a top-level wrapping function.
declare var $$$config: any;
export opaque type ModuleLoading = mixed;
export opaque type SSRModuleMap = mixed;
export opaque type ServerManifest = mixed;
export opaque type ServerReferenceId = string;
export opaque type ClientReferenceMetadata = mixed;
export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars
export const resolveClientReference = $$$config.resolveClientReference;
export const resolveServerReference = $$$config.resolveServerReference;
export const preloadModule = $$$config.preloadModule;
export const requireModule = $$$config.requireModule;
export const dispatchHint = $$$config.dispatchHint;
export const prepareDestinationForModule =
$$$config.prepareDestinationForModule;
export const usedWithSSR = true;
export opaque type Source = mixed;
export opaque type StringDecoder = mixed; // eslint-disable-line no-undef
export const createStringDecoder = $$$config.createStringDecoder;
export const readPartialStringChunk = $$$config.readPartialStringChunk;
export const readFinalStringChunk = $$$config.readFinalStringChunk;
| 36.02 | 84 | 0.76 |
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
*/
// When passing user input into querySelector(All) the embedded string must not alter
// the semantics of the query. This escape function is safe to use when we know the
// provided value is going to be wrapped in double quotes as part of an attribute selector
// Do not use it anywhere else
// we escape double quotes and backslashes
const escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\n\"\\]/g;
export default function escapeSelectorAttributeValueInsideDoubleQuotes(
value: string,
): string {
return value.replace(
escapeSelectorAttributeValueInsideDoubleQuotesRegex,
ch => '\\' + ch.charCodeAt(0).toString(16) + ' ',
);
}
| 34.666667 | 90 | 0.745029 |
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-Second-Edition | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _extends = _interopDefault(require('@babel/runtime/helpers/extends'));
var _inheritsLoose = _interopDefault(require('@babel/runtime/helpers/inheritsLoose'));
var _assertThisInitialized = _interopDefault(require('@babel/runtime/helpers/assertThisInitialized'));
var memoizeOne = _interopDefault(require('memoize-one'));
var react = require('react');
var _objectWithoutPropertiesLoose = _interopDefault(require('@babel/runtime/helpers/objectWithoutPropertiesLoose'));
// Animation frame based implementation of setTimeout.
// Inspired by Joe Lambert, https://gist.github.com/joelambert/1002116#file-requesttimeout-js
var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
var now = hasNativePerformanceNow ? function () {
return performance.now();
} : function () {
return Date.now();
};
function cancelTimeout(timeoutID) {
cancelAnimationFrame(timeoutID.id);
}
function requestTimeout(callback, delay) {
var start = now();
function tick() {
if (now() - start >= delay) {
callback.call(null);
} else {
timeoutID.id = requestAnimationFrame(tick);
}
}
var timeoutID = {
id: requestAnimationFrame(tick)
};
return timeoutID;
}
var size = -1; // This utility copied from "dom-helpers" package.
function getScrollbarSize(recalculate) {
if (recalculate === void 0) {
recalculate = false;
}
if (size === -1 || recalculate) {
var div = document.createElement('div');
var style = div.style;
style.width = '50px';
style.height = '50px';
style.overflow = 'scroll';
document.body.appendChild(div);
size = div.offsetWidth - div.clientWidth;
document.body.removeChild(div);
}
return size;
}
var cachedRTLResult = null; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// Chrome does not seem to adhere; its scrollLeft values are positive (measured relative to the left).
// Safari's elastic bounce makes detecting this even more complicated wrt potential false positives.
// The safest way to check this is to intentionally set a negative offset,
// and then verify that the subsequent "scroll" event matches the negative offset.
// If it does not match, then we can assume a non-standard RTL scroll implementation.
function getRTLOffsetType(recalculate) {
if (recalculate === void 0) {
recalculate = false;
}
if (cachedRTLResult === null || recalculate) {
var outerDiv = document.createElement('div');
var outerStyle = outerDiv.style;
outerStyle.width = '50px';
outerStyle.height = '50px';
outerStyle.overflow = 'scroll';
outerStyle.direction = 'rtl';
var innerDiv = document.createElement('div');
var innerStyle = innerDiv.style;
innerStyle.width = '100px';
innerStyle.height = '100px';
outerDiv.appendChild(innerDiv);
document.body.appendChild(outerDiv);
if (outerDiv.scrollLeft > 0) {
cachedRTLResult = 'positive-descending';
} else {
outerDiv.scrollLeft = 1;
if (outerDiv.scrollLeft === 0) {
cachedRTLResult = 'negative';
} else {
cachedRTLResult = 'positive-ascending';
}
}
document.body.removeChild(outerDiv);
return cachedRTLResult;
}
return cachedRTLResult;
}
var IS_SCROLLING_DEBOUNCE_INTERVAL = 150;
var defaultItemKey = function defaultItemKey(_ref) {
var columnIndex = _ref.columnIndex,
data = _ref.data,
rowIndex = _ref.rowIndex;
return rowIndex + ":" + columnIndex;
}; // In DEV mode, this Set helps us only log a warning once per component instance.
// This avoids spamming the console every time a render happens.
var devWarningsOverscanCount = null;
var devWarningsOverscanRowsColumnsCount = null;
var devWarningsTagName = null;
if (process.env.NODE_ENV !== 'production') {
if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') {
devWarningsOverscanCount =
/*#__PURE__*/
new WeakSet();
devWarningsOverscanRowsColumnsCount =
/*#__PURE__*/
new WeakSet();
devWarningsTagName =
/*#__PURE__*/
new WeakSet();
}
}
function createGridComponent(_ref2) {
var _class, _temp;
var getColumnOffset = _ref2.getColumnOffset,
getColumnStartIndexForOffset = _ref2.getColumnStartIndexForOffset,
getColumnStopIndexForStartIndex = _ref2.getColumnStopIndexForStartIndex,
getColumnWidth = _ref2.getColumnWidth,
getEstimatedTotalHeight = _ref2.getEstimatedTotalHeight,
getEstimatedTotalWidth = _ref2.getEstimatedTotalWidth,
getOffsetForColumnAndAlignment = _ref2.getOffsetForColumnAndAlignment,
getOffsetForRowAndAlignment = _ref2.getOffsetForRowAndAlignment,
getRowHeight = _ref2.getRowHeight,
getRowOffset = _ref2.getRowOffset,
getRowStartIndexForOffset = _ref2.getRowStartIndexForOffset,
getRowStopIndexForStartIndex = _ref2.getRowStopIndexForStartIndex,
initInstanceProps = _ref2.initInstanceProps,
shouldResetStyleCacheOnItemSizeChange = _ref2.shouldResetStyleCacheOnItemSizeChange,
validateProps = _ref2.validateProps;
return _temp = _class =
/*#__PURE__*/
function (_PureComponent) {
_inheritsLoose(Grid, _PureComponent);
// Always use explicit constructor for React components.
// It produces less code after transpilation. (#26)
// eslint-disable-next-line no-useless-constructor
function Grid(props) {
var _this;
_this = _PureComponent.call(this, props) || this;
_this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_assertThisInitialized(_this)));
_this._resetIsScrollingTimeoutId = null;
_this._outerRef = void 0;
_this.state = {
instance: _assertThisInitialized(_assertThisInitialized(_this)),
isScrolling: false,
horizontalScrollDirection: 'forward',
scrollLeft: typeof _this.props.initialScrollLeft === 'number' ? _this.props.initialScrollLeft : 0,
scrollTop: typeof _this.props.initialScrollTop === 'number' ? _this.props.initialScrollTop : 0,
scrollUpdateWasRequested: false,
verticalScrollDirection: 'forward'
};
_this._callOnItemsRendered = void 0;
_this._callOnItemsRendered = memoizeOne(function (overscanColumnStartIndex, overscanColumnStopIndex, overscanRowStartIndex, overscanRowStopIndex, visibleColumnStartIndex, visibleColumnStopIndex, visibleRowStartIndex, visibleRowStopIndex) {
return _this.props.onItemsRendered({
overscanColumnStartIndex: overscanColumnStartIndex,
overscanColumnStopIndex: overscanColumnStopIndex,
overscanRowStartIndex: overscanRowStartIndex,
overscanRowStopIndex: overscanRowStopIndex,
visibleColumnStartIndex: visibleColumnStartIndex,
visibleColumnStopIndex: visibleColumnStopIndex,
visibleRowStartIndex: visibleRowStartIndex,
visibleRowStopIndex: visibleRowStopIndex
});
});
_this._callOnScroll = void 0;
_this._callOnScroll = memoizeOne(function (scrollLeft, scrollTop, horizontalScrollDirection, verticalScrollDirection, scrollUpdateWasRequested) {
return _this.props.onScroll({
horizontalScrollDirection: horizontalScrollDirection,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
verticalScrollDirection: verticalScrollDirection,
scrollUpdateWasRequested: scrollUpdateWasRequested
});
});
_this._getItemStyle = void 0;
_this._getItemStyle = function (rowIndex, columnIndex) {
var _this$props = _this.props,
columnWidth = _this$props.columnWidth,
direction = _this$props.direction,
rowHeight = _this$props.rowHeight;
var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && columnWidth, shouldResetStyleCacheOnItemSizeChange && direction, shouldResetStyleCacheOnItemSizeChange && rowHeight);
var key = rowIndex + ":" + columnIndex;
var style;
if (itemStyleCache.hasOwnProperty(key)) {
style = itemStyleCache[key];
} else {
var _style;
itemStyleCache[key] = style = (_style = {
position: 'absolute'
}, _style[direction === 'rtl' ? 'right' : 'left'] = getColumnOffset(_this.props, columnIndex, _this._instanceProps), _style.top = getRowOffset(_this.props, rowIndex, _this._instanceProps), _style.height = getRowHeight(_this.props, rowIndex, _this._instanceProps), _style.width = getColumnWidth(_this.props, columnIndex, _this._instanceProps), _style);
}
return style;
};
_this._getItemStyleCache = void 0;
_this._getItemStyleCache = memoizeOne(function (_, __, ___) {
return {};
});
_this._onScroll = function (event) {
var _event$currentTarget = event.currentTarget,
clientHeight = _event$currentTarget.clientHeight,
clientWidth = _event$currentTarget.clientWidth,
scrollLeft = _event$currentTarget.scrollLeft,
scrollTop = _event$currentTarget.scrollTop,
scrollHeight = _event$currentTarget.scrollHeight,
scrollWidth = _event$currentTarget.scrollWidth;
_this.setState(function (prevState) {
if (prevState.scrollLeft === scrollLeft && prevState.scrollTop === scrollTop) {
// Scroll position may have been updated by cDM/cDU,
// In which case we don't need to trigger another render,
// And we don't want to update state.isScrolling.
return null;
}
var direction = _this.props.direction; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// It's also easier for this component if we convert offsets to the same format as they would be in for ltr.
// So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.
var calculatedScrollLeft = scrollLeft;
if (direction === 'rtl') {
switch (getRTLOffsetType()) {
case 'negative':
calculatedScrollLeft = -scrollLeft;
break;
case 'positive-descending':
calculatedScrollLeft = scrollWidth - clientWidth - scrollLeft;
break;
}
} // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
calculatedScrollLeft = Math.max(0, Math.min(calculatedScrollLeft, scrollWidth - clientWidth));
var calculatedScrollTop = Math.max(0, Math.min(scrollTop, scrollHeight - clientHeight));
return {
isScrolling: true,
horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward',
scrollLeft: calculatedScrollLeft,
scrollTop: calculatedScrollTop,
verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward',
scrollUpdateWasRequested: false
};
}, _this._resetIsScrollingDebounced);
};
_this._outerRefSetter = function (ref) {
var outerRef = _this.props.outerRef;
_this._outerRef = ref;
if (typeof outerRef === 'function') {
outerRef(ref);
} else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) {
outerRef.current = ref;
}
};
_this._resetIsScrollingDebounced = function () {
if (_this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(_this._resetIsScrollingTimeoutId);
}
_this._resetIsScrollingTimeoutId = requestTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL);
};
_this._resetIsScrolling = function () {
_this._resetIsScrollingTimeoutId = null;
_this.setState({
isScrolling: false
}, function () {
// Clear style cache after state update has been committed.
// This way we don't break pure sCU for items that don't use isScrolling param.
_this._getItemStyleCache(-1);
});
};
return _this;
}
Grid.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
validateSharedProps(nextProps, prevState);
validateProps(nextProps);
return null;
};
var _proto = Grid.prototype;
_proto.scrollTo = function scrollTo(_ref3) {
var scrollLeft = _ref3.scrollLeft,
scrollTop = _ref3.scrollTop;
if (scrollLeft !== undefined) {
scrollLeft = Math.max(0, scrollLeft);
}
if (scrollTop !== undefined) {
scrollTop = Math.max(0, scrollTop);
}
this.setState(function (prevState) {
if (scrollLeft === undefined) {
scrollLeft = prevState.scrollLeft;
}
if (scrollTop === undefined) {
scrollTop = prevState.scrollTop;
}
if (prevState.scrollLeft === scrollLeft && prevState.scrollTop === scrollTop) {
return null;
}
return {
horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward',
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollUpdateWasRequested: true,
verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward'
};
}, this._resetIsScrollingDebounced);
};
_proto.scrollToItem = function scrollToItem(_ref4) {
var _ref4$align = _ref4.align,
align = _ref4$align === void 0 ? 'auto' : _ref4$align,
columnIndex = _ref4.columnIndex,
rowIndex = _ref4.rowIndex;
var _this$props2 = this.props,
columnCount = _this$props2.columnCount,
height = _this$props2.height,
rowCount = _this$props2.rowCount,
width = _this$props2.width;
var _this$state = this.state,
scrollLeft = _this$state.scrollLeft,
scrollTop = _this$state.scrollTop;
var scrollbarSize = getScrollbarSize();
if (columnIndex !== undefined) {
columnIndex = Math.max(0, Math.min(columnIndex, columnCount - 1));
}
if (rowIndex !== undefined) {
rowIndex = Math.max(0, Math.min(rowIndex, rowCount - 1));
}
var estimatedTotalHeight = getEstimatedTotalHeight(this.props, this._instanceProps);
var estimatedTotalWidth = getEstimatedTotalWidth(this.props, this._instanceProps); // The scrollbar size should be considered when scrolling an item into view,
// to ensure it's fully visible.
// But we only need to account for its size when it's actually visible.
var horizontalScrollbarSize = estimatedTotalWidth > width ? scrollbarSize : 0;
var verticalScrollbarSize = estimatedTotalHeight > height ? scrollbarSize : 0;
this.scrollTo({
scrollLeft: columnIndex !== undefined ? getOffsetForColumnAndAlignment(this.props, columnIndex, align, scrollLeft, this._instanceProps, verticalScrollbarSize) : scrollLeft,
scrollTop: rowIndex !== undefined ? getOffsetForRowAndAlignment(this.props, rowIndex, align, scrollTop, this._instanceProps, horizontalScrollbarSize) : scrollTop
});
};
_proto.componentDidMount = function componentDidMount() {
var _this$props3 = this.props,
initialScrollLeft = _this$props3.initialScrollLeft,
initialScrollTop = _this$props3.initialScrollTop;
if (this._outerRef != null) {
var outerRef = this._outerRef;
if (typeof initialScrollLeft === 'number') {
outerRef.scrollLeft = initialScrollLeft;
}
if (typeof initialScrollTop === 'number') {
outerRef.scrollTop = initialScrollTop;
}
}
this._callPropsCallbacks();
};
_proto.componentDidUpdate = function componentDidUpdate() {
var direction = this.props.direction;
var _this$state2 = this.state,
scrollLeft = _this$state2.scrollLeft,
scrollTop = _this$state2.scrollTop,
scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested;
if (scrollUpdateWasRequested && this._outerRef != null) {
// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// So we need to determine which browser behavior we're dealing with, and mimic it.
var outerRef = this._outerRef;
if (direction === 'rtl') {
switch (getRTLOffsetType()) {
case 'negative':
outerRef.scrollLeft = -scrollLeft;
break;
case 'positive-ascending':
outerRef.scrollLeft = scrollLeft;
break;
default:
var clientWidth = outerRef.clientWidth,
scrollWidth = outerRef.scrollWidth;
outerRef.scrollLeft = scrollWidth - clientWidth - scrollLeft;
break;
}
} else {
outerRef.scrollLeft = Math.max(0, scrollLeft);
}
outerRef.scrollTop = Math.max(0, scrollTop);
}
this._callPropsCallbacks();
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(this._resetIsScrollingTimeoutId);
}
};
_proto.render = function render() {
var _this$props4 = this.props,
children = _this$props4.children,
className = _this$props4.className,
columnCount = _this$props4.columnCount,
direction = _this$props4.direction,
height = _this$props4.height,
innerRef = _this$props4.innerRef,
innerElementType = _this$props4.innerElementType,
innerTagName = _this$props4.innerTagName,
itemData = _this$props4.itemData,
_this$props4$itemKey = _this$props4.itemKey,
itemKey = _this$props4$itemKey === void 0 ? defaultItemKey : _this$props4$itemKey,
outerElementType = _this$props4.outerElementType,
outerTagName = _this$props4.outerTagName,
rowCount = _this$props4.rowCount,
style = _this$props4.style,
useIsScrolling = _this$props4.useIsScrolling,
width = _this$props4.width;
var isScrolling = this.state.isScrolling;
var _this$_getHorizontalR = this._getHorizontalRangeToRender(),
columnStartIndex = _this$_getHorizontalR[0],
columnStopIndex = _this$_getHorizontalR[1];
var _this$_getVerticalRan = this._getVerticalRangeToRender(),
rowStartIndex = _this$_getVerticalRan[0],
rowStopIndex = _this$_getVerticalRan[1];
var items = [];
if (columnCount > 0 && rowCount) {
for (var _rowIndex = rowStartIndex; _rowIndex <= rowStopIndex; _rowIndex++) {
for (var _columnIndex = columnStartIndex; _columnIndex <= columnStopIndex; _columnIndex++) {
items.push(react.createElement(children, {
columnIndex: _columnIndex,
data: itemData,
isScrolling: useIsScrolling ? isScrolling : undefined,
key: itemKey({
columnIndex: _columnIndex,
data: itemData,
rowIndex: _rowIndex
}),
rowIndex: _rowIndex,
style: this._getItemStyle(_rowIndex, _columnIndex)
}));
}
}
} // Read this value AFTER items have been created,
// So their actual sizes (if variable) are taken into consideration.
var estimatedTotalHeight = getEstimatedTotalHeight(this.props, this._instanceProps);
var estimatedTotalWidth = getEstimatedTotalWidth(this.props, this._instanceProps);
return react.createElement(outerElementType || outerTagName || 'div', {
className: className,
onScroll: this._onScroll,
ref: this._outerRefSetter,
style: _extends({
position: 'relative',
height: height,
width: width,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
direction: direction
}, style)
}, react.createElement(innerElementType || innerTagName || 'div', {
children: items,
ref: innerRef,
style: {
height: estimatedTotalHeight,
pointerEvents: isScrolling ? 'none' : undefined,
width: estimatedTotalWidth
}
}));
};
_proto._callPropsCallbacks = function _callPropsCallbacks() {
var _this$props5 = this.props,
columnCount = _this$props5.columnCount,
onItemsRendered = _this$props5.onItemsRendered,
onScroll = _this$props5.onScroll,
rowCount = _this$props5.rowCount;
if (typeof onItemsRendered === 'function') {
if (columnCount > 0 && rowCount > 0) {
var _this$_getHorizontalR2 = this._getHorizontalRangeToRender(),
_overscanColumnStartIndex = _this$_getHorizontalR2[0],
_overscanColumnStopIndex = _this$_getHorizontalR2[1],
_visibleColumnStartIndex = _this$_getHorizontalR2[2],
_visibleColumnStopIndex = _this$_getHorizontalR2[3];
var _this$_getVerticalRan2 = this._getVerticalRangeToRender(),
_overscanRowStartIndex = _this$_getVerticalRan2[0],
_overscanRowStopIndex = _this$_getVerticalRan2[1],
_visibleRowStartIndex = _this$_getVerticalRan2[2],
_visibleRowStopIndex = _this$_getVerticalRan2[3];
this._callOnItemsRendered(_overscanColumnStartIndex, _overscanColumnStopIndex, _overscanRowStartIndex, _overscanRowStopIndex, _visibleColumnStartIndex, _visibleColumnStopIndex, _visibleRowStartIndex, _visibleRowStopIndex);
}
}
if (typeof onScroll === 'function') {
var _this$state3 = this.state,
_horizontalScrollDirection = _this$state3.horizontalScrollDirection,
_scrollLeft = _this$state3.scrollLeft,
_scrollTop = _this$state3.scrollTop,
_scrollUpdateWasRequested = _this$state3.scrollUpdateWasRequested,
_verticalScrollDirection = _this$state3.verticalScrollDirection;
this._callOnScroll(_scrollLeft, _scrollTop, _horizontalScrollDirection, _verticalScrollDirection, _scrollUpdateWasRequested);
}
}; // Lazily create and cache item styles while scrolling,
// So that pure component sCU will prevent re-renders.
// We maintain this cache, and pass a style prop rather than index,
// So that List can clear cached styles and force item re-render if necessary.
_proto._getHorizontalRangeToRender = function _getHorizontalRangeToRender() {
var _this$props6 = this.props,
columnCount = _this$props6.columnCount,
overscanColumnCount = _this$props6.overscanColumnCount,
overscanColumnsCount = _this$props6.overscanColumnsCount,
overscanCount = _this$props6.overscanCount,
rowCount = _this$props6.rowCount;
var _this$state4 = this.state,
horizontalScrollDirection = _this$state4.horizontalScrollDirection,
isScrolling = _this$state4.isScrolling,
scrollLeft = _this$state4.scrollLeft;
var overscanCountResolved = overscanColumnCount || overscanColumnsCount || overscanCount || 1;
if (columnCount === 0 || rowCount === 0) {
return [0, 0, 0, 0];
}
var startIndex = getColumnStartIndexForOffset(this.props, scrollLeft, this._instanceProps);
var stopIndex = getColumnStopIndexForStartIndex(this.props, startIndex, scrollLeft, this._instanceProps); // Overscan by one item in each direction so that tab/focus works.
// If there isn't at least one extra item, tab loops back around.
var overscanBackward = !isScrolling || horizontalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1;
var overscanForward = !isScrolling || horizontalScrollDirection === 'forward' ? Math.max(1, overscanCountResolved) : 1;
return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(columnCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
};
_proto._getVerticalRangeToRender = function _getVerticalRangeToRender() {
var _this$props7 = this.props,
columnCount = _this$props7.columnCount,
overscanCount = _this$props7.overscanCount,
overscanRowCount = _this$props7.overscanRowCount,
overscanRowsCount = _this$props7.overscanRowsCount,
rowCount = _this$props7.rowCount;
var _this$state5 = this.state,
isScrolling = _this$state5.isScrolling,
verticalScrollDirection = _this$state5.verticalScrollDirection,
scrollTop = _this$state5.scrollTop;
var overscanCountResolved = overscanRowCount || overscanRowsCount || overscanCount || 1;
if (columnCount === 0 || rowCount === 0) {
return [0, 0, 0, 0];
}
var startIndex = getRowStartIndexForOffset(this.props, scrollTop, this._instanceProps);
var stopIndex = getRowStopIndexForStartIndex(this.props, startIndex, scrollTop, this._instanceProps); // Overscan by one item in each direction so that tab/focus works.
// If there isn't at least one extra item, tab loops back around.
var overscanBackward = !isScrolling || verticalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1;
var overscanForward = !isScrolling || verticalScrollDirection === 'forward' ? Math.max(1, overscanCountResolved) : 1;
return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(rowCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
};
return Grid;
}(react.PureComponent), _class.defaultProps = {
direction: 'ltr',
itemData: undefined,
useIsScrolling: false
}, _temp;
}
var validateSharedProps = function validateSharedProps(_ref5, _ref6) {
var children = _ref5.children,
direction = _ref5.direction,
height = _ref5.height,
innerTagName = _ref5.innerTagName,
outerTagName = _ref5.outerTagName,
overscanColumnsCount = _ref5.overscanColumnsCount,
overscanCount = _ref5.overscanCount,
overscanRowsCount = _ref5.overscanRowsCount,
width = _ref5.width;
var instance = _ref6.instance;
if (process.env.NODE_ENV !== 'production') {
if (typeof overscanCount === 'number') {
if (devWarningsOverscanCount && !devWarningsOverscanCount.has(instance)) {
devWarningsOverscanCount.add(instance);
console.warn('The overscanCount prop has been deprecated. ' + 'Please use the overscanColumnCount and overscanRowCount props instead.');
}
}
if (typeof overscanColumnsCount === 'number' || typeof overscanRowsCount === 'number') {
if (devWarningsOverscanRowsColumnsCount && !devWarningsOverscanRowsColumnsCount.has(instance)) {
devWarningsOverscanRowsColumnsCount.add(instance);
console.warn('The overscanColumnsCount and overscanRowsCount props have been deprecated. ' + 'Please use the overscanColumnCount and overscanRowCount props instead.');
}
}
if (innerTagName != null || outerTagName != null) {
if (devWarningsTagName && !devWarningsTagName.has(instance)) {
devWarningsTagName.add(instance);
console.warn('The innerTagName and outerTagName props have been deprecated. ' + 'Please use the innerElementType and outerElementType props instead.');
}
}
if (children == null) {
throw Error('An invalid "children" prop has been specified. ' + 'Value should be a React component. ' + ("\"" + (children === null ? 'null' : typeof children) + "\" was specified."));
}
switch (direction) {
case 'ltr':
case 'rtl':
// Valid values
break;
default:
throw Error('An invalid "direction" prop has been specified. ' + 'Value should be either "ltr" or "rtl". ' + ("\"" + direction + "\" was specified."));
}
if (typeof width !== 'number') {
throw Error('An invalid "width" prop has been specified. ' + 'Grids must specify a number for width. ' + ("\"" + (width === null ? 'null' : typeof width) + "\" was specified."));
}
if (typeof height !== 'number') {
throw Error('An invalid "height" prop has been specified. ' + 'Grids must specify a number for height. ' + ("\"" + (height === null ? 'null' : typeof height) + "\" was specified."));
}
}
};
var DEFAULT_ESTIMATED_ITEM_SIZE = 50;
var getEstimatedTotalHeight = function getEstimatedTotalHeight(_ref, _ref2) {
var rowCount = _ref.rowCount;
var rowMetadataMap = _ref2.rowMetadataMap,
estimatedRowHeight = _ref2.estimatedRowHeight,
lastMeasuredRowIndex = _ref2.lastMeasuredRowIndex;
var totalSizeOfMeasuredRows = 0; // Edge case check for when the number of items decreases while a scroll is in progress.
// https://github.com/bvaughn/react-window/pull/138
if (lastMeasuredRowIndex >= rowCount) {
lastMeasuredRowIndex = rowCount - 1;
}
if (lastMeasuredRowIndex >= 0) {
var itemMetadata = rowMetadataMap[lastMeasuredRowIndex];
totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size;
}
var numUnmeasuredItems = rowCount - lastMeasuredRowIndex - 1;
var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedRowHeight;
return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems;
};
var getEstimatedTotalWidth = function getEstimatedTotalWidth(_ref3, _ref4) {
var columnCount = _ref3.columnCount;
var columnMetadataMap = _ref4.columnMetadataMap,
estimatedColumnWidth = _ref4.estimatedColumnWidth,
lastMeasuredColumnIndex = _ref4.lastMeasuredColumnIndex;
var totalSizeOfMeasuredRows = 0; // Edge case check for when the number of items decreases while a scroll is in progress.
// https://github.com/bvaughn/react-window/pull/138
if (lastMeasuredColumnIndex >= columnCount) {
lastMeasuredColumnIndex = columnCount - 1;
}
if (lastMeasuredColumnIndex >= 0) {
var itemMetadata = columnMetadataMap[lastMeasuredColumnIndex];
totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size;
}
var numUnmeasuredItems = columnCount - lastMeasuredColumnIndex - 1;
var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedColumnWidth;
return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems;
};
var getItemMetadata = function getItemMetadata(itemType, props, index, instanceProps) {
var itemMetadataMap, itemSize, lastMeasuredIndex;
if (itemType === 'column') {
itemMetadataMap = instanceProps.columnMetadataMap;
itemSize = props.columnWidth;
lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex;
} else {
itemMetadataMap = instanceProps.rowMetadataMap;
itemSize = props.rowHeight;
lastMeasuredIndex = instanceProps.lastMeasuredRowIndex;
}
if (index > lastMeasuredIndex) {
var offset = 0;
if (lastMeasuredIndex >= 0) {
var itemMetadata = itemMetadataMap[lastMeasuredIndex];
offset = itemMetadata.offset + itemMetadata.size;
}
for (var i = lastMeasuredIndex + 1; i <= index; i++) {
var size = itemSize(i);
itemMetadataMap[i] = {
offset: offset,
size: size
};
offset += size;
}
if (itemType === 'column') {
instanceProps.lastMeasuredColumnIndex = index;
} else {
instanceProps.lastMeasuredRowIndex = index;
}
}
return itemMetadataMap[index];
};
var findNearestItem = function findNearestItem(itemType, props, instanceProps, offset) {
var itemMetadataMap, lastMeasuredIndex;
if (itemType === 'column') {
itemMetadataMap = instanceProps.columnMetadataMap;
lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex;
} else {
itemMetadataMap = instanceProps.rowMetadataMap;
lastMeasuredIndex = instanceProps.lastMeasuredRowIndex;
}
var lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0;
if (lastMeasuredItemOffset >= offset) {
// If we've already measured items within this range just use a binary search as it's faster.
return findNearestItemBinarySearch(itemType, props, instanceProps, lastMeasuredIndex, 0, offset);
} else {
// If we haven't yet measured this high, fallback to an exponential search with an inner binary search.
// The exponential search avoids pre-computing sizes for the full set of items as a binary search would.
// The overall complexity for this approach is O(log n).
return findNearestItemExponentialSearch(itemType, props, instanceProps, Math.max(0, lastMeasuredIndex), offset);
}
};
var findNearestItemBinarySearch = function findNearestItemBinarySearch(itemType, props, instanceProps, high, low, offset) {
while (low <= high) {
var middle = low + Math.floor((high - low) / 2);
var currentOffset = getItemMetadata(itemType, props, middle, instanceProps).offset;
if (currentOffset === offset) {
return middle;
} else if (currentOffset < offset) {
low = middle + 1;
} else if (currentOffset > offset) {
high = middle - 1;
}
}
if (low > 0) {
return low - 1;
} else {
return 0;
}
};
var findNearestItemExponentialSearch = function findNearestItemExponentialSearch(itemType, props, instanceProps, index, offset) {
var itemCount = itemType === 'column' ? props.columnCount : props.rowCount;
var interval = 1;
while (index < itemCount && getItemMetadata(itemType, props, index, instanceProps).offset < offset) {
index += interval;
interval *= 2;
}
return findNearestItemBinarySearch(itemType, props, instanceProps, Math.min(index, itemCount - 1), Math.floor(index / 2), offset);
};
var getOffsetForIndexAndAlignment = function getOffsetForIndexAndAlignment(itemType, props, index, align, scrollOffset, instanceProps, scrollbarSize) {
var size = itemType === 'column' ? props.width : props.height;
var itemMetadata = getItemMetadata(itemType, props, index, instanceProps); // Get estimated total size after ItemMetadata is computed,
// To ensure it reflects actual measurements instead of just estimates.
var estimatedTotalSize = itemType === 'column' ? getEstimatedTotalWidth(props, instanceProps) : getEstimatedTotalHeight(props, instanceProps);
var maxOffset = Math.max(0, Math.min(estimatedTotalSize - size, itemMetadata.offset));
var minOffset = Math.max(0, itemMetadata.offset - size + scrollbarSize + itemMetadata.size);
if (align === 'smart') {
if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) {
align = 'auto';
} else {
align = 'center';
}
}
switch (align) {
case 'start':
return maxOffset;
case 'end':
return minOffset;
case 'center':
return Math.round(minOffset + (maxOffset - minOffset) / 2);
case 'auto':
default:
if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {
return scrollOffset;
} 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 (scrollOffset < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
};
var VariableSizeGrid =
/*#__PURE__*/
createGridComponent({
getColumnOffset: function getColumnOffset(props, index, instanceProps) {
return getItemMetadata('column', props, index, instanceProps).offset;
},
getColumnStartIndexForOffset: function getColumnStartIndexForOffset(props, scrollLeft, instanceProps) {
return findNearestItem('column', props, instanceProps, scrollLeft);
},
getColumnStopIndexForStartIndex: function getColumnStopIndexForStartIndex(props, startIndex, scrollLeft, instanceProps) {
var columnCount = props.columnCount,
width = props.width;
var itemMetadata = getItemMetadata('column', props, startIndex, instanceProps);
var maxOffset = scrollLeft + width;
var offset = itemMetadata.offset + itemMetadata.size;
var stopIndex = startIndex;
while (stopIndex < columnCount - 1 && offset < maxOffset) {
stopIndex++;
offset += getItemMetadata('column', props, stopIndex, instanceProps).size;
}
return stopIndex;
},
getColumnWidth: function getColumnWidth(props, index, instanceProps) {
return instanceProps.columnMetadataMap[index].size;
},
getEstimatedTotalHeight: getEstimatedTotalHeight,
getEstimatedTotalWidth: getEstimatedTotalWidth,
getOffsetForColumnAndAlignment: function getOffsetForColumnAndAlignment(props, index, align, scrollOffset, instanceProps, scrollbarSize) {
return getOffsetForIndexAndAlignment('column', props, index, align, scrollOffset, instanceProps, scrollbarSize);
},
getOffsetForRowAndAlignment: function getOffsetForRowAndAlignment(props, index, align, scrollOffset, instanceProps, scrollbarSize) {
return getOffsetForIndexAndAlignment('row', props, index, align, scrollOffset, instanceProps, scrollbarSize);
},
getRowOffset: function getRowOffset(props, index, instanceProps) {
return getItemMetadata('row', props, index, instanceProps).offset;
},
getRowHeight: function getRowHeight(props, index, instanceProps) {
return instanceProps.rowMetadataMap[index].size;
},
getRowStartIndexForOffset: function getRowStartIndexForOffset(props, scrollTop, instanceProps) {
return findNearestItem('row', props, instanceProps, scrollTop);
},
getRowStopIndexForStartIndex: function getRowStopIndexForStartIndex(props, startIndex, scrollTop, instanceProps) {
var rowCount = props.rowCount,
height = props.height;
var itemMetadata = getItemMetadata('row', props, startIndex, instanceProps);
var maxOffset = scrollTop + height;
var offset = itemMetadata.offset + itemMetadata.size;
var stopIndex = startIndex;
while (stopIndex < rowCount - 1 && offset < maxOffset) {
stopIndex++;
offset += getItemMetadata('row', props, stopIndex, instanceProps).size;
}
return stopIndex;
},
initInstanceProps: function initInstanceProps(props, instance) {
var _ref5 = props,
estimatedColumnWidth = _ref5.estimatedColumnWidth,
estimatedRowHeight = _ref5.estimatedRowHeight;
var instanceProps = {
columnMetadataMap: {},
estimatedColumnWidth: estimatedColumnWidth || DEFAULT_ESTIMATED_ITEM_SIZE,
estimatedRowHeight: estimatedRowHeight || DEFAULT_ESTIMATED_ITEM_SIZE,
lastMeasuredColumnIndex: -1,
lastMeasuredRowIndex: -1,
rowMetadataMap: {}
};
instance.resetAfterColumnIndex = function (columnIndex, shouldForceUpdate) {
if (shouldForceUpdate === void 0) {
shouldForceUpdate = true;
}
instance.resetAfterIndices({
columnIndex: columnIndex,
shouldForceUpdate: shouldForceUpdate
});
};
instance.resetAfterRowIndex = function (rowIndex, shouldForceUpdate) {
if (shouldForceUpdate === void 0) {
shouldForceUpdate = true;
}
instance.resetAfterIndices({
rowIndex: rowIndex,
shouldForceUpdate: shouldForceUpdate
});
};
instance.resetAfterIndices = function (_ref6) {
var columnIndex = _ref6.columnIndex,
rowIndex = _ref6.rowIndex,
_ref6$shouldForceUpda = _ref6.shouldForceUpdate,
shouldForceUpdate = _ref6$shouldForceUpda === void 0 ? true : _ref6$shouldForceUpda;
if (typeof columnIndex === 'number') {
instanceProps.lastMeasuredColumnIndex = Math.min(instanceProps.lastMeasuredColumnIndex, columnIndex - 1);
}
if (typeof rowIndex === 'number') {
instanceProps.lastMeasuredRowIndex = Math.min(instanceProps.lastMeasuredRowIndex, rowIndex - 1);
} // We could potentially optimize further by only evicting styles after this index,
// But since styles are only cached while scrolling is in progress-
// It seems an unnecessary optimization.
// It's unlikely that resetAfterIndex() will be called while a user is scrolling.
instance._getItemStyleCache(-1);
if (shouldForceUpdate) {
instance.forceUpdate();
}
};
return instanceProps;
},
shouldResetStyleCacheOnItemSizeChange: false,
validateProps: function validateProps(_ref7) {
var columnWidth = _ref7.columnWidth,
rowHeight = _ref7.rowHeight;
if (process.env.NODE_ENV !== 'production') {
if (typeof columnWidth !== 'function') {
throw Error('An invalid "columnWidth" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (columnWidth === null ? 'null' : typeof columnWidth) + "\" was specified."));
} else if (typeof rowHeight !== 'function') {
throw Error('An invalid "rowHeight" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (rowHeight === null ? 'null' : typeof rowHeight) + "\" was specified."));
}
}
}
});
var IS_SCROLLING_DEBOUNCE_INTERVAL$1 = 150;
var defaultItemKey$1 = function defaultItemKey(index, data) {
return index;
}; // In DEV mode, this Set helps us only log a warning once per component instance.
// This avoids spamming the console every time a render happens.
var devWarningsDirection = null;
var devWarningsTagName$1 = null;
if (process.env.NODE_ENV !== 'production') {
if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') {
devWarningsDirection =
/*#__PURE__*/
new WeakSet();
devWarningsTagName$1 =
/*#__PURE__*/
new WeakSet();
}
}
function createListComponent(_ref) {
var _class, _temp;
var getItemOffset = _ref.getItemOffset,
getEstimatedTotalSize = _ref.getEstimatedTotalSize,
getItemSize = _ref.getItemSize,
getOffsetForIndexAndAlignment = _ref.getOffsetForIndexAndAlignment,
getStartIndexForOffset = _ref.getStartIndexForOffset,
getStopIndexForStartIndex = _ref.getStopIndexForStartIndex,
initInstanceProps = _ref.initInstanceProps,
shouldResetStyleCacheOnItemSizeChange = _ref.shouldResetStyleCacheOnItemSizeChange,
validateProps = _ref.validateProps;
return _temp = _class =
/*#__PURE__*/
function (_PureComponent) {
_inheritsLoose(List, _PureComponent);
// Always use explicit constructor for React components.
// It produces less code after transpilation. (#26)
// eslint-disable-next-line no-useless-constructor
function List(props) {
var _this;
_this = _PureComponent.call(this, props) || this;
_this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_assertThisInitialized(_this)));
_this._outerRef = void 0;
_this._resetIsScrollingTimeoutId = null;
_this.state = {
instance: _assertThisInitialized(_assertThisInitialized(_this)),
isScrolling: false,
scrollDirection: 'forward',
scrollOffset: typeof _this.props.initialScrollOffset === 'number' ? _this.props.initialScrollOffset : 0,
scrollUpdateWasRequested: false
};
_this._callOnItemsRendered = void 0;
_this._callOnItemsRendered = memoizeOne(function (overscanStartIndex, overscanStopIndex, visibleStartIndex, visibleStopIndex) {
return _this.props.onItemsRendered({
overscanStartIndex: overscanStartIndex,
overscanStopIndex: overscanStopIndex,
visibleStartIndex: visibleStartIndex,
visibleStopIndex: visibleStopIndex
});
});
_this._callOnScroll = void 0;
_this._callOnScroll = memoizeOne(function (scrollDirection, scrollOffset, scrollUpdateWasRequested) {
return _this.props.onScroll({
scrollDirection: scrollDirection,
scrollOffset: scrollOffset,
scrollUpdateWasRequested: scrollUpdateWasRequested
});
});
_this._getItemStyle = void 0;
_this._getItemStyle = function (index) {
var _this$props = _this.props,
direction = _this$props.direction,
itemSize = _this$props.itemSize,
layout = _this$props.layout;
var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && itemSize, shouldResetStyleCacheOnItemSizeChange && layout, shouldResetStyleCacheOnItemSizeChange && direction);
var style;
if (itemStyleCache.hasOwnProperty(index)) {
style = itemStyleCache[index];
} else {
var _style;
var _offset = getItemOffset(_this.props, index, _this._instanceProps);
var size = getItemSize(_this.props, index, _this._instanceProps); // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
itemStyleCache[index] = style = (_style = {
position: 'absolute'
}, _style[direction === 'rtl' ? 'right' : 'left'] = isHorizontal ? _offset : 0, _style.top = !isHorizontal ? _offset : 0, _style.height = !isHorizontal ? size : '100%', _style.width = isHorizontal ? size : '100%', _style);
}
return style;
};
_this._getItemStyleCache = void 0;
_this._getItemStyleCache = memoizeOne(function (_, __, ___) {
return {};
});
_this._onScrollHorizontal = function (event) {
var _event$currentTarget = event.currentTarget,
clientWidth = _event$currentTarget.clientWidth,
scrollLeft = _event$currentTarget.scrollLeft,
scrollWidth = _event$currentTarget.scrollWidth;
_this.setState(function (prevState) {
if (prevState.scrollOffset === scrollLeft) {
// Scroll position may have been updated by cDM/cDU,
// In which case we don't need to trigger another render,
// And we don't want to update state.isScrolling.
return null;
}
var direction = _this.props.direction;
var scrollOffset = scrollLeft;
if (direction === 'rtl') {
// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// It's also easier for this component if we convert offsets to the same format as they would be in for ltr.
// So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.
switch (getRTLOffsetType()) {
case 'negative':
scrollOffset = -scrollLeft;
break;
case 'positive-descending':
scrollOffset = scrollWidth - clientWidth - scrollLeft;
break;
}
} // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
scrollOffset = Math.max(0, Math.min(scrollOffset, scrollWidth - clientWidth));
return {
isScrolling: true,
scrollDirection: prevState.scrollOffset < scrollLeft ? 'forward' : 'backward',
scrollOffset: scrollOffset,
scrollUpdateWasRequested: false
};
}, _this._resetIsScrollingDebounced);
};
_this._onScrollVertical = function (event) {
var _event$currentTarget2 = event.currentTarget,
clientHeight = _event$currentTarget2.clientHeight,
scrollHeight = _event$currentTarget2.scrollHeight,
scrollTop = _event$currentTarget2.scrollTop;
_this.setState(function (prevState) {
if (prevState.scrollOffset === scrollTop) {
// Scroll position may have been updated by cDM/cDU,
// In which case we don't need to trigger another render,
// And we don't want to update state.isScrolling.
return null;
} // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
var scrollOffset = Math.max(0, Math.min(scrollTop, scrollHeight - clientHeight));
return {
isScrolling: true,
scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
scrollOffset: scrollOffset,
scrollUpdateWasRequested: false
};
}, _this._resetIsScrollingDebounced);
};
_this._outerRefSetter = function (ref) {
var outerRef = _this.props.outerRef;
_this._outerRef = ref;
if (typeof outerRef === 'function') {
outerRef(ref);
} else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) {
outerRef.current = ref;
}
};
_this._resetIsScrollingDebounced = function () {
if (_this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(_this._resetIsScrollingTimeoutId);
}
_this._resetIsScrollingTimeoutId = requestTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL$1);
};
_this._resetIsScrolling = function () {
_this._resetIsScrollingTimeoutId = null;
_this.setState({
isScrolling: false
}, function () {
// Clear style cache after state update has been committed.
// This way we don't break pure sCU for items that don't use isScrolling param.
_this._getItemStyleCache(-1, null);
});
};
return _this;
}
List.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
validateSharedProps$1(nextProps, prevState);
validateProps(nextProps);
return null;
};
var _proto = List.prototype;
_proto.scrollTo = function scrollTo(scrollOffset) {
scrollOffset = Math.max(0, scrollOffset);
this.setState(function (prevState) {
if (prevState.scrollOffset === scrollOffset) {
return null;
}
return {
scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
scrollOffset: scrollOffset,
scrollUpdateWasRequested: true
};
}, this._resetIsScrollingDebounced);
};
_proto.scrollToItem = function scrollToItem(index, align) {
if (align === void 0) {
align = 'auto';
}
var itemCount = this.props.itemCount;
var scrollOffset = this.state.scrollOffset;
index = Math.max(0, Math.min(index, itemCount - 1));
this.scrollTo(getOffsetForIndexAndAlignment(this.props, index, align, scrollOffset, this._instanceProps));
};
_proto.componentDidMount = function componentDidMount() {
var _this$props2 = this.props,
direction = _this$props2.direction,
initialScrollOffset = _this$props2.initialScrollOffset,
layout = _this$props2.layout;
if (typeof initialScrollOffset === 'number' && this._outerRef != null) {
var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"
if (direction === 'horizontal' || layout === 'horizontal') {
outerRef.scrollLeft = initialScrollOffset;
} else {
outerRef.scrollTop = initialScrollOffset;
}
}
this._callPropsCallbacks();
};
_proto.componentDidUpdate = function componentDidUpdate() {
var _this$props3 = this.props,
direction = _this$props3.direction,
layout = _this$props3.layout;
var _this$state = this.state,
scrollOffset = _this$state.scrollOffset,
scrollUpdateWasRequested = _this$state.scrollUpdateWasRequested;
if (scrollUpdateWasRequested && this._outerRef != null) {
var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"
if (direction === 'horizontal' || layout === 'horizontal') {
if (direction === 'rtl') {
// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// So we need to determine which browser behavior we're dealing with, and mimic it.
switch (getRTLOffsetType()) {
case 'negative':
outerRef.scrollLeft = -scrollOffset;
break;
case 'positive-ascending':
outerRef.scrollLeft = scrollOffset;
break;
default:
var clientWidth = outerRef.clientWidth,
scrollWidth = outerRef.scrollWidth;
outerRef.scrollLeft = scrollWidth - clientWidth - scrollOffset;
break;
}
} else {
outerRef.scrollLeft = scrollOffset;
}
} else {
outerRef.scrollTop = scrollOffset;
}
}
this._callPropsCallbacks();
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(this._resetIsScrollingTimeoutId);
}
};
_proto.render = function render() {
var _this$props4 = this.props,
children = _this$props4.children,
className = _this$props4.className,
direction = _this$props4.direction,
height = _this$props4.height,
innerRef = _this$props4.innerRef,
innerElementType = _this$props4.innerElementType,
innerTagName = _this$props4.innerTagName,
itemCount = _this$props4.itemCount,
itemData = _this$props4.itemData,
_this$props4$itemKey = _this$props4.itemKey,
itemKey = _this$props4$itemKey === void 0 ? defaultItemKey$1 : _this$props4$itemKey,
layout = _this$props4.layout,
outerElementType = _this$props4.outerElementType,
outerTagName = _this$props4.outerTagName,
style = _this$props4.style,
useIsScrolling = _this$props4.useIsScrolling,
width = _this$props4.width;
var isScrolling = this.state.isScrolling; // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var onScroll = isHorizontal ? this._onScrollHorizontal : this._onScrollVertical;
var _this$_getRangeToRend = this._getRangeToRender(),
startIndex = _this$_getRangeToRend[0],
stopIndex = _this$_getRangeToRend[1];
var items = [];
if (itemCount > 0) {
for (var _index = startIndex; _index <= stopIndex; _index++) {
items.push(react.createElement(children, {
data: itemData,
key: itemKey(_index, itemData),
index: _index,
isScrolling: useIsScrolling ? isScrolling : undefined,
style: this._getItemStyle(_index)
}));
}
} // Read this value AFTER items have been created,
// So their actual sizes (if variable) are taken into consideration.
var estimatedTotalSize = getEstimatedTotalSize(this.props, this._instanceProps);
return react.createElement(outerElementType || outerTagName || 'div', {
className: className,
onScroll: onScroll,
ref: this._outerRefSetter,
style: _extends({
position: 'relative',
height: height,
width: width,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
direction: direction
}, style)
}, react.createElement(innerElementType || innerTagName || 'div', {
children: items,
ref: innerRef,
style: {
height: isHorizontal ? '100%' : estimatedTotalSize,
pointerEvents: isScrolling ? 'none' : undefined,
width: isHorizontal ? estimatedTotalSize : '100%'
}
}));
};
_proto._callPropsCallbacks = function _callPropsCallbacks() {
if (typeof this.props.onItemsRendered === 'function') {
var itemCount = this.props.itemCount;
if (itemCount > 0) {
var _this$_getRangeToRend2 = this._getRangeToRender(),
_overscanStartIndex = _this$_getRangeToRend2[0],
_overscanStopIndex = _this$_getRangeToRend2[1],
_visibleStartIndex = _this$_getRangeToRend2[2],
_visibleStopIndex = _this$_getRangeToRend2[3];
this._callOnItemsRendered(_overscanStartIndex, _overscanStopIndex, _visibleStartIndex, _visibleStopIndex);
}
}
if (typeof this.props.onScroll === 'function') {
var _this$state2 = this.state,
_scrollDirection = _this$state2.scrollDirection,
_scrollOffset = _this$state2.scrollOffset,
_scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested;
this._callOnScroll(_scrollDirection, _scrollOffset, _scrollUpdateWasRequested);
}
}; // Lazily create and cache item styles while scrolling,
// So that pure component sCU will prevent re-renders.
// We maintain this cache, and pass a style prop rather than index,
// So that List can clear cached styles and force item re-render if necessary.
_proto._getRangeToRender = function _getRangeToRender() {
var _this$props5 = this.props,
itemCount = _this$props5.itemCount,
overscanCount = _this$props5.overscanCount;
var _this$state3 = this.state,
isScrolling = _this$state3.isScrolling,
scrollDirection = _this$state3.scrollDirection,
scrollOffset = _this$state3.scrollOffset;
if (itemCount === 0) {
return [0, 0, 0, 0];
}
var startIndex = getStartIndexForOffset(this.props, scrollOffset, this._instanceProps);
var stopIndex = getStopIndexForStartIndex(this.props, startIndex, scrollOffset, this._instanceProps); // Overscan by one item in each direction so that tab/focus works.
// If there isn't at least one extra item, tab loops back around.
var overscanBackward = !isScrolling || scrollDirection === 'backward' ? Math.max(1, overscanCount) : 1;
var overscanForward = !isScrolling || scrollDirection === 'forward' ? Math.max(1, overscanCount) : 1;
return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
};
return List;
}(react.PureComponent), _class.defaultProps = {
direction: 'ltr',
itemData: undefined,
layout: 'vertical',
overscanCount: 2,
useIsScrolling: false
}, _temp;
} // NOTE: I considered further wrapping individual items with a pure ListItem component.
// This would avoid ever calling the render function for the same index more than once,
// But it would also add the overhead of a lot of components/fibers.
// I assume people already do this (render function returning a class component),
// So my doing it would just unnecessarily double the wrappers.
var validateSharedProps$1 = function validateSharedProps(_ref2, _ref3) {
var children = _ref2.children,
direction = _ref2.direction,
height = _ref2.height,
layout = _ref2.layout,
innerTagName = _ref2.innerTagName,
outerTagName = _ref2.outerTagName,
width = _ref2.width;
var instance = _ref3.instance;
if (process.env.NODE_ENV !== 'production') {
if (innerTagName != null || outerTagName != null) {
if (devWarningsTagName$1 && !devWarningsTagName$1.has(instance)) {
devWarningsTagName$1.add(instance);
console.warn('The innerTagName and outerTagName props have been deprecated. ' + 'Please use the innerElementType and outerElementType props instead.');
}
} // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
switch (direction) {
case 'horizontal':
case 'vertical':
if (devWarningsDirection && !devWarningsDirection.has(instance)) {
devWarningsDirection.add(instance);
console.warn('The direction prop should be either "ltr" (default) or "rtl". ' + 'Please use the layout prop to specify "vertical" (default) or "horizontal" orientation.');
}
break;
case 'ltr':
case 'rtl':
// Valid values
break;
default:
throw Error('An invalid "direction" prop has been specified. ' + 'Value should be either "ltr" or "rtl". ' + ("\"" + direction + "\" was specified."));
}
switch (layout) {
case 'horizontal':
case 'vertical':
// Valid values
break;
default:
throw Error('An invalid "layout" prop has been specified. ' + 'Value should be either "horizontal" or "vertical". ' + ("\"" + layout + "\" was specified."));
}
if (children == null) {
throw Error('An invalid "children" prop has been specified. ' + 'Value should be a React component. ' + ("\"" + (children === null ? 'null' : typeof children) + "\" was specified."));
}
if (isHorizontal && typeof width !== 'number') {
throw Error('An invalid "width" prop has been specified. ' + 'Horizontal lists must specify a number for width. ' + ("\"" + (width === null ? 'null' : typeof width) + "\" was specified."));
} else if (!isHorizontal && typeof height !== 'number') {
throw Error('An invalid "height" prop has been specified. ' + 'Vertical lists must specify a number for height. ' + ("\"" + (height === null ? 'null' : typeof height) + "\" was specified."));
}
}
};
var DEFAULT_ESTIMATED_ITEM_SIZE$1 = 50;
var getItemMetadata$1 = function getItemMetadata(props, index, instanceProps) {
var _ref = props,
itemSize = _ref.itemSize;
var itemMetadataMap = instanceProps.itemMetadataMap,
lastMeasuredIndex = instanceProps.lastMeasuredIndex;
if (index > lastMeasuredIndex) {
var offset = 0;
if (lastMeasuredIndex >= 0) {
var itemMetadata = itemMetadataMap[lastMeasuredIndex];
offset = itemMetadata.offset + itemMetadata.size;
}
for (var i = lastMeasuredIndex + 1; i <= index; i++) {
var size = itemSize(i);
itemMetadataMap[i] = {
offset: offset,
size: size
};
offset += size;
}
instanceProps.lastMeasuredIndex = index;
}
return itemMetadataMap[index];
};
var findNearestItem$1 = function findNearestItem(props, instanceProps, offset) {
var itemMetadataMap = instanceProps.itemMetadataMap,
lastMeasuredIndex = instanceProps.lastMeasuredIndex;
var lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0;
if (lastMeasuredItemOffset >= offset) {
// If we've already measured items within this range just use a binary search as it's faster.
return findNearestItemBinarySearch$1(props, instanceProps, lastMeasuredIndex, 0, offset);
} else {
// If we haven't yet measured this high, fallback to an exponential search with an inner binary search.
// The exponential search avoids pre-computing sizes for the full set of items as a binary search would.
// The overall complexity for this approach is O(log n).
return findNearestItemExponentialSearch$1(props, instanceProps, Math.max(0, lastMeasuredIndex), offset);
}
};
var findNearestItemBinarySearch$1 = function findNearestItemBinarySearch(props, instanceProps, high, low, offset) {
while (low <= high) {
var middle = low + Math.floor((high - low) / 2);
var currentOffset = getItemMetadata$1(props, middle, instanceProps).offset;
if (currentOffset === offset) {
return middle;
} else if (currentOffset < offset) {
low = middle + 1;
} else if (currentOffset > offset) {
high = middle - 1;
}
}
if (low > 0) {
return low - 1;
} else {
return 0;
}
};
var findNearestItemExponentialSearch$1 = function findNearestItemExponentialSearch(props, instanceProps, index, offset) {
var itemCount = props.itemCount;
var interval = 1;
while (index < itemCount && getItemMetadata$1(props, index, instanceProps).offset < offset) {
index += interval;
interval *= 2;
}
return findNearestItemBinarySearch$1(props, instanceProps, Math.min(index, itemCount - 1), Math.floor(index / 2), offset);
};
var getEstimatedTotalSize = function getEstimatedTotalSize(_ref2, _ref3) {
var itemCount = _ref2.itemCount;
var itemMetadataMap = _ref3.itemMetadataMap,
estimatedItemSize = _ref3.estimatedItemSize,
lastMeasuredIndex = _ref3.lastMeasuredIndex;
var totalSizeOfMeasuredItems = 0; // Edge case check for when the number of items decreases while a scroll is in progress.
// https://github.com/bvaughn/react-window/pull/138
if (lastMeasuredIndex >= itemCount) {
lastMeasuredIndex = itemCount - 1;
}
if (lastMeasuredIndex >= 0) {
var itemMetadata = itemMetadataMap[lastMeasuredIndex];
totalSizeOfMeasuredItems = itemMetadata.offset + itemMetadata.size;
}
var numUnmeasuredItems = itemCount - lastMeasuredIndex - 1;
var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedItemSize;
return totalSizeOfMeasuredItems + totalSizeOfUnmeasuredItems;
};
var VariableSizeList =
/*#__PURE__*/
createListComponent({
getItemOffset: function getItemOffset(props, index, instanceProps) {
return getItemMetadata$1(props, index, instanceProps).offset;
},
getItemSize: function getItemSize(props, index, instanceProps) {
return instanceProps.itemMetadataMap[index].size;
},
getEstimatedTotalSize: getEstimatedTotalSize,
getOffsetForIndexAndAlignment: function getOffsetForIndexAndAlignment(props, index, align, scrollOffset, instanceProps) {
var direction = props.direction,
height = props.height,
layout = props.layout,
width = props.width; // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var size = isHorizontal ? width : height;
var itemMetadata = getItemMetadata$1(props, index, instanceProps); // Get estimated total size after ItemMetadata is computed,
// To ensure it reflects actual measurements instead of just estimates.
var estimatedTotalSize = getEstimatedTotalSize(props, instanceProps);
var maxOffset = Math.max(0, Math.min(estimatedTotalSize - size, itemMetadata.offset));
var minOffset = Math.max(0, itemMetadata.offset - size + itemMetadata.size);
if (align === 'smart') {
if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) {
align = 'auto';
} else {
align = 'center';
}
}
switch (align) {
case 'start':
return maxOffset;
case 'end':
return minOffset;
case 'center':
return Math.round(minOffset + (maxOffset - minOffset) / 2);
case 'auto':
default:
if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {
return scrollOffset;
} else if (scrollOffset < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getStartIndexForOffset: function getStartIndexForOffset(props, offset, instanceProps) {
return findNearestItem$1(props, instanceProps, offset);
},
getStopIndexForStartIndex: function getStopIndexForStartIndex(props, startIndex, scrollOffset, instanceProps) {
var direction = props.direction,
height = props.height,
itemCount = props.itemCount,
layout = props.layout,
width = props.width; // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var size = isHorizontal ? width : height;
var itemMetadata = getItemMetadata$1(props, startIndex, instanceProps);
var maxOffset = scrollOffset + size;
var offset = itemMetadata.offset + itemMetadata.size;
var stopIndex = startIndex;
while (stopIndex < itemCount - 1 && offset < maxOffset) {
stopIndex++;
offset += getItemMetadata$1(props, stopIndex, instanceProps).size;
}
return stopIndex;
},
initInstanceProps: function initInstanceProps(props, instance) {
var _ref4 = props,
estimatedItemSize = _ref4.estimatedItemSize;
var instanceProps = {
itemMetadataMap: {},
estimatedItemSize: estimatedItemSize || DEFAULT_ESTIMATED_ITEM_SIZE$1,
lastMeasuredIndex: -1
};
instance.resetAfterIndex = function (index, shouldForceUpdate) {
if (shouldForceUpdate === void 0) {
shouldForceUpdate = true;
}
instanceProps.lastMeasuredIndex = Math.min(instanceProps.lastMeasuredIndex, index - 1); // We could potentially optimize further by only evicting styles after this index,
// But since styles are only cached while scrolling is in progress-
// It seems an unnecessary optimization.
// It's unlikely that resetAfterIndex() will be called while a user is scrolling.
instance._getItemStyleCache(-1);
if (shouldForceUpdate) {
instance.forceUpdate();
}
};
return instanceProps;
},
shouldResetStyleCacheOnItemSizeChange: false,
validateProps: function validateProps(_ref5) {
var itemSize = _ref5.itemSize;
if (process.env.NODE_ENV !== 'production') {
if (typeof itemSize !== 'function') {
throw Error('An invalid "itemSize" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (itemSize === null ? 'null' : typeof itemSize) + "\" was specified."));
}
}
}
});
var FixedSizeGrid =
/*#__PURE__*/
createGridComponent({
getColumnOffset: function getColumnOffset(_ref, index) {
var columnWidth = _ref.columnWidth;
return index * columnWidth;
},
getColumnWidth: function getColumnWidth(_ref2, index) {
var columnWidth = _ref2.columnWidth;
return columnWidth;
},
getRowOffset: function getRowOffset(_ref3, index) {
var rowHeight = _ref3.rowHeight;
return index * rowHeight;
},
getRowHeight: function getRowHeight(_ref4, index) {
var rowHeight = _ref4.rowHeight;
return rowHeight;
},
getEstimatedTotalHeight: function getEstimatedTotalHeight(_ref5) {
var rowCount = _ref5.rowCount,
rowHeight = _ref5.rowHeight;
return rowHeight * rowCount;
},
getEstimatedTotalWidth: function getEstimatedTotalWidth(_ref6) {
var columnCount = _ref6.columnCount,
columnWidth = _ref6.columnWidth;
return columnWidth * columnCount;
},
getOffsetForColumnAndAlignment: function getOffsetForColumnAndAlignment(_ref7, columnIndex, align, scrollLeft, instanceProps, scrollbarSize) {
var columnCount = _ref7.columnCount,
columnWidth = _ref7.columnWidth,
width = _ref7.width;
var lastColumnOffset = Math.max(0, columnCount * columnWidth - width);
var maxOffset = Math.min(lastColumnOffset, columnIndex * columnWidth);
var minOffset = Math.max(0, columnIndex * columnWidth - width + scrollbarSize + columnWidth);
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.
var 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: function getOffsetForRowAndAlignment(_ref8, rowIndex, align, scrollTop, instanceProps, scrollbarSize) {
var rowHeight = _ref8.rowHeight,
height = _ref8.height,
rowCount = _ref8.rowCount;
var lastRowOffset = Math.max(0, rowCount * rowHeight - height);
var maxOffset = Math.min(lastRowOffset, rowIndex * rowHeight);
var minOffset = Math.max(0, rowIndex * rowHeight - height + scrollbarSize + rowHeight);
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.
var 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: function getColumnStartIndexForOffset(_ref9, scrollLeft) {
var columnWidth = _ref9.columnWidth,
columnCount = _ref9.columnCount;
return Math.max(0, Math.min(columnCount - 1, Math.floor(scrollLeft / columnWidth)));
},
getColumnStopIndexForStartIndex: function getColumnStopIndexForStartIndex(_ref10, startIndex, scrollLeft) {
var columnWidth = _ref10.columnWidth,
columnCount = _ref10.columnCount,
width = _ref10.width;
var left = startIndex * columnWidth;
var numVisibleColumns = Math.ceil((width + scrollLeft - left) / columnWidth);
return Math.max(0, Math.min(columnCount - 1, startIndex + numVisibleColumns - 1 // -1 is because stop index is inclusive
));
},
getRowStartIndexForOffset: function getRowStartIndexForOffset(_ref11, scrollTop) {
var rowHeight = _ref11.rowHeight,
rowCount = _ref11.rowCount;
return Math.max(0, Math.min(rowCount - 1, Math.floor(scrollTop / rowHeight)));
},
getRowStopIndexForStartIndex: function getRowStopIndexForStartIndex(_ref12, startIndex, scrollTop) {
var rowHeight = _ref12.rowHeight,
rowCount = _ref12.rowCount,
height = _ref12.height;
var top = startIndex * rowHeight;
var numVisibleRows = Math.ceil((height + scrollTop - top) / rowHeight);
return Math.max(0, Math.min(rowCount - 1, startIndex + numVisibleRows - 1 // -1 is because stop index is inclusive
));
},
initInstanceProps: function initInstanceProps(props) {// Noop
},
shouldResetStyleCacheOnItemSizeChange: true,
validateProps: function validateProps(_ref13) {
var columnWidth = _ref13.columnWidth,
rowHeight = _ref13.rowHeight;
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."));
}
}
}
});
var FixedSizeList =
/*#__PURE__*/
createListComponent({
getItemOffset: function getItemOffset(_ref, index) {
var itemSize = _ref.itemSize;
return index * itemSize;
},
getItemSize: function getItemSize(_ref2, index) {
var itemSize = _ref2.itemSize;
return itemSize;
},
getEstimatedTotalSize: function getEstimatedTotalSize(_ref3) {
var itemCount = _ref3.itemCount,
itemSize = _ref3.itemSize;
return itemSize * itemCount;
},
getOffsetForIndexAndAlignment: function getOffsetForIndexAndAlignment(_ref4, index, align, scrollOffset) {
var direction = _ref4.direction,
height = _ref4.height,
itemCount = _ref4.itemCount,
itemSize = _ref4.itemSize,
layout = _ref4.layout,
width = _ref4.width;
// TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var size = isHorizontal ? width : height;
var lastItemOffset = Math.max(0, itemCount * itemSize - size);
var maxOffset = Math.min(lastItemOffset, index * itemSize);
var minOffset = Math.max(0, index * itemSize - size + itemSize);
if (align === 'smart') {
if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) {
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.
var middleOffset = Math.round(minOffset + (maxOffset - minOffset) / 2);
if (middleOffset < Math.ceil(size / 2)) {
return 0; // near the beginning
} else if (middleOffset > lastItemOffset + Math.floor(size / 2)) {
return lastItemOffset; // near the end
} else {
return middleOffset;
}
}
case 'auto':
default:
if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {
return scrollOffset;
} else if (scrollOffset < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getStartIndexForOffset: function getStartIndexForOffset(_ref5, offset) {
var itemCount = _ref5.itemCount,
itemSize = _ref5.itemSize;
return Math.max(0, Math.min(itemCount - 1, Math.floor(offset / itemSize)));
},
getStopIndexForStartIndex: function getStopIndexForStartIndex(_ref6, startIndex, scrollOffset) {
var direction = _ref6.direction,
height = _ref6.height,
itemCount = _ref6.itemCount,
itemSize = _ref6.itemSize,
layout = _ref6.layout,
width = _ref6.width;
// TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var offset = startIndex * itemSize;
var size = isHorizontal ? width : height;
var numVisibleItems = Math.ceil((size + scrollOffset - offset) / itemSize);
return Math.max(0, Math.min(itemCount - 1, startIndex + numVisibleItems - 1 // -1 is because stop index is inclusive
));
},
initInstanceProps: function initInstanceProps(props) {// Noop
},
shouldResetStyleCacheOnItemSizeChange: true,
validateProps: function validateProps(_ref7) {
var itemSize = _ref7.itemSize;
if (process.env.NODE_ENV !== 'production') {
if (typeof itemSize !== 'number') {
throw Error('An invalid "itemSize" prop has been specified. ' + 'Value should be a number. ' + ("\"" + (itemSize === null ? 'null' : typeof itemSize) + "\" was specified."));
}
}
}
});
// Pulled from react-compat
// https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349
function shallowDiffers(prev, next) {
for (var attribute in prev) {
if (!(attribute in next)) {
return true;
}
}
for (var _attribute in next) {
if (prev[_attribute] !== next[_attribute]) {
return true;
}
}
return false;
}
// It knows to compare individual style props and ignore the wrapper object.
// See https://reactjs.org/docs/react-api.html#reactmemo
function areEqual(prevProps, nextProps) {
var prevStyle = prevProps.style,
prevRest = _objectWithoutPropertiesLoose(prevProps, ["style"]);
var nextStyle = nextProps.style,
nextRest = _objectWithoutPropertiesLoose(nextProps, ["style"]);
return !shallowDiffers(prevStyle, nextStyle) && !shallowDiffers(prevRest, nextRest);
}
// It knows to compare individual style props and ignore the wrapper object.
// See https://reactjs.org/docs/react-component.html#shouldcomponentupdate
function shouldComponentUpdate(nextProps, nextState) {
return !areEqual(this.props, nextProps) || shallowDiffers(this.state, nextState);
}
exports.VariableSizeGrid = VariableSizeGrid;
exports.VariableSizeList = VariableSizeList;
exports.FixedSizeGrid = FixedSizeGrid;
exports.FixedSizeList = FixedSizeList;
exports.areEqual = areEqual;
exports.shouldComponentUpdate = shouldComponentUpdate;
//# sourceMappingURL=index.cjs.js.map
| 38.475962 | 361 | 0.65927 |
Penetration-Testing-with-Shellcode | /**
* 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 function loadChunk(filename: string): Promise<mixed> {
return __turbopack_load__(filename);
}
| 22.692308 | 66 | 0.703583 |
owtf | #!/usr/bin/env node
'use strict';
const {
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
rmdirSync,
} = require('fs');
const {join} = require('path');
const http = require('http');
const DEPENDENCIES = [
['scheduler/umd/scheduler.development.js', 'scheduler.js'],
['react/umd/react.development.js', 'react.js'],
['react-dom/umd/react-dom.development.js', 'react-dom.js'],
];
const BUILD_DIRECTORY = '../../../build/oss-experimental/';
const DEPENDENCIES_DIRECTORY = 'dependencies';
function initDependencies() {
if (existsSync(DEPENDENCIES_DIRECTORY)) {
rmdirSync(DEPENDENCIES_DIRECTORY, {recursive: true});
}
mkdirSync(DEPENDENCIES_DIRECTORY);
DEPENDENCIES.forEach(([from, to]) => {
const fromPath = join(__dirname, BUILD_DIRECTORY, from);
const toPath = join(__dirname, DEPENDENCIES_DIRECTORY, to);
console.log(`Copying ${fromPath} => ${toPath}`);
copyFileSync(fromPath, toPath);
});
}
function initServer() {
const host = 'localhost';
const port = 8000;
const requestListener = function (request, response) {
let contents;
switch (request.url) {
case '/react.js':
case '/react-dom.js':
case '/scheduler.js':
response.setHeader('Content-Type', 'text/javascript');
response.writeHead(200);
contents = readFileSync(
join(__dirname, DEPENDENCIES_DIRECTORY, request.url)
);
response.end(contents);
break;
case '/app.js':
response.setHeader('Content-Type', 'text/javascript');
response.writeHead(200);
contents = readFileSync(join(__dirname, 'app.js'));
response.end(contents);
break;
case '/index.html':
default:
response.setHeader('Content-Type', 'text/html');
response.writeHead(200);
contents = readFileSync(join(__dirname, 'index.html'));
response.end(contents);
break;
}
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
}
initDependencies();
initServer();
| 25.924051 | 63 | 0.633114 |
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
*/
describe('Fast Refresh', () => {
let React;
let ReactFreshRuntime;
let act;
let babel;
let container;
let exportsObj;
let freshPlugin;
let legacyRender;
let store;
let withErrorsOrWarningsIgnored;
afterEach(() => {
jest.resetModules();
});
beforeEach(() => {
exportsObj = undefined;
container = document.createElement('div');
babel = require('@babel/core');
freshPlugin = require('react-refresh/babel');
store = global.store;
React = require('react');
ReactFreshRuntime = require('react-refresh/runtime');
ReactFreshRuntime.injectIntoGlobalHook(global);
const utils = require('./utils');
act = utils.act;
legacyRender = utils.legacyRender;
withErrorsOrWarningsIgnored = utils.withErrorsOrWarningsIgnored;
});
function execute(source) {
const compiled = babel.transform(source, {
babelrc: false,
presets: ['@babel/react'],
plugins: [
[freshPlugin, {skipEnvCheck: true}],
'@babel/plugin-transform-modules-commonjs',
'@babel/plugin-transform-destructuring',
].filter(Boolean),
}).code;
exportsObj = {};
// eslint-disable-next-line no-new-func
new Function(
'global',
'React',
'exports',
'$RefreshReg$',
'$RefreshSig$',
compiled,
)(global, React, exportsObj, $RefreshReg$, $RefreshSig$);
// Module systems will register exports as a fallback.
// This is useful for cases when e.g. a class is exported,
// and we don't want to propagate the update beyond this module.
$RefreshReg$(exportsObj.default, 'exports.default');
return exportsObj.default;
}
function render(source) {
const Component = execute(source);
act(() => {
legacyRender(<Component />, container);
});
// Module initialization shouldn't be counted as a hot update.
expect(ReactFreshRuntime.performReactRefresh()).toBe(null);
}
function patch(source) {
const prevExports = exportsObj;
execute(source);
const nextExports = exportsObj;
// Check if exported families have changed.
// (In a real module system we'd do this for *all* exports.)
// For example, this can happen if you convert a class to a function.
// Or if you wrap something in a HOC.
const didExportsChange =
ReactFreshRuntime.getFamilyByType(prevExports.default) !==
ReactFreshRuntime.getFamilyByType(nextExports.default);
if (didExportsChange) {
// In a real module system, we would propagate such updates upwards,
// and re-execute modules that imported this one. (Just like if we edited them.)
// This makes adding/removing/renaming exports re-render references to them.
// Here, we'll just force a re-render using the newer type to emulate this.
const NextComponent = nextExports.default;
act(() => {
legacyRender(<NextComponent />, container);
});
}
act(() => {
const result = ReactFreshRuntime.performReactRefresh();
if (!didExportsChange) {
// Normally we expect that some components got updated in our tests.
expect(result).not.toBe(null);
} else {
// However, we have tests where we convert functions to classes,
// and in those cases it's expected nothing would get updated.
// (Instead, the export change branch above would take care of it.)
}
});
expect(ReactFreshRuntime._getMountedRootCount()).toBe(1);
}
function $RefreshReg$(type, id) {
ReactFreshRuntime.register(type, id);
}
function $RefreshSig$() {
return ReactFreshRuntime.createSignatureFunctionForTransform();
}
// @reactVersion >= 16.9
it('should not break the DevTools store', () => {
render(`
function Parent() {
return <Child key="A" />;
};
function Child() {
return <div />;
};
export default Parent;
`);
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="A">
`);
let element = container.firstChild;
expect(container.firstChild).not.toBe(null);
patch(`
function Parent() {
return <Child key="A" />;
};
function Child() {
return <div />;
};
export default Parent;
`);
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="A">
`);
// State is preserved; this verifies that Fast Refresh is wired up.
expect(container.firstChild).toBe(element);
element = container.firstChild;
patch(`
function Parent() {
return <Child key="B" />;
};
function Child() {
return <div />;
};
export default Parent;
`);
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="B">
`);
// State is reset because hooks changed.
expect(container.firstChild).not.toBe(element);
});
// @reactVersion >= 16.9
it('should not break when there are warnings in between patching', () => {
withErrorsOrWarningsIgnored(['Expected:'], () => {
render(`
const {useState} = React;
export default function Component() {
const [state, setState] = useState(1);
console.warn("Expected: warning during render");
return null;
}
`);
});
expect(store).toMatchInlineSnapshot(`
✕ 0, ⚠ 1
[root]
<Component> ⚠
`);
withErrorsOrWarningsIgnored(['Expected:'], () => {
patch(`
const {useEffect, useState} = React;
export default function Component() {
const [state, setState] = useState(1);
console.warn("Expected: warning during render");
return null;
}
`);
});
expect(store).toMatchInlineSnapshot(`
✕ 0, ⚠ 2
[root]
<Component> ⚠
`);
withErrorsOrWarningsIgnored(['Expected:'], () => {
patch(`
const {useEffect, useState} = React;
export default function Component() {
const [state, setState] = useState(1);
useEffect(() => {
console.error("Expected: error during effect");
});
console.warn("Expected: warning during render");
return null;
}
`);
});
expect(store).toMatchInlineSnapshot(`
✕ 1, ⚠ 1
[root]
<Component> ✕⚠
`);
withErrorsOrWarningsIgnored(['Expected:'], () => {
patch(`
const {useEffect, useState} = React;
export default function Component() {
const [state, setState] = useState(1);
console.warn("Expected: warning during render");
return null;
}
`);
});
expect(store).toMatchInlineSnapshot(`
✕ 0, ⚠ 1
[root]
<Component> ⚠
`);
});
// TODO (bvaughn) Write a test that checks in between the steps of patch
});
| 25.605263 | 86 | 0.602035 |
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.
*
* @flow
*/
throw new Error(
'The React Server cannot be used outside a react-server environment. ' +
'You must configure Node.js using the `--conditions react-server` flag.',
);
| 26 | 77 | 0.700265 |
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.
*
* @emails react-core
*/
'use strict';
let PropTypes;
let React;
let ReactDOM;
let ReactDOMClient;
describe('ReactES6Class', () => {
let container;
let root;
const freeze = function (expectation) {
Object.freeze(expectation);
return expectation;
};
let Inner;
let attachedListener = null;
let renderedName = null;
beforeEach(() => {
PropTypes = require('prop-types');
React = require('react');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
container = document.createElement('div');
root = ReactDOMClient.createRoot(container);
attachedListener = null;
renderedName = null;
Inner = class extends React.Component {
getName() {
return this.props.name;
}
render() {
attachedListener = this.props.onClick;
renderedName = this.props.name;
return <div className={this.props.name} />;
}
};
});
function test(element, expectedTag, expectedClassName) {
ReactDOM.flushSync(() => root.render(element));
expect(container.firstChild).not.toBeNull();
expect(container.firstChild.tagName).toBe(expectedTag);
expect(container.firstChild.className).toBe(expectedClassName);
}
it('preserves the name of the class for use in error messages', () => {
class Foo extends React.Component {}
expect(Foo.name).toBe('Foo');
});
it('throws if no render function is defined', () => {
class Foo extends React.Component {}
expect(() => {
expect(() => ReactDOM.flushSync(() => root.render(<Foo />))).toThrow();
}).toErrorDev([
// A failed component renders four times in DEV in concurrent mode
'Warning: Foo(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render`.',
'Warning: Foo(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render`.',
'Warning: Foo(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render`.',
'Warning: Foo(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render`.',
]);
});
it('renders a simple stateless component with prop', () => {
class Foo extends React.Component {
render() {
return <Inner name={this.props.bar} />;
}
}
test(<Foo bar="foo" />, 'DIV', 'foo');
test(<Foo bar="bar" />, 'DIV', 'bar');
});
it('renders based on state using initial values in this.props', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {bar: this.props.initialValue};
}
render() {
return <span className={this.state.bar} />;
}
}
test(<Foo initialValue="foo" />, 'SPAN', 'foo');
});
it('renders based on state using props in the constructor', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {bar: props.initialValue};
}
changeState() {
this.setState({bar: 'bar'});
}
render() {
if (this.state.bar === 'foo') {
return <div className="foo" />;
}
return <span className={this.state.bar} />;
}
}
const ref = React.createRef();
test(<Foo initialValue="foo" ref={ref} />, 'DIV', 'foo');
ReactDOM.flushSync(() => ref.current.changeState());
test(<Foo />, 'SPAN', 'bar');
});
it('sets initial state with value returned by static getDerivedStateFromProps', () => {
class Foo extends React.Component {
state = {};
static getDerivedStateFromProps(nextProps, prevState) {
return {
foo: nextProps.foo,
bar: 'bar',
};
}
render() {
return <div className={`${this.state.foo} ${this.state.bar}`} />;
}
}
test(<Foo foo="foo" />, 'DIV', 'foo bar');
});
it('warns if getDerivedStateFromProps is not static', () => {
class Foo extends React.Component {
getDerivedStateFromProps() {
return {};
}
render() {
return <div />;
}
}
expect(() => {
ReactDOM.flushSync(() => root.render(<Foo foo="foo" />));
}).toErrorDev(
'Foo: getDerivedStateFromProps() is defined as an instance method ' +
'and will be ignored. Instead, declare it as a static method.',
);
});
it('warns if getDerivedStateFromError is not static', () => {
class Foo extends React.Component {
getDerivedStateFromError() {
return {};
}
render() {
return <div />;
}
}
expect(() => {
ReactDOM.flushSync(() => root.render(<Foo foo="foo" />));
}).toErrorDev(
'Foo: getDerivedStateFromError() is defined as an instance method ' +
'and will be ignored. Instead, declare it as a static method.',
);
});
it('warns if getSnapshotBeforeUpdate is static', () => {
class Foo extends React.Component {
static getSnapshotBeforeUpdate() {}
render() {
return <div />;
}
}
expect(() => {
ReactDOM.flushSync(() => root.render(<Foo foo="foo" />));
}).toErrorDev(
'Foo: getSnapshotBeforeUpdate() is defined as a static method ' +
'and will be ignored. Instead, declare it as an instance method.',
);
});
it('warns if state not initialized before static getDerivedStateFromProps', () => {
class Foo extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
return {
foo: nextProps.foo,
bar: 'bar',
};
}
render() {
return <div className={`${this.state.foo} ${this.state.bar}`} />;
}
}
expect(() => {
ReactDOM.flushSync(() => root.render(<Foo foo="foo" />));
}).toErrorDev(
'`Foo` uses `getDerivedStateFromProps` but its initial state is ' +
'undefined. This is not recommended. Instead, define the initial state by ' +
'assigning an object to `this.state` in the constructor of `Foo`. ' +
'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.',
);
});
it('updates initial state with values returned by static getDerivedStateFromProps', () => {
class Foo extends React.Component {
state = {
foo: 'foo',
bar: 'bar',
};
static getDerivedStateFromProps(nextProps, prevState) {
return {
foo: `not-${prevState.foo}`,
};
}
render() {
return <div className={`${this.state.foo} ${this.state.bar}`} />;
}
}
test(<Foo />, 'DIV', 'not-foo bar');
});
it('renders updated state with values returned by static getDerivedStateFromProps', () => {
class Foo extends React.Component {
state = {
value: 'initial',
};
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.update) {
return {
value: 'updated',
};
}
return null;
}
render() {
return <div className={this.state.value} />;
}
}
test(<Foo update={false} />, 'DIV', 'initial');
test(<Foo update={true} />, 'DIV', 'updated');
});
if (!require('shared/ReactFeatureFlags').disableLegacyContext) {
it('renders based on context in the constructor', () => {
class Foo extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {tag: context.tag, className: this.context.className};
}
render() {
const Tag = this.state.tag;
return <Tag className={this.state.className} />;
}
}
Foo.contextTypes = {
tag: PropTypes.string,
className: PropTypes.string,
};
class Outer extends React.Component {
getChildContext() {
return {tag: 'span', className: 'foo'};
}
render() {
return <Foo />;
}
}
Outer.childContextTypes = {
tag: PropTypes.string,
className: PropTypes.string,
};
test(<Outer />, 'SPAN', 'foo');
});
}
it('renders only once when setting state in componentWillMount', () => {
let renderCount = 0;
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {bar: props.initialValue};
}
UNSAFE_componentWillMount() {
this.setState({bar: 'bar'});
}
render() {
renderCount++;
return <span className={this.state.bar} />;
}
}
test(<Foo initialValue="foo" />, 'SPAN', 'bar');
expect(renderCount).toBe(1);
});
it('should warn with non-object in the initial state property', () => {
[['an array'], 'a string', 1234].forEach(function (state) {
class Foo extends React.Component {
constructor() {
super();
this.state = state;
}
render() {
return <span />;
}
}
expect(() => test(<Foo />, 'SPAN', '')).toErrorDev(
'Foo.state: must be set to an object or null',
);
});
});
it('should render with null in the initial state property', () => {
class Foo extends React.Component {
constructor() {
super();
this.state = null;
}
render() {
return <span />;
}
}
test(<Foo />, 'SPAN', '');
});
it('setState through an event handler', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {bar: props.initialValue};
}
handleClick() {
this.setState({bar: 'bar'});
}
render() {
return (
<Inner name={this.state.bar} onClick={this.handleClick.bind(this)} />
);
}
}
test(<Foo initialValue="foo" />, 'DIV', 'foo');
ReactDOM.flushSync(() => attachedListener());
expect(renderedName).toBe('bar');
});
it('should not implicitly bind event handlers', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {bar: props.initialValue};
}
handleClick() {
this.setState({bar: 'bar'});
}
render() {
return <Inner name={this.state.bar} onClick={this.handleClick} />;
}
}
test(<Foo initialValue="foo" />, 'DIV', 'foo');
expect(attachedListener).toThrow();
});
it('renders using forceUpdate even when there is no state', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.mutativeValue = props.initialValue;
}
handleClick() {
this.mutativeValue = 'bar';
this.forceUpdate();
}
render() {
return (
<Inner
name={this.mutativeValue}
onClick={this.handleClick.bind(this)}
/>
);
}
}
test(<Foo initialValue="foo" />, 'DIV', 'foo');
ReactDOM.flushSync(() => attachedListener());
expect(renderedName).toBe('bar');
});
it('will call all the normal life cycle methods', () => {
let lifeCycles = [];
class Foo extends React.Component {
constructor() {
super();
this.state = {};
}
UNSAFE_componentWillMount() {
lifeCycles.push('will-mount');
}
componentDidMount() {
lifeCycles.push('did-mount');
}
UNSAFE_componentWillReceiveProps(nextProps) {
lifeCycles.push('receive-props', nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
lifeCycles.push('should-update', nextProps, nextState);
return true;
}
UNSAFE_componentWillUpdate(nextProps, nextState) {
lifeCycles.push('will-update', nextProps, nextState);
}
componentDidUpdate(prevProps, prevState) {
lifeCycles.push('did-update', prevProps, prevState);
}
componentWillUnmount() {
lifeCycles.push('will-unmount');
}
render() {
return <span className={this.props.value} />;
}
}
test(<Foo value="foo" />, 'SPAN', 'foo');
expect(lifeCycles).toEqual(['will-mount', 'did-mount']);
lifeCycles = []; // reset
test(<Foo value="bar" />, 'SPAN', 'bar');
// prettier-ignore
expect(lifeCycles).toEqual([
'receive-props', freeze({value: 'bar'}),
'should-update', freeze({value: 'bar'}), {},
'will-update', freeze({value: 'bar'}), {},
'did-update', freeze({value: 'foo'}), {},
]);
lifeCycles = []; // reset
ReactDOM.flushSync(() => root.unmount());
expect(lifeCycles).toEqual(['will-unmount']);
});
if (!require('shared/ReactFeatureFlags').disableLegacyContext) {
it('warns when classic properties are defined on the instance, but does not invoke them.', () => {
let getDefaultPropsWasCalled = false;
let getInitialStateWasCalled = false;
class Foo extends React.Component {
constructor() {
super();
this.contextTypes = {};
this.contextType = {};
this.propTypes = {};
}
getInitialState() {
getInitialStateWasCalled = true;
return {};
}
getDefaultProps() {
getDefaultPropsWasCalled = true;
return {};
}
render() {
return <span className="foo" />;
}
}
expect(() => test(<Foo />, 'SPAN', 'foo')).toErrorDev([
'getInitialState was defined on Foo, a plain JavaScript class.',
'getDefaultProps was defined on Foo, a plain JavaScript class.',
'propTypes was defined as an instance property on Foo.',
'contextType was defined as an instance property on Foo.',
'contextTypes was defined as an instance property on Foo.',
]);
expect(getInitialStateWasCalled).toBe(false);
expect(getDefaultPropsWasCalled).toBe(false);
});
}
it('does not warn about getInitialState() on class components if state is also defined.', () => {
class Foo extends React.Component {
state = this.getInitialState();
getInitialState() {
return {};
}
render() {
return <span className="foo" />;
}
}
test(<Foo />, 'SPAN', 'foo');
});
it('should warn when misspelling shouldComponentUpdate', () => {
class NamedComponent extends React.Component {
componentShouldUpdate() {
return false;
}
render() {
return <span className="foo" />;
}
}
expect(() => test(<NamedComponent />, 'SPAN', 'foo')).toErrorDev(
'Warning: ' +
'NamedComponent has a method called componentShouldUpdate(). Did you ' +
'mean shouldComponentUpdate()? The name is phrased as a question ' +
'because the function is expected to return a value.',
);
});
it('should warn when misspelling componentWillReceiveProps', () => {
class NamedComponent extends React.Component {
componentWillRecieveProps() {
return false;
}
render() {
return <span className="foo" />;
}
}
expect(() => test(<NamedComponent />, 'SPAN', 'foo')).toErrorDev(
'Warning: ' +
'NamedComponent has a method called componentWillRecieveProps(). Did ' +
'you mean componentWillReceiveProps()?',
);
});
it('should warn when misspelling UNSAFE_componentWillReceiveProps', () => {
class NamedComponent extends React.Component {
UNSAFE_componentWillRecieveProps() {
return false;
}
render() {
return <span className="foo" />;
}
}
expect(() => test(<NamedComponent />, 'SPAN', 'foo')).toErrorDev(
'Warning: ' +
'NamedComponent has a method called UNSAFE_componentWillRecieveProps(). ' +
'Did you mean UNSAFE_componentWillReceiveProps()?',
);
});
it('should throw AND warn when trying to access classic APIs', () => {
const ref = React.createRef();
test(<Inner name="foo" ref={ref} />, 'DIV', 'foo');
expect(() =>
expect(() => ref.current.replaceState({})).toThrow(),
).toWarnDev(
'replaceState(...) is deprecated in plain JavaScript React classes',
{withoutStack: true},
);
expect(() => expect(() => ref.current.isMounted()).toThrow()).toWarnDev(
'isMounted(...) is deprecated in plain JavaScript React classes',
{withoutStack: true},
);
});
if (!require('shared/ReactFeatureFlags').disableLegacyContext) {
it('supports this.context passed via getChildContext', () => {
class Bar extends React.Component {
render() {
return <div className={this.context.bar} />;
}
}
Bar.contextTypes = {bar: PropTypes.string};
class Foo extends React.Component {
getChildContext() {
return {bar: 'bar-through-context'};
}
render() {
return <Bar />;
}
}
Foo.childContextTypes = {bar: PropTypes.string};
test(<Foo />, 'DIV', 'bar-through-context');
});
}
it('supports string refs', () => {
class Foo extends React.Component {
render() {
return <Inner name="foo" ref="inner" />;
}
}
const ref = React.createRef();
expect(() => {
test(<Foo ref={ref} />, 'DIV', 'foo');
}).toErrorDev([
'Warning: Component "Foo" contains the string ref "inner". ' +
'Support for string refs will be removed in a future major release. ' +
'We recommend using useRef() or createRef() instead. ' +
'Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref\n' +
' in Foo (at **)',
]);
expect(ref.current.refs.inner.getName()).toBe('foo');
});
it('supports drilling through to the DOM using findDOMNode', () => {
const ref = React.createRef();
test(<Inner name="foo" ref={ref} />, 'DIV', 'foo');
const node = ReactDOM.findDOMNode(ref.current);
expect(node).toBe(container.firstChild);
});
});
| 29.328926 | 102 | 0.571234 |
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.
*/
'use strict';
export default function (babel, opts = {}) {
if (typeof babel.env === 'function') {
// Only available in Babel 7.
const env = babel.env();
if (env !== 'development' && !opts.skipEnvCheck) {
throw new Error(
'React Refresh Babel transform should only be enabled in development environment. ' +
'Instead, the environment is: "' +
env +
'". If you want to override this check, pass {skipEnvCheck: true} as plugin options.',
);
}
}
const {types: t} = babel;
const refreshReg = t.identifier(opts.refreshReg || '$RefreshReg$');
const refreshSig = t.identifier(opts.refreshSig || '$RefreshSig$');
const registrationsByProgramPath = new Map();
function createRegistration(programPath, persistentID) {
const handle = programPath.scope.generateUidIdentifier('c');
if (!registrationsByProgramPath.has(programPath)) {
registrationsByProgramPath.set(programPath, []);
}
const registrations = registrationsByProgramPath.get(programPath);
registrations.push({
handle,
persistentID,
});
return handle;
}
function isComponentishName(name) {
return typeof name === 'string' && name[0] >= 'A' && name[0] <= 'Z';
}
function findInnerComponents(inferredName, path, callback) {
const node = path.node;
switch (node.type) {
case 'Identifier': {
if (!isComponentishName(node.name)) {
return false;
}
// export default hoc(Foo)
// const X = hoc(Foo)
callback(inferredName, node, null);
return true;
}
case 'FunctionDeclaration': {
// function Foo() {}
// export function Foo() {}
// export default function Foo() {}
callback(inferredName, node.id, null);
return true;
}
case 'ArrowFunctionExpression': {
if (node.body.type === 'ArrowFunctionExpression') {
return false;
}
// let Foo = () => {}
// export default hoc1(hoc2(() => {}))
callback(inferredName, node, path);
return true;
}
case 'FunctionExpression': {
// let Foo = function() {}
// const Foo = hoc1(forwardRef(function renderFoo() {}))
// export default memo(function() {})
callback(inferredName, node, path);
return true;
}
case 'CallExpression': {
const argsPath = path.get('arguments');
if (argsPath === undefined || argsPath.length === 0) {
return false;
}
const calleePath = path.get('callee');
switch (calleePath.node.type) {
case 'MemberExpression':
case 'Identifier': {
const calleeSource = calleePath.getSource();
const firstArgPath = argsPath[0];
const innerName = inferredName + '$' + calleeSource;
const foundInside = findInnerComponents(
innerName,
firstArgPath,
callback,
);
if (!foundInside) {
return false;
}
// const Foo = hoc1(hoc2(() => {}))
// export default memo(React.forwardRef(function() {}))
callback(inferredName, node, path);
return true;
}
default: {
return false;
}
}
}
case 'VariableDeclarator': {
const init = node.init;
if (init === null) {
return false;
}
const name = node.id.name;
if (!isComponentishName(name)) {
return false;
}
switch (init.type) {
case 'ArrowFunctionExpression':
case 'FunctionExpression':
// Likely component definitions.
break;
case 'CallExpression': {
// Maybe a HOC.
// Try to determine if this is some form of import.
const callee = init.callee;
const calleeType = callee.type;
if (calleeType === 'Import') {
return false;
} else if (calleeType === 'Identifier') {
if (callee.name.indexOf('require') === 0) {
return false;
} else if (callee.name.indexOf('import') === 0) {
return false;
}
// Neither require nor import. Might be a HOC.
// Pass through.
} else if (calleeType === 'MemberExpression') {
// Could be something like React.forwardRef(...)
// Pass through.
}
break;
}
case 'TaggedTemplateExpression':
// Maybe something like styled.div`...`
break;
default:
return false;
}
const initPath = path.get('init');
const foundInside = findInnerComponents(
inferredName,
initPath,
callback,
);
if (foundInside) {
return true;
}
// See if this identifier is used in JSX. Then it's a component.
const binding = path.scope.getBinding(name);
if (binding === undefined) {
return;
}
let isLikelyUsedAsType = false;
const referencePaths = binding.referencePaths;
for (let i = 0; i < referencePaths.length; i++) {
const ref = referencePaths[i];
if (
ref.node &&
ref.node.type !== 'JSXIdentifier' &&
ref.node.type !== 'Identifier'
) {
continue;
}
const refParent = ref.parent;
if (refParent.type === 'JSXOpeningElement') {
isLikelyUsedAsType = true;
} else if (refParent.type === 'CallExpression') {
const callee = refParent.callee;
let fnName;
switch (callee.type) {
case 'Identifier':
fnName = callee.name;
break;
case 'MemberExpression':
fnName = callee.property.name;
break;
}
switch (fnName) {
case 'createElement':
case 'jsx':
case 'jsxDEV':
case 'jsxs':
isLikelyUsedAsType = true;
break;
}
}
if (isLikelyUsedAsType) {
// const X = ... + later <X />
callback(inferredName, init, initPath);
return true;
}
}
}
}
return false;
}
function isBuiltinHook(hookName) {
switch (hookName) {
case 'useState':
case 'React.useState':
case 'useReducer':
case 'React.useReducer':
case 'useEffect':
case 'React.useEffect':
case 'useLayoutEffect':
case 'React.useLayoutEffect':
case 'useMemo':
case 'React.useMemo':
case 'useCallback':
case 'React.useCallback':
case 'useRef':
case 'React.useRef':
case 'useContext':
case 'React.useContext':
case 'useImperativeHandle':
case 'React.useImperativeHandle':
case 'useDebugValue':
case 'React.useDebugValue':
return true;
default:
return false;
}
}
function getHookCallsSignature(functionNode) {
const fnHookCalls = hookCalls.get(functionNode);
if (fnHookCalls === undefined) {
return null;
}
return {
key: fnHookCalls.map(call => call.name + '{' + call.key + '}').join('\n'),
customHooks: fnHookCalls
.filter(call => !isBuiltinHook(call.name))
.map(call => t.cloneDeep(call.callee)),
};
}
const hasForceResetCommentByFile = new WeakMap();
// We let user do /* @refresh reset */ to reset state in the whole file.
function hasForceResetComment(path) {
const file = path.hub.file;
let hasForceReset = hasForceResetCommentByFile.get(file);
if (hasForceReset !== undefined) {
return hasForceReset;
}
hasForceReset = false;
const comments = file.ast.comments;
for (let i = 0; i < comments.length; i++) {
const cmt = comments[i];
if (cmt.value.indexOf('@refresh reset') !== -1) {
hasForceReset = true;
break;
}
}
hasForceResetCommentByFile.set(file, hasForceReset);
return hasForceReset;
}
function createArgumentsForSignature(node, signature, scope) {
const {key, customHooks} = signature;
let forceReset = hasForceResetComment(scope.path);
const customHooksInScope = [];
customHooks.forEach(callee => {
// Check if a corresponding binding exists where we emit the signature.
let bindingName;
switch (callee.type) {
case 'MemberExpression':
if (callee.object.type === 'Identifier') {
bindingName = callee.object.name;
}
break;
case 'Identifier':
bindingName = callee.name;
break;
}
if (scope.hasBinding(bindingName)) {
customHooksInScope.push(callee);
} else {
// We don't have anything to put in the array because Hook is out of scope.
// Since it could potentially have been edited, remount the component.
forceReset = true;
}
});
let finalKey = key;
if (typeof require === 'function' && !opts.emitFullSignatures) {
// Prefer to hash when we can (e.g. outside of ASTExplorer).
// This makes it deterministically compact, even if there's
// e.g. a useState initializer with some code inside.
// We also need it for www that has transforms like cx()
// that don't understand if something is part of a string.
finalKey = require('crypto')
.createHash('sha1')
.update(key)
.digest('base64');
}
const args = [node, t.stringLiteral(finalKey)];
if (forceReset || customHooksInScope.length > 0) {
args.push(t.booleanLiteral(forceReset));
}
if (customHooksInScope.length > 0) {
args.push(
// TODO: We could use an arrow here to be more compact.
// However, don't do it until AMA can run them natively.
t.functionExpression(
null,
[],
t.blockStatement([
t.returnStatement(t.arrayExpression(customHooksInScope)),
]),
),
);
}
return args;
}
function findHOCCallPathsAbove(path) {
const calls = [];
while (true) {
if (!path) {
return calls;
}
const parentPath = path.parentPath;
if (!parentPath) {
return calls;
}
if (
// hoc(_c = function() { })
parentPath.node.type === 'AssignmentExpression' &&
path.node === parentPath.node.right
) {
// Ignore registrations.
path = parentPath;
continue;
}
if (
// hoc1(hoc2(...))
parentPath.node.type === 'CallExpression' &&
path.node !== parentPath.node.callee
) {
calls.push(parentPath);
path = parentPath;
continue;
}
return calls; // Stop at other types.
}
}
const seenForRegistration = new WeakSet();
const seenForSignature = new WeakSet();
const seenForOutro = new WeakSet();
const hookCalls = new WeakMap();
const HookCallsVisitor = {
CallExpression(path) {
const node = path.node;
const callee = node.callee;
// Note: this visitor MUST NOT mutate the tree in any way.
// It runs early in a separate traversal and should be very fast.
let name = null;
switch (callee.type) {
case 'Identifier':
name = callee.name;
break;
case 'MemberExpression':
name = callee.property.name;
break;
}
if (name === null || !/^use[A-Z]/.test(name)) {
return;
}
const fnScope = path.scope.getFunctionParent();
if (fnScope === null) {
return;
}
// This is a Hook call. Record it.
const fnNode = fnScope.block;
if (!hookCalls.has(fnNode)) {
hookCalls.set(fnNode, []);
}
const hookCallsForFn = hookCalls.get(fnNode);
let key = '';
if (path.parent.type === 'VariableDeclarator') {
// TODO: if there is no LHS, consider some other heuristic.
key = path.parentPath.get('id').getSource();
}
// Some built-in Hooks reset on edits to arguments.
const args = path.get('arguments');
if (name === 'useState' && args.length > 0) {
// useState second argument is initial state.
key += '(' + args[0].getSource() + ')';
} else if (name === 'useReducer' && args.length > 1) {
// useReducer second argument is initial state.
key += '(' + args[1].getSource() + ')';
}
hookCallsForFn.push({
callee: path.node.callee,
name,
key,
});
},
};
return {
visitor: {
ExportDefaultDeclaration(path) {
const node = path.node;
const decl = node.declaration;
const declPath = path.get('declaration');
if (decl.type !== 'CallExpression') {
// For now, we only support possible HOC calls here.
// Named function declarations are handled in FunctionDeclaration.
// Anonymous direct exports like export default function() {}
// are currently ignored.
return;
}
// Make sure we're not mutating the same tree twice.
// This can happen if another Babel plugin replaces parents.
if (seenForRegistration.has(node)) {
return;
}
seenForRegistration.add(node);
// Don't mutate the tree above this point.
// This code path handles nested cases like:
// export default memo(() => {})
// In those cases it is more plausible people will omit names
// so they're worth handling despite possible false positives.
// More importantly, it handles the named case:
// export default memo(function Named() {})
const inferredName = '%default%';
const programPath = path.parentPath;
findInnerComponents(
inferredName,
declPath,
(persistentID, targetExpr, targetPath) => {
if (targetPath === null) {
// For case like:
// export default hoc(Foo)
// we don't want to wrap Foo inside the call.
// Instead we assume it's registered at definition.
return;
}
const handle = createRegistration(programPath, persistentID);
targetPath.replaceWith(
t.assignmentExpression('=', handle, targetExpr),
);
},
);
},
FunctionDeclaration: {
enter(path) {
const node = path.node;
let programPath;
let insertAfterPath;
let modulePrefix = '';
switch (path.parent.type) {
case 'Program':
insertAfterPath = path;
programPath = path.parentPath;
break;
case 'TSModuleBlock':
insertAfterPath = path;
programPath = insertAfterPath.parentPath.parentPath;
break;
case 'ExportNamedDeclaration':
insertAfterPath = path.parentPath;
programPath = insertAfterPath.parentPath;
break;
case 'ExportDefaultDeclaration':
insertAfterPath = path.parentPath;
programPath = insertAfterPath.parentPath;
break;
default:
return;
}
// These types can be nested in typescript namespace
// We need to find the export chain
// Or return if it stays local
if (
path.parent.type === 'TSModuleBlock' ||
path.parent.type === 'ExportNamedDeclaration'
) {
while (programPath.type !== 'Program') {
if (programPath.type === 'TSModuleDeclaration') {
if (
programPath.parentPath.type !== 'Program' &&
programPath.parentPath.type !== 'ExportNamedDeclaration'
) {
return;
}
modulePrefix = programPath.node.id.name + '$' + modulePrefix;
}
programPath = programPath.parentPath;
}
}
const id = node.id;
if (id === null) {
// We don't currently handle anonymous default exports.
return;
}
const inferredName = id.name;
if (!isComponentishName(inferredName)) {
return;
}
// Make sure we're not mutating the same tree twice.
// This can happen if another Babel plugin replaces parents.
if (seenForRegistration.has(node)) {
return;
}
seenForRegistration.add(node);
// Don't mutate the tree above this point.
const innerName = modulePrefix + inferredName;
// export function Named() {}
// function Named() {}
findInnerComponents(innerName, path, (persistentID, targetExpr) => {
const handle = createRegistration(programPath, persistentID);
insertAfterPath.insertAfter(
t.expressionStatement(
t.assignmentExpression('=', handle, targetExpr),
),
);
});
},
exit(path) {
const node = path.node;
const id = node.id;
if (id === null) {
return;
}
const signature = getHookCallsSignature(node);
if (signature === null) {
return;
}
// Make sure we're not mutating the same tree twice.
// This can happen if another Babel plugin replaces parents.
if (seenForSignature.has(node)) {
return;
}
seenForSignature.add(node);
// Don't mutate the tree above this point.
const sigCallID = path.scope.generateUidIdentifier('_s');
path.scope.parent.push({
id: sigCallID,
init: t.callExpression(refreshSig, []),
});
// The signature call is split in two parts. One part is called inside the function.
// This is used to signal when first render happens.
path
.get('body')
.unshiftContainer(
'body',
t.expressionStatement(t.callExpression(sigCallID, [])),
);
// The second call is around the function itself.
// This is used to associate a type with a signature.
// Unlike with $RefreshReg$, this needs to work for nested
// declarations too. So we need to search for a path where
// we can insert a statement rather than hard coding it.
let insertAfterPath = null;
path.find(p => {
if (p.parentPath.isBlock()) {
insertAfterPath = p;
return true;
}
});
if (insertAfterPath === null) {
return;
}
insertAfterPath.insertAfter(
t.expressionStatement(
t.callExpression(
sigCallID,
createArgumentsForSignature(
id,
signature,
insertAfterPath.scope,
),
),
),
);
},
},
'ArrowFunctionExpression|FunctionExpression': {
exit(path) {
const node = path.node;
const signature = getHookCallsSignature(node);
if (signature === null) {
return;
}
// Make sure we're not mutating the same tree twice.
// This can happen if another Babel plugin replaces parents.
if (seenForSignature.has(node)) {
return;
}
seenForSignature.add(node);
// Don't mutate the tree above this point.
const sigCallID = path.scope.generateUidIdentifier('_s');
path.scope.parent.push({
id: sigCallID,
init: t.callExpression(refreshSig, []),
});
// The signature call is split in two parts. One part is called inside the function.
// This is used to signal when first render happens.
if (path.node.body.type !== 'BlockStatement') {
path.node.body = t.blockStatement([
t.returnStatement(path.node.body),
]);
}
path
.get('body')
.unshiftContainer(
'body',
t.expressionStatement(t.callExpression(sigCallID, [])),
);
// The second call is around the function itself.
// This is used to associate a type with a signature.
if (path.parent.type === 'VariableDeclarator') {
let insertAfterPath = null;
path.find(p => {
if (p.parentPath.isBlock()) {
insertAfterPath = p;
return true;
}
});
if (insertAfterPath === null) {
return;
}
// Special case when a function would get an inferred name:
// let Foo = () => {}
// let Foo = function() {}
// We'll add signature it on next line so that
// we don't mess up the inferred 'Foo' function name.
insertAfterPath.insertAfter(
t.expressionStatement(
t.callExpression(
sigCallID,
createArgumentsForSignature(
path.parent.id,
signature,
insertAfterPath.scope,
),
),
),
);
// Result: let Foo = () => {}; __signature(Foo, ...);
} else {
// let Foo = hoc(() => {})
const paths = [path, ...findHOCCallPathsAbove(path)];
paths.forEach(p => {
p.replaceWith(
t.callExpression(
sigCallID,
createArgumentsForSignature(p.node, signature, p.scope),
),
);
});
// Result: let Foo = __signature(hoc(__signature(() => {}, ...)), ...)
}
},
},
VariableDeclaration(path) {
const node = path.node;
let programPath;
let insertAfterPath;
let modulePrefix = '';
switch (path.parent.type) {
case 'Program':
insertAfterPath = path;
programPath = path.parentPath;
break;
case 'TSModuleBlock':
insertAfterPath = path;
programPath = insertAfterPath.parentPath.parentPath;
break;
case 'ExportNamedDeclaration':
insertAfterPath = path.parentPath;
programPath = insertAfterPath.parentPath;
break;
case 'ExportDefaultDeclaration':
insertAfterPath = path.parentPath;
programPath = insertAfterPath.parentPath;
break;
default:
return;
}
// These types can be nested in typescript namespace
// We need to find the export chain
// Or return if it stays local
if (
path.parent.type === 'TSModuleBlock' ||
path.parent.type === 'ExportNamedDeclaration'
) {
while (programPath.type !== 'Program') {
if (programPath.type === 'TSModuleDeclaration') {
if (
programPath.parentPath.type !== 'Program' &&
programPath.parentPath.type !== 'ExportNamedDeclaration'
) {
return;
}
modulePrefix = programPath.node.id.name + '$' + modulePrefix;
}
programPath = programPath.parentPath;
}
}
// Make sure we're not mutating the same tree twice.
// This can happen if another Babel plugin replaces parents.
if (seenForRegistration.has(node)) {
return;
}
seenForRegistration.add(node);
// Don't mutate the tree above this point.
const declPaths = path.get('declarations');
if (declPaths.length !== 1) {
return;
}
const declPath = declPaths[0];
const inferredName = declPath.node.id.name;
const innerName = modulePrefix + inferredName;
findInnerComponents(
innerName,
declPath,
(persistentID, targetExpr, targetPath) => {
if (targetPath === null) {
// For case like:
// export const Something = hoc(Foo)
// we don't want to wrap Foo inside the call.
// Instead we assume it's registered at definition.
return;
}
const handle = createRegistration(programPath, persistentID);
if (targetPath.parent.type === 'VariableDeclarator') {
// Special case when a variable would get an inferred name:
// let Foo = () => {}
// let Foo = function() {}
// let Foo = styled.div``;
// We'll register it on next line so that
// we don't mess up the inferred 'Foo' function name.
// (eg: with @babel/plugin-transform-react-display-name or
// babel-plugin-styled-components)
insertAfterPath.insertAfter(
t.expressionStatement(
t.assignmentExpression('=', handle, declPath.node.id),
),
);
// Result: let Foo = () => {}; _c1 = Foo;
} else {
// let Foo = hoc(() => {})
targetPath.replaceWith(
t.assignmentExpression('=', handle, targetExpr),
);
// Result: let Foo = hoc(_c1 = () => {})
}
},
);
},
Program: {
enter(path) {
// This is a separate early visitor because we need to collect Hook calls
// and "const [foo, setFoo] = ..." signatures before the destructuring
// transform mangles them. This extra traversal is not ideal for perf,
// but it's the best we can do until we stop transpiling destructuring.
path.traverse(HookCallsVisitor);
},
exit(path) {
const registrations = registrationsByProgramPath.get(path);
if (registrations === undefined) {
return;
}
// Make sure we're not mutating the same tree twice.
// This can happen if another Babel plugin replaces parents.
const node = path.node;
if (seenForOutro.has(node)) {
return;
}
seenForOutro.add(node);
// Don't mutate the tree above this point.
registrationsByProgramPath.delete(path);
const declarators = [];
path.pushContainer('body', t.variableDeclaration('var', declarators));
registrations.forEach(({handle, persistentID}) => {
path.pushContainer(
'body',
t.expressionStatement(
t.callExpression(refreshReg, [
handle,
t.stringLiteral(persistentID),
]),
),
);
declarators.push(t.variableDeclarator(handle));
});
},
},
},
};
}
| 32.053318 | 96 | 0.526814 |
owtf | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
import {Children} from 'react';
// TODO: This logic could be in MDX plugins instead.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
export const PREPARE_MDX_CACHE_BREAKER = 3;
// !!! IMPORTANT !!! Bump this if you change any logic.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
export function prepareMDX(rawChildren) {
const toc = getTableOfContents(rawChildren, /* depth */ 10);
const children = wrapChildrenInMaxWidthContainers(rawChildren);
return {toc, children};
}
function wrapChildrenInMaxWidthContainers(children) {
// Auto-wrap everything except a few types into
// <MaxWidth> wrappers. Keep reusing the same
// wrapper as long as we can until we meet
// a full-width section which interrupts it.
let fullWidthTypes = [
'Sandpack',
'FullWidth',
'Illustration',
'IllustrationBlock',
'Challenges',
'Recipes',
];
let wrapQueue = [];
let finalChildren = [];
function flushWrapper(key) {
if (wrapQueue.length > 0) {
const Wrapper = 'MaxWidth';
finalChildren.push(<Wrapper key={key}>{wrapQueue}</Wrapper>);
wrapQueue = [];
}
}
function handleChild(child, key) {
if (child == null) {
return;
}
if (typeof child !== 'object') {
wrapQueue.push(child);
return;
}
if (fullWidthTypes.includes(child.type)) {
flushWrapper(key);
finalChildren.push(child);
} else {
wrapQueue.push(child);
}
}
Children.forEach(children, handleChild);
flushWrapper('last');
return finalChildren;
}
function getTableOfContents(children, depth) {
const anchors = [];
extractHeaders(children, depth, anchors);
if (anchors.length > 0) {
anchors.unshift({
url: '#',
text: 'Overview',
depth: 2,
});
}
return anchors;
}
const headerTypes = new Set([
'h1',
'h2',
'h3',
'Challenges',
'Recap',
'TeamMember',
]);
function extractHeaders(children, depth, out) {
for (const child of Children.toArray(children)) {
if (child.type && headerTypes.has(child.type)) {
let header;
if (child.type === 'Challenges') {
header = {
url: '#challenges',
depth: 2,
text: 'Challenges',
};
} else if (child.type === 'Recap') {
header = {
url: '#recap',
depth: 2,
text: 'Recap',
};
} else if (child.type === 'TeamMember') {
header = {
url: '#' + child.props.permalink,
depth: 3,
text: child.props.name,
};
} else {
header = {
url: '#' + child.props.id,
depth: (child.type && parseInt(child.type.replace('h', ''), 0)) ?? 0,
text: child.props.children,
};
}
out.push(header);
} else if (child.children && depth > 0) {
extractHeaders(child.children, depth - 1, out);
}
}
}
| 23.983051 | 79 | 0.558534 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useTheme;
exports.ThemeContext = void 0;
var _react = require("react");
/**
* 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.
*
*
*/
const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright');
exports.ThemeContext = ThemeContext;
function useTheme() {
const theme = (0, _react.useContext)(ThemeContext);
(0, _react.useDebugValue)(theme);
return theme;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZW1lIiwidGhlbWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBU0E7O0FBVEE7Ozs7Ozs7O0FBV0EsTUFBQUEsWUFBQSxnQkFBQSwwQkFBQSxRQUFBLENBQUE7OztBQUVBLFNBQUFDLFFBQUEsR0FBQTtBQUNBLFFBQUFDLEtBQUEsR0FBQSx1QkFBQUYsWUFBQSxDQUFBO0FBQ0EsNEJBQUFFLEtBQUE7QUFDQSxTQUFBQSxLQUFBO0FBQ0EiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0LCB1c2VEZWJ1Z1ZhbHVlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBjb25zdCBUaGVtZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0KCdicmlnaHQnKTtcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gdXNlVGhlbWUoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlQ29udGV4dChUaGVtZUNvbnRleHQpO1xuICB1c2VEZWJ1Z1ZhbHVlKHRoZW1lKTtcbiAgcmV0dXJuIHRoZW1lO1xufVxuIl19 | 60.555556 | 1,052 | 0.879591 |
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 {hslaColorToString, dimmedColor, ColorGenerator} from '../colors';
describe(hslaColorToString, () => {
it('should transform colors to strings', () => {
expect(hslaColorToString({h: 1, s: 2, l: 3, a: 4})).toEqual(
'hsl(1deg 2% 3% / 4)',
);
expect(hslaColorToString({h: 3.14, s: 6.28, l: 1.68, a: 100})).toEqual(
'hsl(3.14deg 6.28% 1.68% / 100)',
);
});
});
describe(dimmedColor, () => {
it('should dim luminosity using delta', () => {
expect(dimmedColor({h: 1, s: 2, l: 3, a: 4}, 3)).toEqual({
h: 1,
s: 2,
l: 0,
a: 4,
});
expect(dimmedColor({h: 1, s: 2, l: 3, a: 4}, -3)).toEqual({
h: 1,
s: 2,
l: 6,
a: 4,
});
});
});
describe(ColorGenerator, () => {
describe(ColorGenerator.prototype.colorForID, () => {
it('should generate a color for an ID', () => {
expect(new ColorGenerator().colorForID('123')).toMatchInlineSnapshot(`
{
"a": 1,
"h": 190,
"l": 80,
"s": 67,
}
`);
});
it('should generate colors deterministically given an ID', () => {
expect(new ColorGenerator().colorForID('id1')).toEqual(
new ColorGenerator().colorForID('id1'),
);
expect(new ColorGenerator().colorForID('id2')).toEqual(
new ColorGenerator().colorForID('id2'),
);
});
it('should generate different colors for different IDs', () => {
expect(new ColorGenerator().colorForID('id1')).not.toEqual(
new ColorGenerator().colorForID('id2'),
);
});
it('should return colors that have been set manually', () => {
const generator = new ColorGenerator();
const manualColor = {h: 1, s: 2, l: 3, a: 4};
generator.setColorForID('id with set color', manualColor);
expect(generator.colorForID('id with set color')).toEqual(manualColor);
expect(generator.colorForID('some other id')).not.toEqual(manualColor);
});
it('should generate colors from fixed color spaces', () => {
const generator = new ColorGenerator(1, 2, 3, 4);
expect(generator.colorForID('123')).toEqual({h: 1, s: 2, l: 3, a: 4});
expect(generator.colorForID('234')).toEqual({h: 1, s: 2, l: 3, a: 4});
});
it('should generate colors from range color spaces', () => {
const generator = new ColorGenerator(
{min: 0, max: 360, count: 2},
2,
3,
4,
);
expect(generator.colorForID('123')).toEqual({h: 0, s: 2, l: 3, a: 4});
expect(generator.colorForID('234')).toEqual({h: 360, s: 2, l: 3, a: 4});
});
});
});
| 29.06383 | 78 | 0.558584 |
null | /**
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
// Polyfills for test environment
global.ReadableStream =
require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;
global.TextDecoder = require('util').TextDecoder;
global.Headers = require('node-fetch').Headers;
global.Request = require('node-fetch').Request;
global.Response = require('node-fetch').Response;
// Patch for Edge environments for global scope
global.AsyncLocalStorage = require('async_hooks').AsyncLocalStorage;
// Don't wait before processing work on the server.
// TODO: we can replace this with FlightServer.act().
global.setTimeout = cb => cb();
let fetchCount = 0;
async function fetchMock(resource, options) {
fetchCount++;
const request = new Request(resource, options);
return new Response(
request.method +
' ' +
request.url +
' ' +
JSON.stringify(Array.from(request.headers.entries())),
);
}
let React;
let ReactServerDOMServer;
let ReactServerDOMClient;
let use;
describe('ReactFetch', () => {
beforeEach(() => {
jest.resetModules();
fetchCount = 0;
global.fetch = fetchMock;
jest.mock('react', () => require('react/react.shared-subset'));
jest.mock('react-server-dom-webpack/server', () =>
require('react-server-dom-webpack/server.edge'),
);
require('react-server-dom-webpack/src/__tests__/utils/WebpackMock');
React = require('react');
ReactServerDOMServer = require('react-server-dom-webpack/server');
jest.resetModules();
__unmockReact();
jest.unmock('react-server-dom-webpack/server');
ReactServerDOMClient = require('react-server-dom-webpack/client');
use = React.use;
});
async function render(Component) {
const stream = ReactServerDOMServer.renderToReadableStream(<Component />);
return ReactServerDOMClient.createFromReadableStream(stream);
}
// @gate enableFetchInstrumentation && enableCache
it('can dedupe fetches separately in interleaved renders', async () => {
async function getData() {
const r1 = await fetch('hi');
const t1 = await r1.text();
const r2 = await fetch('hi');
const t2 = await r2.text();
return t1 + ' ' + t2;
}
function Component() {
return use(getData());
}
const render1 = render(Component);
const render2 = render(Component);
expect(await render1).toMatchInlineSnapshot(`"GET hi [] GET hi []"`);
expect(await render2).toMatchInlineSnapshot(`"GET hi [] GET hi []"`);
expect(fetchCount).toBe(2);
});
});
| 29.318681 | 78 | 0.679478 |
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.
*
* @noflow
*/
// Provided by www
const ReactFbErrorUtils = require('ReactFbErrorUtils');
if (typeof ReactFbErrorUtils.invokeGuardedCallback !== 'function') {
throw new Error(
'Expected ReactFbErrorUtils.invokeGuardedCallback to be a function.',
);
}
function invokeGuardedCallbackImpl<A, B, C, D, E, F, Context>(
name: string | null,
func: (a: A, b: B, c: C, d: D, e: E, f: F) => mixed,
context: Context,
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
) {
// This will call `this.onError(err)` if an error was caught.
ReactFbErrorUtils.invokeGuardedCallback.apply(this, arguments);
}
export default invokeGuardedCallbackImpl;
| 23.028571 | 73 | 0.680952 |
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 const moduleAStartError = new Error();
export const innerErrorA = new Error();
export const moduleAStopError = new Error();
export const outerError = new Error();
export const moduleBStartError = new Error();
export const innerErrorB = new Error();
export const moduleBStopError = new Error();
| 25.736842 | 66 | 0.731755 |
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';
import {
getVisibleChildren,
insertNodesAndExecuteScripts,
} from '../test-utils/FizzTestUtils';
// Polyfills for test environment
global.ReadableStream =
require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;
global.TextDecoder = require('util').TextDecoder;
let React;
let ReactDOM;
let ReactDOMFizzServer;
let ReactDOMFizzStatic;
let Suspense;
let container;
describe('ReactDOMFizzStaticBrowser', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMFizzServer = require('react-dom/server.browser');
if (__EXPERIMENTAL__) {
ReactDOMFizzStatic = require('react-dom/static.browser');
}
Suspense = React.Suspense;
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
});
const theError = new Error('This is an error');
function Throw() {
throw theError;
}
const theInfinitePromise = new Promise(() => {});
function InfiniteSuspend() {
throw theInfinitePromise;
}
function concat(streamA, streamB) {
const readerA = streamA.getReader();
const readerB = streamB.getReader();
return new ReadableStream({
start(controller) {
function readA() {
readerA.read().then(({done, value}) => {
if (done) {
readB();
return;
}
controller.enqueue(value);
readA();
});
}
function readB() {
readerB.read().then(({done, value}) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
readB();
});
}
readA();
},
});
}
async function readContent(stream) {
const reader = stream.getReader();
let content = '';
while (true) {
const {done, value} = await reader.read();
if (done) {
return content;
}
content += Buffer.from(value).toString('utf8');
}
}
async function readIntoContainer(stream) {
const reader = stream.getReader();
let result = '';
while (true) {
const {done, value} = await reader.read();
if (done) {
break;
}
result += Buffer.from(value).toString('utf8');
}
const temp = document.createElement('div');
temp.innerHTML = result;
await insertNodesAndExecuteScripts(temp, container, null);
}
// @gate experimental
it('should call prerender', async () => {
const result = await ReactDOMFizzStatic.prerender(<div>hello world</div>);
const prelude = await readContent(result.prelude);
expect(prelude).toMatchInlineSnapshot(`"<div>hello world</div>"`);
});
// @gate experimental
it('should emit DOCTYPE at the root of the document', async () => {
const result = await ReactDOMFizzStatic.prerender(
<html>
<body>hello world</body>
</html>,
);
const prelude = await readContent(result.prelude);
if (gate(flags => flags.enableFloat)) {
expect(prelude).toMatchInlineSnapshot(
`"<!DOCTYPE html><html><head></head><body>hello world</body></html>"`,
);
} else {
expect(prelude).toMatchInlineSnapshot(
`"<!DOCTYPE html><html><body>hello world</body></html>"`,
);
}
});
// @gate experimental
it('should emit bootstrap script src at the end', async () => {
const result = await ReactDOMFizzStatic.prerender(<div>hello world</div>, {
bootstrapScriptContent: 'INIT();',
bootstrapScripts: ['init.js'],
bootstrapModules: ['init.mjs'],
});
const prelude = await readContent(result.prelude);
expect(prelude).toMatchInlineSnapshot(
`"<link rel="preload" as="script" fetchPriority="low" href="init.js"/><link rel="modulepreload" fetchPriority="low" href="init.mjs"/><div>hello world</div><script>INIT();</script><script src="init.js" async=""></script><script type="module" src="init.mjs" async=""></script>"`,
);
});
// @gate experimental
it('emits all HTML as one unit', async () => {
let hasLoaded = false;
let resolve;
const promise = new Promise(r => (resolve = r));
function Wait() {
if (!hasLoaded) {
throw promise;
}
return 'Done';
}
const resultPromise = ReactDOMFizzStatic.prerender(
<div>
<Suspense fallback="Loading">
<Wait />
</Suspense>
</div>,
);
await jest.runAllTimers();
// Resolve the loading.
hasLoaded = true;
await resolve();
const result = await resultPromise;
const prelude = await readContent(result.prelude);
expect(prelude).toMatchInlineSnapshot(
`"<div><!--$-->Done<!-- --><!--/$--></div>"`,
);
});
// @gate experimental
it('should reject the promise when an error is thrown at the root', async () => {
const reportedErrors = [];
let caughtError = null;
try {
await ReactDOMFizzStatic.prerender(
<div>
<Throw />
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theError);
expect(reportedErrors).toEqual([theError]);
});
// @gate experimental
it('should reject the promise when an error is thrown inside a fallback', async () => {
const reportedErrors = [];
let caughtError = null;
try {
await ReactDOMFizzStatic.prerender(
<div>
<Suspense fallback={<Throw />}>
<InfiniteSuspend />
</Suspense>
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theError);
expect(reportedErrors).toEqual([theError]);
});
// @gate experimental
it('should not error the stream when an error is thrown inside suspense boundary', async () => {
const reportedErrors = [];
const result = await ReactDOMFizzStatic.prerender(
<div>
<Suspense fallback={<div>Loading</div>}>
<Throw />
</Suspense>
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
const prelude = await readContent(result.prelude);
expect(prelude).toContain('Loading');
expect(reportedErrors).toEqual([theError]);
});
// @gate experimental
it('should be able to complete by aborting even if the promise never resolves', async () => {
const errors = [];
const controller = new AbortController();
const resultPromise = ReactDOMFizzStatic.prerender(
<div>
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
await jest.runAllTimers();
controller.abort();
const result = await resultPromise;
const prelude = await readContent(result.prelude);
expect(prelude).toContain('Loading');
expect(errors).toEqual(['The operation was aborted.']);
});
// @gate experimental
it('should reject if aborting before the shell is complete', async () => {
const errors = [];
const controller = new AbortController();
const promise = ReactDOMFizzStatic.prerender(
<div>
<InfiniteSuspend />
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
await jest.runAllTimers();
const theReason = new Error('aborted for reasons');
controller.abort(theReason);
let caughtError = null;
try {
await promise;
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theReason);
expect(errors).toEqual(['aborted for reasons']);
});
// @gate experimental
it('should be able to abort before something suspends', async () => {
const errors = [];
const controller = new AbortController();
function App() {
controller.abort();
return (
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
);
}
const streamPromise = ReactDOMFizzStatic.prerender(
<div>
<App />
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
let caughtError = null;
try {
await streamPromise;
} catch (error) {
caughtError = error;
}
expect(caughtError.message).toBe('The operation was aborted.');
expect(errors).toEqual(['The operation was aborted.']);
});
// @gate experimental
it('should reject if passing an already aborted signal', async () => {
const errors = [];
const controller = new AbortController();
const theReason = new Error('aborted for reasons');
controller.abort(theReason);
const promise = ReactDOMFizzStatic.prerender(
<div>
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
// Technically we could still continue rendering the shell but currently the
// semantics mean that we also abort any pending CPU work.
let caughtError = null;
try {
await promise;
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theReason);
expect(errors).toEqual(['aborted for reasons']);
});
// @gate experimental
it('supports custom abort reasons with a string', async () => {
const promise = new Promise(r => {});
function Wait() {
throw promise;
}
function App() {
return (
<div>
<p>
<Suspense fallback={'p'}>
<Wait />
</Suspense>
</p>
<span>
<Suspense fallback={'span'}>
<Wait />
</Suspense>
</span>
</div>
);
}
const errors = [];
const controller = new AbortController();
const resultPromise = ReactDOMFizzStatic.prerender(<App />, {
signal: controller.signal,
onError(x) {
errors.push(x);
return 'a digest';
},
});
controller.abort('foobar');
await resultPromise;
expect(errors).toEqual(['foobar', 'foobar']);
});
// @gate experimental
it('supports custom abort reasons with an Error', async () => {
const promise = new Promise(r => {});
function Wait() {
throw promise;
}
function App() {
return (
<div>
<p>
<Suspense fallback={'p'}>
<Wait />
</Suspense>
</p>
<span>
<Suspense fallback={'span'}>
<Wait />
</Suspense>
</span>
</div>
);
}
const errors = [];
const controller = new AbortController();
const resultPromise = ReactDOMFizzStatic.prerender(<App />, {
signal: controller.signal,
onError(x) {
errors.push(x.message);
return 'a digest';
},
});
controller.abort(new Error('uh oh'));
await resultPromise;
expect(errors).toEqual(['uh oh', 'uh oh']);
});
// @gate enablePostpone
it('supports postponing in prerender and resuming later', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return ['Hello', 'World'];
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<Postpone />
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(
<div>{['Hello', 'World']}</div>,
);
});
// @gate enablePostpone
it('supports postponing in prerender and resuming with a prefix', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'World';
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
Hello
<Postpone />
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(
<div>{['Hello', 'World']}</div>,
);
});
// @gate enablePostpone
it('supports postponing in lazy in prerender and resuming later', async () => {
let prerendering = true;
const Hole = React.lazy(async () => {
React.unstable_postpone();
});
function App() {
return (
<div>
<Suspense fallback="Loading...">
Hi
{prerendering ? Hole : 'Hello'}
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(
<div>
{'Hi'}
{'Hello'}
</div>,
);
});
// @gate enablePostpone
it('supports postponing in a nested array', async () => {
let prerendering = true;
const Hole = React.lazy(async () => {
React.unstable_postpone();
});
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
Hi
{[<Postpone key="key" />, prerendering ? Hole : 'World']}
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(
<div>{['Hi', 'Hello', 'World']}</div>,
);
});
// @gate enablePostpone
it('supports postponing in lazy as a direct child', async () => {
let prerendering = true;
const Hole = React.lazy(async () => {
React.unstable_postpone();
});
function Postpone() {
return prerendering ? Hole : 'Hello';
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<Postpone key="key" />
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(<div>Hello</div>);
});
// @gate enablePostpone
it('only emits end tags once when resuming', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
function App() {
return (
<html>
<body>
<Suspense fallback="Loading...">
<Postpone />
</Suspense>
</body>
</html>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const content = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
const html = await readContent(concat(prerendered.prelude, content));
const htmlEndTags = /<\/html\s*>/gi;
const bodyEndTags = /<\/body\s*>/gi;
expect(Array.from(html.matchAll(htmlEndTags)).length).toBe(1);
expect(Array.from(html.matchAll(bodyEndTags)).length).toBe(1);
});
// @gate enablePostpone
it('can prerender various hoistables and deduped resources', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return (
<>
<link rel="stylesheet" href="my-style2" precedence="low" />
<link rel="stylesheet" href="my-style1" precedence="high" />
<style precedence="high" href="my-style3">
style
</style>
<img src="my-img" />
</>
);
}
function App() {
ReactDOM.preconnect('example.com');
ReactDOM.preload('my-font', {as: 'font', type: 'font/woff2'});
ReactDOM.preload('my-style0', {as: 'style'});
// This should transfer the props in to the style that loads later.
ReactDOM.preload('my-style2', {
as: 'style',
crossOrigin: 'use-credentials',
});
return (
<div>
<Suspense fallback="Loading...">
<link rel="stylesheet" href="my-style1" precedence="high" />
<img src="my-img" />
<Postpone />
</Suspense>
<title>Hello World</title>
</div>
);
}
let calledInit = false;
jest.mock(
'init.js',
() => {
calledInit = true;
},
{virtual: true},
);
const prerendered = await ReactDOMFizzStatic.prerender(<App />, {
bootstrapScripts: ['init.js'],
});
expect(prerendered.postponed).not.toBe(null);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual([
<link href="example.com" rel="preconnect" />,
<link
as="font"
crossorigin=""
href="my-font"
rel="preload"
type="font/woff2"
/>,
<link as="image" href="my-img" rel="preload" />,
<link data-precedence="high" href="my-style1" rel="stylesheet" />,
<link as="script" fetchpriority="low" href="init.js" rel="preload" />,
<link as="style" href="my-style0" rel="preload" />,
<link
as="style"
crossorigin="use-credentials"
href="my-style2"
rel="preload"
/>,
<title>Hello World</title>,
<div>Loading...</div>,
]);
prerendering = false;
const content = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(content);
expect(calledInit).toBe(true);
// Dispatch load event to injected stylesheet
const link = document.querySelector(
'link[rel="stylesheet"][href="my-style2"]',
);
const event = document.createEvent('Events');
event.initEvent('load', true, true);
link.dispatchEvent(event);
// Wait for the instruction microtasks to flush.
await 0;
await 0;
expect(getVisibleChildren(container)).toEqual([
<link href="example.com" rel="preconnect" />,
<link
as="font"
crossorigin=""
href="my-font"
rel="preload"
type="font/woff2"
/>,
<link as="image" href="my-img" rel="preload" />,
<link data-precedence="high" href="my-style1" rel="stylesheet" />,
<style data-href="my-style3" data-precedence="high">
style
</style>,
<link
crossorigin="use-credentials"
data-precedence="low"
href="my-style2"
rel="stylesheet"
/>,
<link as="script" fetchpriority="low" href="init.js" rel="preload" />,
<link as="style" href="my-style0" rel="preload" />,
<link
as="style"
crossorigin="use-credentials"
href="my-style2"
rel="preload"
/>,
<title>Hello World</title>,
<div>
<img src="my-img" />
<img src="my-img" />
</div>,
]);
});
// @gate enablePostpone
it('can postpone a boundary after it has already been added', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<Suspense fallback="Loading...">
<Postpone />
</Suspense>
<Postpone />
<Postpone />
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(
<div>{['Hello', 'Hello', 'Hello']}</div>,
);
});
// @gate enablePostpone
it('can postpone in fallback', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
const Lazy = React.lazy(async () => {
await 0;
return {default: Postpone};
});
function App() {
return (
<div>
<Suspense fallback="Outer">
<Suspense fallback={<Postpone />}>
<Postpone /> World
</Suspense>
<Suspense fallback={<Postpone />}>
<Lazy />
</Suspense>
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Outer</div>);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(
<div>
{'Hello'}
{' World'}
{'Hello'}
</div>,
);
});
// @gate enablePostpone
it('can postpone in fallback without postponing the tree', async () => {
function Postpone() {
React.unstable_postpone();
}
const lazyText = React.lazy(async () => {
await 0; // causes the fallback to start work
return {default: 'Hello'};
});
function App() {
return (
<div>
<Suspense fallback="Outer">
<Suspense fallback={<Postpone />}>{lazyText}</Suspense>
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
// TODO: This should actually be null because we should've been able to fully
// resolve the render on the server eventually, even though the fallback postponed.
// So we should not need to resume.
expect(prerendered.postponed).not.toBe(null);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Outer</div>);
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await readIntoContainer(resumed);
expect(getVisibleChildren(container)).toEqual(<div>Hello</div>);
});
// @gate enablePostpone
it('errors if the replay does not line up', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
function Wrapper({children}) {
return children;
}
const lazySpan = React.lazy(async () => {
await 0;
return {default: <span />};
});
function App() {
const children = (
<Suspense fallback="Loading...">
<Postpone />
</Suspense>
);
return (
<>
<div>{prerendering ? <Wrapper>{children}</Wrapper> : children}</div>
<div>
{prerendering ? (
<Suspense fallback="Loading...">
<div>
<Postpone />
</div>
</Suspense>
) : (
lazySpan
)}
</div>
</>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual([
<div>Loading...</div>,
<div>Loading...</div>,
]);
prerendering = false;
const errors = [];
const resumed = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
{
onError(x) {
errors.push(x.message);
},
},
);
expect(errors).toEqual([
'Expected the resume to render <Wrapper> in this slot but instead it rendered <Suspense>. ' +
"The tree doesn't match so React will fallback to client rendering.",
'Expected the resume to render <Suspense> in this slot but instead it rendered <span>. ' +
"The tree doesn't match so React will fallback to client rendering.",
]);
// TODO: Test the component stack but we don't expose it to the server yet.
await readIntoContainer(resumed);
// Client rendered
expect(getVisibleChildren(container)).toEqual([
<div>Loading...</div>,
<div>Loading...</div>,
]);
});
// @gate enablePostpone
it('can abort the resume', async () => {
let prerendering = true;
const infinitePromise = new Promise(() => {});
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
function App() {
if (!prerendering) {
React.use(infinitePromise);
}
return (
<div>
<Suspense fallback="Loading...">
<Postpone />
</Suspense>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
prerendering = false;
const controller = new AbortController();
const errors = [];
const resumedPromise = ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
{
signal: controller.signal,
onError(x) {
errors.push(x);
},
},
);
controller.abort('abort');
const resumed = await resumedPromise;
await resumed.allReady;
expect(errors).toEqual(['abort']);
await readIntoContainer(resumed);
// Client rendered
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
});
// @gate enablePostpone
it('can suspend in a replayed component several layers deep', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
let resolve;
const promise = new Promise(r => (resolve = r));
function Delay({children}) {
if (!prerendering) {
React.use(promise);
}
return children;
}
// This wrapper will cause us to do one destructive render past this.
function Outer({children}) {
return children;
}
function App() {
return (
<div>
<Outer>
<Delay>
<Suspense fallback="Loading...">
<Postpone />
</Suspense>
</Delay>
</Outer>
</div>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
await readIntoContainer(prerendered.prelude);
prerendering = false;
const resumedPromise = ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
await jest.runAllTimers();
expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>);
await resolve();
await readIntoContainer(await resumedPromise);
expect(getVisibleChildren(container)).toEqual(<div>Hello</div>);
});
// @gate enablePostpone
it('emits an empty prelude and resumes at the root if we postpone in the shell', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
function App() {
return (
<html lang="en">
<body>
<link rel="stylesheet" href="my-style" precedence="high" />
<Postpone />
</body>
</html>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
expect(await readContent(prerendered.prelude)).toBe('');
const content = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
expect(await readContent(content)).toBe(
'<!DOCTYPE html><html lang="en"><head>' +
'<link rel="stylesheet" href="my-style" data-precedence="high"/>' +
'</head><body>Hello</body></html>',
);
});
// @gate enablePostpone
it('emits an empty prelude if we have not rendered html or head tags yet', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return (
<html lang="en">
<body>Hello</body>
</html>
);
}
function App() {
return (
<>
<link rel="stylesheet" href="my-style" precedence="high" />
<Postpone />
</>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
expect(await readContent(prerendered.prelude)).toBe('');
const content = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
expect(await readContent(content)).toBe(
'<!DOCTYPE html><html lang="en"><head>' +
'<link rel="stylesheet" href="my-style" data-precedence="high"/>' +
'</head><body>Hello</body></html>',
);
});
// @gate enablePostpone
it('emits an empty prelude if a postpone in a promise in the shell', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return 'Hello';
}
const Lazy = React.lazy(async () => {
await 0;
return {default: Postpone};
});
function App() {
return (
<html>
<link rel="stylesheet" href="my-style" precedence="high" />
<body>
<div>
<Lazy />
</div>
</body>
</html>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
expect(await readContent(prerendered.prelude)).toBe('');
const content = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
expect(await readContent(content)).toBe(
'<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" href="my-style" data-precedence="high"/>' +
'</head><body><div>Hello</div></body></html>',
);
});
// @gate enablePostpone
it('does not emit preloads during resume for Resources preloaded through onHeaders', async () => {
let prerendering = true;
let hasLoaded = false;
let resolve;
const promise = new Promise(r => (resolve = r));
function WaitIfResuming({children}) {
if (!prerendering && !hasLoaded) {
throw promise;
}
return children;
}
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return null;
}
let headers;
function onHeaders(x) {
headers = x;
}
function App() {
ReactDOM.preload('image', {as: 'image', fetchPriority: 'high'});
return (
<html>
<body>
hello
<Suspense fallback={null}>
<WaitIfResuming>
world
<link rel="stylesheet" href="style" precedence="default" />
</WaitIfResuming>
</Suspense>
<Postpone />
</body>
</html>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />, {
onHeaders,
});
expect(prerendered.postponed).not.toBe(null);
prerendering = false;
expect(await readContent(prerendered.prelude)).toBe('');
expect(headers).toEqual(
new Headers({
Link: `
<image>; rel=preload; as="image"; fetchpriority="high",
<style>; rel=preload; as="style"
`
.replaceAll('\n', '')
.trim(),
}),
);
const content = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(JSON.stringify(prerendered.postponed)),
);
const decoder = new TextDecoder();
const reader = content.getReader();
let {value, done} = await reader.read();
let result = decoder.decode(value, {stream: true});
expect(result).toBe(
'<!DOCTYPE html><html><head></head><body>hello<!--$?--><template id="B:1"></template><!--/$-->',
);
await 1;
hasLoaded = true;
resolve();
while (true) {
({value, done} = await reader.read());
if (done) {
result += decoder.decode(value);
break;
}
result += decoder.decode(value, {stream: true});
}
// We are mostly just trying to assert that no preload for our stylesheet was emitted
// prior to sending the segment the stylesheet was for. This test is asserting this
// because the boundary complete instruction is sent when we are writing the
const instructionIndex = result.indexOf('$RC');
expect(instructionIndex > -1).toBe(true);
const slice = result.slice(0, instructionIndex + '$RC'.length);
expect(slice).toBe(
'<!DOCTYPE html><html><head></head><body>hello<!--$?--><template id="B:1"></template><!--/$--><div hidden id="S:1">world<!-- --></div><script>$RC',
);
});
// @gate experimental
it('logs an error if onHeaders throws but continues the prerender', async () => {
const errors = [];
function onError(error) {
errors.push(error.message);
}
function onHeaders(x) {
throw new Error('bad onHeaders');
}
const prerendered = await ReactDOMFizzStatic.prerender(<div>hello</div>, {
onHeaders,
onError,
});
expect(prerendered.postponed).toBe(null);
expect(errors).toEqual(['bad onHeaders']);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual(<div>hello</div>);
});
// @gate enablePostpone
it('does not bootstrap again in a resume if it bootstraps', async () => {
let prerendering = true;
function Postpone() {
if (prerendering) {
React.unstable_postpone();
}
return null;
}
function App() {
return (
<html>
<body>
<Suspense fallback="loading...">
<Postpone />
hello
</Suspense>
</body>
</html>
);
}
let inits = 0;
jest.mock(
'init.js',
() => {
inits++;
},
{virtual: true},
);
const prerendered = await ReactDOMFizzStatic.prerender(<App />, {
bootstrapScripts: ['init.js'],
});
const postponedSerializedState = JSON.stringify(prerendered.postponed);
expect(prerendered.postponed).not.toBe(null);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual([
<link rel="preload" href="init.js" fetchpriority="low" as="script" />,
'loading...',
]);
expect(inits).toBe(1);
jest.resetModules();
jest.mock(
'init.js',
() => {
inits++;
},
{virtual: true},
);
prerendering = false;
const content = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(postponedSerializedState),
);
await readIntoContainer(content);
expect(inits).toBe(1);
expect(getVisibleChildren(container)).toEqual([
<link rel="preload" href="init.js" fetchpriority="low" as="script" />,
'hello',
]);
});
// @gate enablePostpone
it('can render a deep list of single components where one postpones', async () => {
let isPrerendering = true;
function Outer({children}) {
return children;
}
function Middle({children}) {
return children;
}
function Inner() {
if (isPrerendering) {
React.unstable_postpone();
}
return 'hello';
}
function App() {
return (
<Suspense fallback="loading...">
<Outer>
<Middle>
<Inner />
</Middle>
</Outer>
</Suspense>
);
}
const prerendered = await ReactDOMFizzStatic.prerender(<App />);
const postponedState = JSON.stringify(prerendered.postponed);
await readIntoContainer(prerendered.prelude);
expect(getVisibleChildren(container)).toEqual('loading...');
isPrerendering = false;
const dynamic = await ReactDOMFizzServer.resume(
<App />,
JSON.parse(postponedState),
);
await readIntoContainer(dynamic);
expect(getVisibleChildren(container)).toEqual('hello');
});
});
| 24.371811 | 283 | 0.572621 |
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 {
clampState,
moveStateToRange,
areScrollStatesEqual,
translateState,
zoomState,
} from '../scrollState';
describe(clampState, () => {
it('should passthrough offset if state fits within container', () => {
expect(
clampState({
state: {offset: 0, length: 50},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).offset,
).toBeCloseTo(0, 10);
expect(
clampState({
state: {offset: -20, length: 100},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).offset,
).toBeCloseTo(-20, 10);
});
it('should clamp offset if offset causes content to go out of container', () => {
expect(
clampState({
state: {offset: -1, length: 50},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).offset,
).toBeCloseTo(0, 10);
expect(
clampState({
state: {offset: 1, length: 50},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).offset,
).toBeCloseTo(0, 10);
expect(
clampState({
state: {offset: -51, length: 100},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).offset,
).toBeCloseTo(-50, 10);
expect(
clampState({
state: {offset: 1, length: 100},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).offset,
).toBeCloseTo(0, 10);
});
it('should passthrough length if container fits in content', () => {
expect(
clampState({
state: {offset: 0, length: 70},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).length,
).toBeCloseTo(70, 10);
expect(
clampState({
state: {offset: 0, length: 50},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).length,
).toBeCloseTo(50, 10);
expect(
clampState({
state: {offset: 0, length: 100},
minContentLength: 0,
maxContentLength: 100,
containerLength: 50,
}).length,
).toBeCloseTo(100, 10);
});
it('should clamp length to minimum of max(minContentLength, containerLength)', () => {
expect(
clampState({
state: {offset: -20, length: 0},
minContentLength: 20,
maxContentLength: 100,
containerLength: 50,
}).length,
).toBeCloseTo(50, 10);
expect(
clampState({
state: {offset: -20, length: 0},
minContentLength: 50,
maxContentLength: 100,
containerLength: 20,
}).length,
).toBeCloseTo(50, 10);
});
it('should clamp length to maximum of max(containerLength, maxContentLength)', () => {
expect(
clampState({
state: {offset: -20, length: 100},
minContentLength: 0,
maxContentLength: 40,
containerLength: 50,
}).length,
).toBeCloseTo(50, 10);
expect(
clampState({
state: {offset: -20, length: 100},
minContentLength: 0,
maxContentLength: 50,
containerLength: 40,
}).length,
).toBeCloseTo(50, 10);
});
});
describe(translateState, () => {
it('should translate state by delta and leave length unchanged', () => {
expect(
translateState({
state: {offset: 0, length: 100},
delta: -3.14,
containerLength: 50,
}),
).toEqual({offset: -3.14, length: 100});
});
it('should clamp resulting offset', () => {
expect(
translateState({
state: {offset: 0, length: 50},
delta: -3.14,
containerLength: 50,
}).offset,
).toBeCloseTo(0, 10);
expect(
translateState({
state: {offset: 0, length: 53},
delta: -100,
containerLength: 50,
}).offset,
).toBeCloseTo(-3, 10);
});
});
describe(zoomState, () => {
it('should scale width by multiplier', () => {
expect(
zoomState({
state: {offset: 0, length: 100},
multiplier: 1.5,
fixedPoint: 0,
minContentLength: 0,
maxContentLength: 1000,
containerLength: 50,
}),
).toEqual({offset: 0, length: 150});
});
it('should clamp zoomed state', () => {
const zoomedState = zoomState({
state: {offset: -20, length: 100},
multiplier: 0.1,
fixedPoint: 5,
minContentLength: 50,
maxContentLength: 100,
containerLength: 50,
});
expect(zoomedState.offset).toBeCloseTo(0, 10);
expect(zoomedState.length).toBeCloseTo(50, 10);
});
it('should maintain containerStart<->fixedPoint distance', () => {
const offset = -20;
const fixedPointFromContainer = 10;
const zoomedState = zoomState({
state: {offset, length: 100},
multiplier: 2,
fixedPoint: fixedPointFromContainer - offset,
minContentLength: 0,
maxContentLength: 1000,
containerLength: 50,
});
expect(zoomedState).toMatchInlineSnapshot(`
{
"length": 200,
"offset": -50,
}
`);
});
});
describe(moveStateToRange, () => {
it('should set [rangeStart, rangeEnd] = container', () => {
const movedState = moveStateToRange({
state: {offset: -20, length: 100},
rangeStart: 50,
rangeEnd: 100,
contentLength: 400,
minContentLength: 10,
maxContentLength: 1000,
containerLength: 50,
});
expect(movedState).toMatchInlineSnapshot(`
{
"length": 400,
"offset": -50,
}
`);
});
});
describe(areScrollStatesEqual, () => {
it('should return true if equal', () => {
expect(
areScrollStatesEqual({offset: 0, length: 0}, {offset: 0, length: 0}),
).toBe(true);
expect(
areScrollStatesEqual({offset: -1, length: 1}, {offset: -1, length: 1}),
).toBe(true);
});
it('should return false if not equal', () => {
expect(
areScrollStatesEqual({offset: 0, length: 0}, {offset: -1, length: 0}),
).toBe(false);
expect(
areScrollStatesEqual({offset: -1, length: 1}, {offset: -1, length: 0}),
).toBe(false);
});
});
| 23.538168 | 88 | 0.564717 |
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
*/
import memoize from 'memoize-one';
import throttle from 'lodash.throttle';
import Agent from 'react-devtools-shared/src/backend/agent';
import {hideOverlay, showOverlay} from './Highlighter';
import type {BackendBridge} from 'react-devtools-shared/src/bridge';
// This plug-in provides in-page highlighting of the selected element.
// It is used by the browser extension and the standalone DevTools shell (when connected to a browser).
// It is not currently the mechanism used to highlight React Native views.
// That is done by the React Native Inspector component.
let iframesListeningTo: Set<HTMLIFrameElement> = new Set();
export default function setupHighlighter(
bridge: BackendBridge,
agent: Agent,
): void {
bridge.addListener(
'clearNativeElementHighlight',
clearNativeElementHighlight,
);
bridge.addListener('highlightNativeElement', highlightNativeElement);
bridge.addListener('shutdown', stopInspectingNative);
bridge.addListener('startInspectingNative', startInspectingNative);
bridge.addListener('stopInspectingNative', stopInspectingNative);
function startInspectingNative() {
registerListenersOnWindow(window);
}
function registerListenersOnWindow(window: any) {
// This plug-in may run in non-DOM environments (e.g. React Native).
if (window && typeof window.addEventListener === 'function') {
window.addEventListener('click', onClick, true);
window.addEventListener('mousedown', onMouseEvent, true);
window.addEventListener('mouseover', onMouseEvent, true);
window.addEventListener('mouseup', onMouseEvent, true);
window.addEventListener('pointerdown', onPointerDown, true);
window.addEventListener('pointermove', onPointerMove, true);
window.addEventListener('pointerup', onPointerUp, true);
} else {
agent.emit('startInspectingNative');
}
}
function stopInspectingNative() {
hideOverlay(agent);
removeListenersOnWindow(window);
iframesListeningTo.forEach(function (frame) {
try {
removeListenersOnWindow(frame.contentWindow);
} catch (error) {
// This can error when the iframe is on a cross-origin.
}
});
iframesListeningTo = new Set();
}
function removeListenersOnWindow(window: any) {
// This plug-in may run in non-DOM environments (e.g. React Native).
if (window && typeof window.removeEventListener === 'function') {
window.removeEventListener('click', onClick, true);
window.removeEventListener('mousedown', onMouseEvent, true);
window.removeEventListener('mouseover', onMouseEvent, true);
window.removeEventListener('mouseup', onMouseEvent, true);
window.removeEventListener('pointerdown', onPointerDown, true);
window.removeEventListener('pointermove', onPointerMove, true);
window.removeEventListener('pointerup', onPointerUp, true);
} else {
agent.emit('stopInspectingNative');
}
}
function clearNativeElementHighlight() {
hideOverlay(agent);
}
function highlightNativeElement({
displayName,
hideAfterTimeout,
id,
openNativeElementsPanel,
rendererID,
scrollIntoView,
}: {
displayName: string | null,
hideAfterTimeout: boolean,
id: number,
openNativeElementsPanel: boolean,
rendererID: number,
scrollIntoView: boolean,
...
}) {
const renderer = agent.rendererInterfaces[rendererID];
if (renderer == null) {
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
hideOverlay(agent);
return;
}
// In some cases fiber may already be unmounted
if (!renderer.hasFiberWithId(id)) {
hideOverlay(agent);
return;
}
const nodes: ?Array<HTMLElement> = (renderer.findNativeNodesForFiberID(
id,
): any);
if (nodes != null && nodes[0] != null) {
const node = nodes[0];
// $FlowFixMe[method-unbinding]
if (scrollIntoView && typeof node.scrollIntoView === 'function') {
// If the node isn't visible show it before highlighting it.
// We may want to reconsider this; it might be a little disruptive.
node.scrollIntoView({block: 'nearest', inline: 'nearest'});
}
showOverlay(nodes, displayName, agent, hideAfterTimeout);
if (openNativeElementsPanel) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 = node;
bridge.send('syncSelectionToNativeElementsPanel');
}
} else {
hideOverlay(agent);
}
}
function onClick(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
stopInspectingNative();
bridge.send('stopInspectingNative', true);
}
function onMouseEvent(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
}
function onPointerDown(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
selectFiberForNode(getEventTarget(event));
}
let lastHoveredNode: HTMLElement | null = null;
function onPointerMove(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
const target: HTMLElement = getEventTarget(event);
if (lastHoveredNode === target) return;
lastHoveredNode = target;
if (target.tagName === 'IFRAME') {
const iframe: HTMLIFrameElement = (target: any);
try {
if (!iframesListeningTo.has(iframe)) {
const window = iframe.contentWindow;
registerListenersOnWindow(window);
iframesListeningTo.add(iframe);
}
} catch (error) {
// This can error when the iframe is on a cross-origin.
}
}
// Don't pass the name explicitly.
// It will be inferred from DOM tag and Fiber owner.
showOverlay([target], null, agent, false);
selectFiberForNode(target);
}
function onPointerUp(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
}
const selectFiberForNode = throttle(
memoize((node: HTMLElement) => {
const id = agent.getIDForNode(node);
if (id !== null) {
bridge.send('selectFiber', id);
}
}),
200,
// Don't change the selection in the very first 200ms
// because those are usually unintentional as you lift the cursor.
{leading: false},
);
function getEventTarget(event: MouseEvent): HTMLElement {
if (event.composed) {
return (event.composedPath()[0]: any);
}
return (event.target: any);
}
}
| 29.536697 | 103 | 0.680739 |
Penetration-Testing-with-Shellcode | /**
* 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 {preinitScriptForSSR} from 'react-client/src/ReactFlightClientConfig';
export type ModuleLoading = null | {
prefix: string,
crossOrigin?: 'use-credentials' | '',
};
export function prepareDestinationWithChunks(
moduleLoading: ModuleLoading,
// Chunks are single-indexed filenames
chunks: Array<string>,
nonce: ?string,
) {
if (moduleLoading !== null) {
for (let i = 0; i < chunks.length; i++) {
preinitScriptForSSR(
moduleLoading.prefix + chunks[i],
nonce,
moduleLoading.crossOrigin,
);
}
}
}
| 22.242424 | 77 | 0.668407 |
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 * as React from 'react';
export default function App(): React.Node {
return <List />;
}
class List extends React.Component {
constructor(props: any) {
super(props);
this.state = {
items: ['one', 'two', 'three'],
};
}
addItem = () => {
if (this.inputRef && this.inputRef.value) {
this.setState({items: [...this.state.items, this.inputRef.value]});
this.inputRef.value = '';
}
};
render(): any {
return (
<div>
<input
data-testname="AddItemInput"
value={this.state.text}
onChange={this.onInputChange}
ref={c => (this.inputRef = c)}
/>
<button data-testname="AddItemButton" onClick={this.addItem}>
Add Item
</button>
<ul data-testname="List">
{this.state.items.map((label, index) => (
<ListItem key={index} label={label} />
))}
</ul>
</div>
);
}
}
// $FlowFixMe[missing-local-annot]
function ListItem({label}) {
return <li data-testname="ListItem">{label}</li>;
}
| 21.491228 | 73 | 0.56128 |
null | 'use strict';
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
'function'
) {
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
}
| 25.363636 | 73 | 0.685121 |
owtf | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
import {Fragment, useMemo} from 'react';
import {useRouter} from 'next/router';
import {Page} from 'components/Layout/Page';
import sidebarHome from '../sidebarHome.json';
import sidebarLearn from '../sidebarLearn.json';
import sidebarReference from '../sidebarReference.json';
import sidebarCommunity from '../sidebarCommunity.json';
import sidebarBlog from '../sidebarBlog.json';
import {MDXComponents} from 'components/MDX/MDXComponents';
import compileMDX from 'utils/compileMDX';
export default function Layout({content, toc, meta}) {
const parsedContent = useMemo(
() => JSON.parse(content, reviveNodeOnClient),
[content]
);
const parsedToc = useMemo(() => JSON.parse(toc, reviveNodeOnClient), [toc]);
const section = useActiveSection();
let routeTree;
switch (section) {
case 'home':
case 'unknown':
routeTree = sidebarHome;
break;
case 'learn':
routeTree = sidebarLearn;
break;
case 'reference':
routeTree = sidebarReference;
break;
case 'community':
routeTree = sidebarCommunity;
break;
case 'blog':
routeTree = sidebarBlog;
break;
}
return (
<Page toc={parsedToc} routeTree={routeTree} meta={meta} section={section}>
{parsedContent}
</Page>
);
}
function useActiveSection() {
const {asPath} = useRouter();
const cleanedPath = asPath.split(/[\?\#]/)[0];
if (cleanedPath === '/') {
return 'home';
} else if (cleanedPath.startsWith('/reference')) {
return 'reference';
} else if (asPath.startsWith('/learn')) {
return 'learn';
} else if (asPath.startsWith('/community')) {
return 'community';
} else if (asPath.startsWith('/blog')) {
return 'blog';
} else {
return 'unknown';
}
}
// Deserialize a client React tree from JSON.
function reviveNodeOnClient(key, val) {
if (Array.isArray(val) && val[0] == '$r') {
// Assume it's a React element.
let type = val[1];
let key = val[2];
let props = val[3];
if (type === 'wrapper') {
type = Fragment;
props = {children: props.children};
}
if (MDXComponents[type]) {
type = MDXComponents[type];
}
if (!type) {
console.error('Unknown type: ' + type);
type = Fragment;
}
return {
$$typeof: Symbol.for('react.element'),
type: type,
key: key,
ref: null,
props: props,
_owner: null,
};
} else {
return val;
}
}
// Put MDX output into JSON for client.
export async function getStaticProps(context) {
const fs = require('fs');
const rootDir = process.cwd() + '/src/content/';
// Read MDX from the file.
let path = (context.params.markdownPath || []).join('/') || 'index';
let mdx;
try {
mdx = fs.readFileSync(rootDir + path + '.md', 'utf8');
} catch {
mdx = fs.readFileSync(rootDir + path + '/index.md', 'utf8');
}
const {toc, content, meta} = await compileMDX(mdx, path, {});
return {
props: {
toc,
content,
meta,
},
};
}
// Collect all MDX files for static generation.
export async function getStaticPaths() {
const {promisify} = require('util');
const {resolve} = require('path');
const fs = require('fs');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);
const rootDir = process.cwd() + '/src/content';
// Find all MD files recursively.
async function getFiles(dir) {
const subdirs = await readdir(dir);
const files = await Promise.all(
subdirs.map(async (subdir) => {
const res = resolve(dir, subdir);
return (await stat(res)).isDirectory()
? getFiles(res)
: res.slice(rootDir.length + 1);
})
);
return (
files
.flat()
// ignores `errors/*.md`, they will be handled by `pages/errors/[errorCode].tsx`
.filter((file) => file.endsWith('.md') && !file.startsWith('errors/'))
);
}
// 'foo/bar/baz.md' -> ['foo', 'bar', 'baz']
// 'foo/bar/qux/index.md' -> ['foo', 'bar', 'qux']
function getSegments(file) {
let segments = file.slice(0, -3).replace(/\\/g, '/').split('/');
if (segments[segments.length - 1] === 'index') {
segments.pop();
}
return segments;
}
const files = await getFiles(rootDir);
const paths = files.map((file) => ({
params: {
markdownPath: getSegments(file),
// ^^^ CAREFUL HERE.
// If you rename markdownPath, update patches/next-remote-watch.patch too.
// Otherwise you'll break Fast Refresh for all MD files.
},
}));
return {
paths: paths,
fallback: false,
};
}
| 25.622857 | 88 | 0.604122 |
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';
describe('when Trusted Types are available in global object', () => {
let React;
let ReactDOM;
let ReactFeatureFlags;
let container;
let ttObject1;
let ttObject2;
beforeEach(() => {
jest.resetModules();
container = document.createElement('div');
const fakeTTObjects = new Set();
window.trustedTypes = {
isHTML: function (value) {
if (this !== window.trustedTypes) {
throw new Error(this);
}
return fakeTTObjects.has(value);
},
isScript: () => false,
isScriptURL: () => false,
};
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.enableTrustedTypesIntegration = true;
React = require('react');
ReactDOM = require('react-dom');
ttObject1 = {
toString() {
return '<b>Hi</b>';
},
};
ttObject2 = {
toString() {
return '<b>Bye</b>';
},
};
fakeTTObjects.add(ttObject1);
fakeTTObjects.add(ttObject2);
});
afterEach(() => {
delete window.trustedTypes;
});
it('should not stringify trusted values for dangerouslySetInnerHTML', () => {
const innerHTMLDescriptor = Object.getOwnPropertyDescriptor(
Element.prototype,
'innerHTML',
);
try {
const innerHTMLCalls = [];
Object.defineProperty(Element.prototype, 'innerHTML', {
get() {
return innerHTMLDescriptor.get.apply(this, arguments);
},
set(value) {
innerHTMLCalls.push(value);
return innerHTMLDescriptor.set.apply(this, arguments);
},
});
ReactDOM.render(
<div dangerouslySetInnerHTML={{__html: ttObject1}} />,
container,
);
expect(container.innerHTML).toBe('<div><b>Hi</b></div>');
expect(innerHTMLCalls.length).toBe(1);
// Ensure it didn't get stringified when passed to a DOM sink:
expect(innerHTMLCalls[0]).toBe(ttObject1);
innerHTMLCalls.length = 0;
ReactDOM.render(
<div dangerouslySetInnerHTML={{__html: ttObject2}} />,
container,
);
expect(container.innerHTML).toBe('<div><b>Bye</b></div>');
expect(innerHTMLCalls.length).toBe(1);
// Ensure it didn't get stringified when passed to a DOM sink:
expect(innerHTMLCalls[0]).toBe(ttObject2);
} finally {
Object.defineProperty(
Element.prototype,
'innerHTML',
innerHTMLDescriptor,
);
}
});
it('should not stringify trusted values for setAttribute (unknown attribute)', () => {
const setAttribute = Element.prototype.setAttribute;
try {
const setAttributeCalls = [];
Element.prototype.setAttribute = function (name, value) {
setAttributeCalls.push([this, name.toLowerCase(), value]);
return setAttribute.apply(this, arguments);
};
ReactDOM.render(<div data-foo={ttObject1} />, container);
expect(container.innerHTML).toBe('<div data-foo="<b>Hi</b>"></div>');
expect(setAttributeCalls.length).toBe(1);
expect(setAttributeCalls[0][0]).toBe(container.firstChild);
expect(setAttributeCalls[0][1]).toBe('data-foo');
// Ensure it didn't get stringified when passed to a DOM sink:
expect(setAttributeCalls[0][2]).toBe(ttObject1);
setAttributeCalls.length = 0;
ReactDOM.render(<div data-foo={ttObject2} />, container);
expect(setAttributeCalls.length).toBe(1);
expect(setAttributeCalls[0][0]).toBe(container.firstChild);
expect(setAttributeCalls[0][1]).toBe('data-foo');
// Ensure it didn't get stringified when passed to a DOM sink:
expect(setAttributeCalls[0][2]).toBe(ttObject2);
} finally {
Element.prototype.setAttribute = setAttribute;
}
});
it('should not stringify trusted values for setAttribute (known attribute)', () => {
const setAttribute = Element.prototype.setAttribute;
try {
const setAttributeCalls = [];
Element.prototype.setAttribute = function (name, value) {
setAttributeCalls.push([this, name.toLowerCase(), value]);
return setAttribute.apply(this, arguments);
};
ReactDOM.render(<div className={ttObject1} />, container);
expect(container.innerHTML).toBe('<div class="<b>Hi</b>"></div>');
expect(setAttributeCalls.length).toBe(1);
expect(setAttributeCalls[0][0]).toBe(container.firstChild);
expect(setAttributeCalls[0][1]).toBe('class');
// Ensure it didn't get stringified when passed to a DOM sink:
expect(setAttributeCalls[0][2]).toBe(ttObject1);
setAttributeCalls.length = 0;
ReactDOM.render(<div className={ttObject2} />, container);
expect(setAttributeCalls.length).toBe(1);
expect(setAttributeCalls[0][0]).toBe(container.firstChild);
expect(setAttributeCalls[0][1]).toBe('class');
// Ensure it didn't get stringified when passed to a DOM sink:
expect(setAttributeCalls[0][2]).toBe(ttObject2);
} finally {
Element.prototype.setAttribute = setAttribute;
}
});
it('should not stringify trusted values for setAttributeNS', () => {
const setAttributeNS = Element.prototype.setAttributeNS;
try {
const setAttributeNSCalls = [];
Element.prototype.setAttributeNS = function (ns, name, value) {
setAttributeNSCalls.push([this, ns, name, value]);
return setAttributeNS.apply(this, arguments);
};
ReactDOM.render(<svg xlinkHref={ttObject1} />, container);
expect(container.innerHTML).toBe('<svg xlink:href="<b>Hi</b>"></svg>');
expect(setAttributeNSCalls.length).toBe(1);
expect(setAttributeNSCalls[0][0]).toBe(container.firstChild);
expect(setAttributeNSCalls[0][1]).toBe('http://www.w3.org/1999/xlink');
expect(setAttributeNSCalls[0][2]).toBe('xlink:href');
// Ensure it didn't get stringified when passed to a DOM sink:
expect(setAttributeNSCalls[0][3]).toBe(ttObject1);
setAttributeNSCalls.length = 0;
ReactDOM.render(<svg xlinkHref={ttObject2} />, container);
expect(setAttributeNSCalls.length).toBe(1);
expect(setAttributeNSCalls[0][0]).toBe(container.firstChild);
expect(setAttributeNSCalls[0][1]).toBe('http://www.w3.org/1999/xlink');
expect(setAttributeNSCalls[0][2]).toBe('xlink:href');
// Ensure it didn't get stringified when passed to a DOM sink:
expect(setAttributeNSCalls[0][3]).toBe(ttObject2);
} finally {
Element.prototype.setAttributeNS = setAttributeNS;
}
});
describe('dangerouslySetInnerHTML in svg elements in Internet Explorer', () => {
let innerHTMLDescriptor;
// simulate svg elements in Internet Explorer which don't have 'innerHTML' property
beforeEach(() => {
innerHTMLDescriptor = Object.getOwnPropertyDescriptor(
Element.prototype,
'innerHTML',
);
delete Element.prototype.innerHTML;
Object.defineProperty(
HTMLDivElement.prototype,
'innerHTML',
innerHTMLDescriptor,
);
});
afterEach(() => {
delete HTMLDivElement.prototype.innerHTML;
Object.defineProperty(
Element.prototype,
'innerHTML',
innerHTMLDescriptor,
);
});
// @gate !disableIEWorkarounds
it('should log a warning', () => {
class Component extends React.Component {
render() {
return <svg dangerouslySetInnerHTML={{__html: 'unsafe html'}} />;
}
}
expect(() => {
ReactDOM.render(<Component />, container);
}).toErrorDev(
"Warning: Using 'dangerouslySetInnerHTML' in an svg element with " +
'Trusted Types enabled in an Internet Explorer will cause ' +
'the trusted value to be converted to string. Assigning string ' +
"to 'innerHTML' will throw an error if Trusted Types are enforced. " +
"You can try to wrap your svg element inside a div and use 'dangerouslySetInnerHTML' " +
'on the enclosing div instead.',
);
expect(container.innerHTML).toBe('<svg>unsafe html</svg>');
});
});
it('should warn once when rendering script tag in jsx on client', () => {
expect(() => {
ReactDOM.render(<script>alert("I am not executed")</script>, container);
}).toErrorDev(
'Warning: Encountered a script tag while rendering React component. ' +
'Scripts inside React components are never executed when rendering ' +
'on the client. Consider using template tag instead ' +
'(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template).\n' +
' in script (at **)',
);
// check that the warning is printed only once
ReactDOM.render(<script>alert("I am not executed")</script>, container);
});
});
| 35.408907 | 98 | 0.638679 |
Effective-Python-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 './ButtonIcon.css';
export type IconType =
| 'add'
| 'cancel'
| 'clear'
| 'close'
| 'collapsed'
| 'copy'
| 'delete'
| 'down'
| 'editor'
| 'expanded'
| 'export'
| 'filter'
| 'import'
| 'log-data'
| 'more'
| 'next'
| 'parse-hook-names'
| 'previous'
| 'record'
| 'reload'
| 'save'
| 'search'
| 'settings'
| 'error'
| 'suspend'
| 'undo'
| 'up'
| 'view-dom'
| 'view-source';
type Props = {
className?: string,
type: IconType,
};
export default function ButtonIcon({className = '', type}: Props): React.Node {
let pathData = null;
switch (type) {
case 'add':
pathData = PATH_ADD;
break;
case 'cancel':
pathData = PATH_CANCEL;
break;
case 'clear':
pathData = PATH_CLEAR;
break;
case 'close':
pathData = PATH_CLOSE;
break;
case 'collapsed':
pathData = PATH_COLLAPSED;
break;
case 'copy':
pathData = PATH_COPY;
break;
case 'delete':
pathData = PATH_DELETE;
break;
case 'down':
pathData = PATH_DOWN;
break;
case 'editor':
pathData = PATH_EDITOR;
break;
case 'expanded':
pathData = PATH_EXPANDED;
break;
case 'export':
pathData = PATH_EXPORT;
break;
case 'filter':
pathData = PATH_FILTER;
break;
case 'import':
pathData = PATH_IMPORT;
break;
case 'log-data':
pathData = PATH_LOG_DATA;
break;
case 'more':
pathData = PATH_MORE;
break;
case 'next':
pathData = PATH_NEXT;
break;
case 'parse-hook-names':
pathData = PATH_PARSE_HOOK_NAMES;
break;
case 'previous':
pathData = PATH_PREVIOUS;
break;
case 'record':
pathData = PATH_RECORD;
break;
case 'reload':
pathData = PATH_RELOAD;
break;
case 'save':
pathData = PATH_SAVE;
break;
case 'search':
pathData = PATH_SEARCH;
break;
case 'settings':
pathData = PATH_SETTINGS;
break;
case 'error':
pathData = PATH_ERROR;
break;
case 'suspend':
pathData = PATH_SUSPEND;
break;
case 'undo':
pathData = PATH_UNDO;
break;
case 'up':
pathData = PATH_UP;
break;
case 'view-dom':
pathData = PATH_VIEW_DOM;
break;
case 'view-source':
pathData = PATH_VIEW_SOURCE;
break;
default:
console.warn(`Unsupported type "${type}" specified for ButtonIcon`);
break;
}
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={`${styles.ButtonIcon} ${className}`}
width="24"
height="24"
viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" fill="none" />
{typeof pathData === 'string' ? (
<path fill="currentColor" d={pathData} />
) : (
pathData
)}
</svg>
);
}
const PATH_ADD =
'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z';
const PATH_CANCEL = `
M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z
`;
const PATH_CLEAR = `
M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69
16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z
`;
const PATH_CLOSE =
'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z';
const PATH_COLLAPSED = 'M10 17l5-5-5-5v10z';
const PATH_COPY = `
M3 13h2v-2H3v2zm0 4h2v-2H3v2zm2 4v-2H3a2 2 0 0 0 2 2zM3 9h2V7H3v2zm12 12h2v-2h-2v2zm4-18H9a2 2 0 0 0-2
2v10a2 2 0 0 0 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 12H9V5h10v10zm-8 6h2v-2h-2v2zm-4 0h2v-2H7v2z
`;
const PATH_DELETE = `
M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12
13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z
`;
const PATH_DOWN = 'M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z';
const PATH_EXPANDED = 'M7 10l5 5 5-5z';
const PATH_EXPORT = 'M15.82,2.14v7H21l-9,9L3,9.18H8.18v-7ZM3,20.13H21v1.73H3Z';
const PATH_FILTER = 'M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z';
const PATH_IMPORT = 'M8.18,18.13v-7H3l9-8.95,9,9H15.82v7ZM3,20.13H21v1.73H3Z';
const PATH_LOG_DATA = `
M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41
3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04
1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6
8h-4v-2h4v2zm0-4h-4v-2h4v2z
`;
const PATH_MORE = `
M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9
2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z
`;
const PATH_NEXT = 'M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z';
const PATH_PARSE_HOOK_NAMES = (
<g>
<polygon points="20,7 20.94,4.94 23,4 20.94,3.06 20,1 19.06,3.06 17,4 19.06,4.94" />
<polygon points="8.5,7 9.44,4.94 11.5,4 9.44,3.06 8.5,1 7.56,3.06 5.5,4 7.56,4.94" />
<polygon points="20,12.5 19.06,14.56 17,15.5 19.06,16.44 20,18.5 20.94,16.44 23,15.5 20.94,14.56" />
<path d="M17.71,9.12l-2.83-2.83C14.68,6.1,14.43,6,14.17,6c-0.26,0-0.51,0.1-0.71,0.29L2.29,17.46c-0.39,0.39-0.39,1.02,0,1.41 l2.83,2.83C5.32,21.9,5.57,22,5.83,22s0.51-0.1,0.71-0.29l11.17-11.17C18.1,10.15,18.1,9.51,17.71,9.12z M14.17,8.42l1.41,1.41 L14.41,11L13,9.59L14.17,8.42z M5.83,19.59l-1.41-1.41L11.59,11L13,12.41L5.83,19.59z" />
</g>
);
const PATH_PREVIOUS =
'M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z';
const PATH_RECORD = 'M4,12a8,8 0 1,0 16,0a8,8 0 1,0 -16,0';
const PATH_RELOAD = `
M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0
6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0
3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z
`;
const PATH_SAVE = `
M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z
`;
const PATH_SEARCH = `
M8.5,22H3.7l-1.4-1.5V3.8l1.3-1.5h17.2l1,1.5v4.9h-1.3V4.3l-0.4-0.6H4.2L3.6,4.3V20l0.7,0.7h4.2V22z
M23,13.9l-4.6,3.6l4.6,4.6l-1.1,1.1l-4.7-4.4l-3.3,4.4l-3.2-12.3L23,13.9z
`;
const PATH_SETTINGS = `
M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49
1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38
2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11
1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4
1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49
1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5
3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z
`;
const PATH_ERROR =
'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z';
const PATH_SUSPEND = `
M15 1H9v2h6V1zm-4 13h2V8h-2v6zm8.03-6.61l1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97
0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM12 20c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z
`;
const PATH_UNDO = `
M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88
3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z
`;
const PATH_UP = 'M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z';
const PATH_VIEW_DOM = `
M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12
17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3
3-1.34 3-3-1.34-3-3-3z
`;
const PATH_VIEW_SOURCE = `
M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z
`;
const PATH_EDITOR = `
M7 5h10v2h2V3c0-1.1-.9-1.99-2-1.99L7 1c-1.1 0-2 .9-2 2v4h2V5zm8.41 11.59L20 12l-4.59-4.59L14 8.83 17.17 12 14 15.17l1.41 1.42zM10 15.17L6.83 12 10 8.83 8.59 7.41 4 12l4.59 4.59L10 15.17zM17 19H7v-2H5v4c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2v-4h-2v2z
`;
| 30.207885 | 337 | 0.601309 |
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
*/
/* eslint valid-typeof: 0 */
import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
import assign from 'shared/assign';
import getEventCharCode from './getEventCharCode';
type EventInterfaceType = {
[propName: string]: 0 | ((event: {[propName: string]: mixed, ...}) => mixed),
};
function functionThatReturnsTrue() {
return true;
}
function functionThatReturnsFalse() {
return false;
}
// This is intentionally a factory so that we have different returned constructors.
// If we had a single constructor, it would be megamorphic and engines would deopt.
function createSyntheticEvent(Interface: EventInterfaceType) {
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*/
// $FlowFixMe[missing-this-annot]
function SyntheticBaseEvent(
reactName: string | null,
reactEventType: string,
targetInst: Fiber | null,
nativeEvent: {[propName: string]: mixed, ...},
nativeEventTarget: null | EventTarget,
) {
this._reactName = reactName;
this._targetInst = targetInst;
this.type = reactEventType;
this.nativeEvent = nativeEvent;
this.target = nativeEventTarget;
this.currentTarget = null;
for (const propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
const normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
this[propName] = nativeEvent[propName];
}
}
const defaultPrevented =
nativeEvent.defaultPrevented != null
? nativeEvent.defaultPrevented
: nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = functionThatReturnsTrue;
} else {
this.isDefaultPrevented = functionThatReturnsFalse;
}
this.isPropagationStopped = functionThatReturnsFalse;
return this;
}
// $FlowFixMe[prop-missing] found when upgrading Flow
assign(SyntheticBaseEvent.prototype, {
// $FlowFixMe[missing-this-annot]
preventDefault: function () {
this.defaultPrevented = true;
const event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
// $FlowFixMe[illegal-typeof] - flow is not aware of `unknown` in IE
} else if (typeof event.returnValue !== 'unknown') {
event.returnValue = false;
}
this.isDefaultPrevented = functionThatReturnsTrue;
},
// $FlowFixMe[missing-this-annot]
stopPropagation: function () {
const event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
// $FlowFixMe[illegal-typeof] - flow is not aware of `unknown` in IE
} else if (typeof event.cancelBubble !== 'unknown') {
// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found". A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
event.cancelBubble = true;
}
this.isPropagationStopped = functionThatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
// Modern event system doesn't use pooling.
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: functionThatReturnsTrue,
});
return SyntheticBaseEvent;
}
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
const EventInterface = {
eventPhase: 0,
bubbles: 0,
cancelable: 0,
timeStamp: function (event: {[propName: string]: mixed}) {
return event.timeStamp || Date.now();
},
defaultPrevented: 0,
isTrusted: 0,
};
export const SyntheticEvent: $FlowFixMe = createSyntheticEvent(EventInterface);
const UIEventInterface: EventInterfaceType = {
...EventInterface,
view: 0,
detail: 0,
};
export const SyntheticUIEvent: $FlowFixMe =
createSyntheticEvent(UIEventInterface);
let lastMovementX;
let lastMovementY;
let lastMouseEvent;
function updateMouseMovementPolyfillState(event: {[propName: string]: mixed}) {
if (event !== lastMouseEvent) {
if (lastMouseEvent && event.type === 'mousemove') {
// $FlowFixMe[unsafe-arithmetic] assuming this is a number
lastMovementX = event.screenX - lastMouseEvent.screenX;
// $FlowFixMe[unsafe-arithmetic] assuming this is a number
lastMovementY = event.screenY - lastMouseEvent.screenY;
} else {
lastMovementX = 0;
lastMovementY = 0;
}
lastMouseEvent = event;
}
}
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
const MouseEventInterface: EventInterfaceType = {
...UIEventInterface,
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
pageX: 0,
pageY: 0,
ctrlKey: 0,
shiftKey: 0,
altKey: 0,
metaKey: 0,
getModifierState: getEventModifierState,
button: 0,
buttons: 0,
relatedTarget: function (event) {
if (event.relatedTarget === undefined)
return event.fromElement === event.srcElement
? event.toElement
: event.fromElement;
return event.relatedTarget;
},
movementX: function (event) {
if ('movementX' in event) {
return event.movementX;
}
updateMouseMovementPolyfillState(event);
return lastMovementX;
},
movementY: function (event) {
if ('movementY' in event) {
return event.movementY;
}
// Don't need to call updateMouseMovementPolyfillState() here
// because it's guaranteed to have already run when movementX
// was copied.
return lastMovementY;
},
};
export const SyntheticMouseEvent: $FlowFixMe =
createSyntheticEvent(MouseEventInterface);
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
const DragEventInterface: EventInterfaceType = {
...MouseEventInterface,
dataTransfer: 0,
};
export const SyntheticDragEvent: $FlowFixMe =
createSyntheticEvent(DragEventInterface);
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
const FocusEventInterface: EventInterfaceType = {
...UIEventInterface,
relatedTarget: 0,
};
export const SyntheticFocusEvent: $FlowFixMe =
createSyntheticEvent(FocusEventInterface);
/**
* @interface Event
* @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
* @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
*/
const AnimationEventInterface: EventInterfaceType = {
...EventInterface,
animationName: 0,
elapsedTime: 0,
pseudoElement: 0,
};
export const SyntheticAnimationEvent: $FlowFixMe = createSyntheticEvent(
AnimationEventInterface,
);
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
const ClipboardEventInterface: EventInterfaceType = {
...EventInterface,
clipboardData: function (event) {
return 'clipboardData' in event
? event.clipboardData
: window.clipboardData;
},
};
export const SyntheticClipboardEvent: $FlowFixMe = createSyntheticEvent(
ClipboardEventInterface,
);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
const CompositionEventInterface: EventInterfaceType = {
...EventInterface,
data: 0,
};
export const SyntheticCompositionEvent: $FlowFixMe = createSyntheticEvent(
CompositionEventInterface,
);
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
// Happens to share the same list for now.
export const SyntheticInputEvent = SyntheticCompositionEvent;
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
const normalizeKey = {
Esc: 'Escape',
Spacebar: ' ',
Left: 'ArrowLeft',
Up: 'ArrowUp',
Right: 'ArrowRight',
Down: 'ArrowDown',
Del: 'Delete',
Win: 'OS',
Menu: 'ContextMenu',
Apps: 'ContextMenu',
Scroll: 'ScrollLock',
MozPrintableKey: 'Unidentified',
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
const translateToKey = {
'8': 'Backspace',
'9': 'Tab',
'12': 'Clear',
'13': 'Enter',
'16': 'Shift',
'17': 'Control',
'18': 'Alt',
'19': 'Pause',
'20': 'CapsLock',
'27': 'Escape',
'32': ' ',
'33': 'PageUp',
'34': 'PageDown',
'35': 'End',
'36': 'Home',
'37': 'ArrowLeft',
'38': 'ArrowUp',
'39': 'ArrowRight',
'40': 'ArrowDown',
'45': 'Insert',
'46': 'Delete',
'112': 'F1',
'113': 'F2',
'114': 'F3',
'115': 'F4',
'116': 'F5',
'117': 'F6',
'118': 'F7',
'119': 'F8',
'120': 'F9',
'121': 'F10',
'122': 'F11',
'123': 'F12',
'144': 'NumLock',
'145': 'ScrollLock',
'224': 'Meta',
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent: {[propName: string]: mixed}) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
const key =
// $FlowFixMe[invalid-computed-prop] unable to index with a `mixed` value
normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
const charCode = getEventCharCode(
// $FlowFixMe[incompatible-call] unable to narrow to `KeyboardEvent`
nativeEvent,
);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
// $FlowFixMe[invalid-computed-prop] unable to index with a `mixed` value
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
const modifierKeyToProp = {
Alt: 'altKey',
Control: 'ctrlKey',
Meta: 'metaKey',
Shift: 'shiftKey',
};
// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
// getModifierState. If getModifierState is not supported, we map it to a set of
// modifier keys exposed by the event. In this case, Lock-keys are not supported.
// $FlowFixMe[missing-local-annot]
// $FlowFixMe[missing-this-annot]
function modifierStateGetter(keyArg) {
const syntheticEvent = this;
const nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
const keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent: {[propName: string]: mixed}) {
return modifierStateGetter;
}
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
const KeyboardEventInterface = {
...UIEventInterface,
key: getEventKey,
code: 0,
location: 0,
ctrlKey: 0,
shiftKey: 0,
altKey: 0,
metaKey: 0,
repeat: 0,
locale: 0,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event: {[propName: string]: mixed}) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(
// $FlowFixMe[incompatible-call] unable to narrow to `KeyboardEvent`
event,
);
}
return 0;
},
keyCode: function (event: {[propName: string]: mixed}) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event: {[propName: string]: mixed}) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(
// $FlowFixMe[incompatible-call] unable to narrow to `KeyboardEvent`
event,
);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
};
export const SyntheticKeyboardEvent: $FlowFixMe = createSyntheticEvent(
KeyboardEventInterface,
);
/**
* @interface PointerEvent
* @see http://www.w3.org/TR/pointerevents/
*/
const PointerEventInterface = {
...MouseEventInterface,
pointerId: 0,
width: 0,
height: 0,
pressure: 0,
tangentialPressure: 0,
tiltX: 0,
tiltY: 0,
twist: 0,
pointerType: 0,
isPrimary: 0,
};
export const SyntheticPointerEvent: $FlowFixMe = createSyntheticEvent(
PointerEventInterface,
);
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
const TouchEventInterface = {
...UIEventInterface,
touches: 0,
targetTouches: 0,
changedTouches: 0,
altKey: 0,
metaKey: 0,
ctrlKey: 0,
shiftKey: 0,
getModifierState: getEventModifierState,
};
export const SyntheticTouchEvent: $FlowFixMe =
createSyntheticEvent(TouchEventInterface);
/**
* @interface Event
* @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
* @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
*/
const TransitionEventInterface = {
...EventInterface,
propertyName: 0,
elapsedTime: 0,
pseudoElement: 0,
};
export const SyntheticTransitionEvent: $FlowFixMe = createSyntheticEvent(
TransitionEventInterface,
);
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
const WheelEventInterface = {
...MouseEventInterface,
deltaX(event: {[propName: string]: mixed}) {
return 'deltaX' in event
? event.deltaX
: // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event
? // $FlowFixMe[unsafe-arithmetic] assuming this is a number
-event.wheelDeltaX
: 0;
},
deltaY(event: {[propName: string]: mixed}) {
return 'deltaY' in event
? event.deltaY
: // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event
? // $FlowFixMe[unsafe-arithmetic] assuming this is a number
-event.wheelDeltaY
: // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event
? // $FlowFixMe[unsafe-arithmetic] assuming this is a number
-event.wheelDelta
: 0;
},
deltaZ: 0,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: 0,
};
export const SyntheticWheelEvent: $FlowFixMe =
createSyntheticEvent(WheelEventInterface);
| 27.830252 | 83 | 0.675858 |
null | 'use strict';
module.exports = {
env: {
commonjs: true,
browser: true,
},
globals: {
// ES6
BigInt: 'readonly',
Map: 'readonly',
Set: 'readonly',
Symbol: 'readonly',
Proxy: 'readonly',
WeakMap: 'readonly',
WeakSet: 'readonly',
Int8Array: 'readonly',
Uint8Array: 'readonly',
Uint8ClampedArray: 'readonly',
Int16Array: 'readonly',
Uint16Array: 'readonly',
Int32Array: 'readonly',
Uint32Array: 'readonly',
Float32Array: 'readonly',
Float64Array: 'readonly',
BigInt64Array: 'readonly',
BigUint64Array: 'readonly',
DataView: 'readonly',
ArrayBuffer: 'readonly',
Reflect: 'readonly',
globalThis: 'readonly',
FinalizationRegistry: 'readonly',
// Vendor specific
MSApp: 'readonly',
__REACT_DEVTOOLS_GLOBAL_HOOK__: 'readonly',
// FB
__DEV__: 'readonly',
// Fabric. See https://github.com/facebook/react/pull/15490
// for more information
nativeFabricUIManager: 'readonly',
// Trusted Types
trustedTypes: 'readonly',
// RN supports this
setImmediate: 'readonly',
// Scheduler profiling
TaskController: 'readonly',
reportError: 'readonly',
AggregateError: 'readonly',
// Temp
AsyncLocalStorage: 'readonly',
async_hooks: 'readonly',
// jest
jest: 'readonly',
// act
IS_REACT_ACT_ENVIRONMENT: 'readonly',
},
parserOptions: {
ecmaVersion: 5,
sourceType: 'script',
},
rules: {
'no-undef': 'error',
'no-shadow-restricted-names': 'error',
},
// These plugins aren't used, but eslint complains if an eslint-ignore comment
// references unused plugins. An alternate approach could be to strip
// eslint-ignore comments as part of the build.
plugins: ['ft-flow', 'jest', 'no-for-of-loops', 'react', 'react-internal'],
};
| 22.679487 | 80 | 0.626219 |
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 * as React from 'react';
import {useRef, useState} from 'react';
export default function App(): React.Node {
return <List />;
}
function List() {
const [items, setItems] = useState(['one', 'two', 'three']);
const inputRef = useRef(null);
const addItem = () => {
const input = ((inputRef.current: any): HTMLInputElement);
const text = input.value;
input.value = '';
if (text) {
setItems([...items, text]);
}
};
return (
<>
<input ref={inputRef} data-testname="AddItemInput" />
<button data-testname="AddItemButton" onClick={addItem}>
Add Item
</button>
<ul data-testname="List">
{items.map((label, index) => (
<ListItem key={index} label={label} />
))}
</ul>
</>
);
}
// $FlowFixMe[missing-local-annot]
function ListItem({label}) {
return <li data-testname="ListItem">{label}</li>;
}
| 21.3 | 66 | 0.59605 |
owtf | import Fixture from '../../Fixture';
const React = window.React;
class PasswordTestCase extends React.Component {
state = {value: ''};
onChange = event => {
this.setState({value: event.target.value});
};
render() {
return (
<Fixture>
<div>{this.props.children}</div>
<div className="control-box">
<fieldset>
<legend>Controlled</legend>
<input
type="password"
value={this.state.value}
onChange={this.onChange}
/>
<span className="hint">
{' '}
Value: {JSON.stringify(this.state.value)}
</span>
</fieldset>
<fieldset>
<legend>Uncontrolled</legend>
<input type="password" defaultValue="" />
</fieldset>
</div>
</Fixture>
);
}
}
export default PasswordTestCase;
| 21.875 | 55 | 0.50547 |
Python-Penetration-Testing-for-Developers | let PropTypes;
let React;
let ReactTestRenderer;
let Scheduler;
let ReactFeatureFlags;
let Suspense;
let lazy;
let waitFor;
let waitForAll;
let waitForThrow;
let assertLog;
let act;
let fakeModuleCache;
function normalizeCodeLocInfo(str) {
return (
str &&
str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) {
return '\n in ' + name + ' (at **)';
})
);
}
describe('ReactLazy', () => {
beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
PropTypes = require('prop-types');
React = require('react');
Suspense = React.Suspense;
lazy = React.lazy;
ReactTestRenderer = require('react-test-renderer');
Scheduler = require('scheduler');
const InternalTestUtils = require('internal-test-utils');
waitFor = InternalTestUtils.waitFor;
waitForAll = InternalTestUtils.waitForAll;
waitForThrow = InternalTestUtils.waitForThrow;
assertLog = InternalTestUtils.assertLog;
act = InternalTestUtils.act;
fakeModuleCache = new Map();
});
function Text(props) {
Scheduler.log(props.text);
return props.text;
}
async function fakeImport(Component) {
const record = fakeModuleCache.get(Component);
if (record === undefined) {
const newRecord = {
status: 'pending',
value: {default: Component},
pings: [],
then(ping) {
switch (newRecord.status) {
case 'pending': {
newRecord.pings.push(ping);
return;
}
case 'resolved': {
ping(newRecord.value);
return;
}
case 'rejected': {
throw newRecord.value;
}
}
},
};
fakeModuleCache.set(Component, newRecord);
return newRecord;
}
return record;
}
function resolveFakeImport(moduleName) {
const record = fakeModuleCache.get(moduleName);
if (record === undefined) {
throw new Error('Module not found');
}
if (record.status !== 'pending') {
throw new Error('Module already resolved');
}
record.status = 'resolved';
record.pings.forEach(ping => ping(record.value));
}
it('suspends until module has loaded', async () => {
const LazyText = lazy(() => fakeImport(Text));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('Hi');
await act(() => resolveFakeImport(Text));
assertLog(['Hi']);
expect(root).toMatchRenderedOutput('Hi');
// Should not suspend on update
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi again" />
</Suspense>,
);
await waitForAll(['Hi again']);
expect(root).toMatchRenderedOutput('Hi again');
});
it('can resolve synchronously without suspending', async () => {
const LazyText = lazy(() => ({
then(cb) {
cb({default: Text});
},
}));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>,
);
assertLog(['Hi']);
expect(root).toMatchRenderedOutput('Hi');
});
it('can reject synchronously without suspending', async () => {
const LazyText = lazy(() => ({
then(resolve, reject) {
reject(new Error('oh no'));
},
}));
class ErrorBoundary extends React.Component {
state = {};
static getDerivedStateFromError(error) {
return {message: error.message};
}
render() {
return this.state.message
? `Error: ${this.state.message}`
: this.props.children;
}
}
const root = ReactTestRenderer.create(
<ErrorBoundary>
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>
</ErrorBoundary>,
);
assertLog([]);
expect(root).toMatchRenderedOutput('Error: oh no');
});
it('multiple lazy components', async () => {
function Foo() {
return <Text text="Foo" />;
}
function Bar() {
return <Text text="Bar" />;
}
const LazyFoo = lazy(() => fakeImport(Foo));
const LazyBar = lazy(() => fakeImport(Bar));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyFoo />
<LazyBar />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('FooBar');
await resolveFakeImport(Foo);
await waitForAll(['Foo']);
expect(root).not.toMatchRenderedOutput('FooBar');
await act(() => resolveFakeImport(Bar));
assertLog(['Foo', 'Bar']);
expect(root).toMatchRenderedOutput('FooBar');
});
it('does not support arbitrary promises, only module objects', async () => {
spyOnDev(console, 'error').mockImplementation(() => {});
const LazyText = lazy(async () => Text);
const root = ReactTestRenderer.create(null, {
isConcurrent: true,
});
let error;
try {
await act(() => {
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>,
);
});
} catch (e) {
error = e;
}
expect(error.message).toMatch('Element type is invalid');
assertLog(['Loading...']);
expect(root).not.toMatchRenderedOutput('Hi');
if (__DEV__) {
expect(console.error).toHaveBeenCalledTimes(3);
expect(console.error.mock.calls[0][0]).toContain(
'Expected the result of a dynamic import() call',
);
}
});
it('throws if promise rejects', async () => {
const networkError = new Error('Bad network');
const LazyText = lazy(async () => {
throw networkError;
});
const root = ReactTestRenderer.create(null, {
isConcurrent: true,
});
let error;
try {
await act(() => {
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>,
);
});
} catch (e) {
error = e;
}
expect(error).toBe(networkError);
assertLog(['Loading...']);
expect(root).not.toMatchRenderedOutput('Hi');
});
it('mount and reorder', async () => {
class Child extends React.Component {
componentDidMount() {
Scheduler.log('Did mount: ' + this.props.label);
}
componentDidUpdate() {
Scheduler.log('Did update: ' + this.props.label);
}
render() {
return <Text text={this.props.label} />;
}
}
const LazyChildA = lazy(() => {
Scheduler.log('Suspend! [LazyChildA]');
return fakeImport(Child);
});
const LazyChildB = lazy(() => {
Scheduler.log('Suspend! [LazyChildB]');
return fakeImport(Child);
});
function Parent({swap}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{swap
? [
<LazyChildB key="B" label="B" />,
<LazyChildA key="A" label="A" />,
]
: [
<LazyChildA key="A" label="A" />,
<LazyChildB key="B" label="B" />,
]}
</Suspense>
);
}
const root = ReactTestRenderer.create(<Parent swap={false} />, {
isConcurrent: true,
});
await waitForAll(['Suspend! [LazyChildA]', 'Loading...']);
expect(root).not.toMatchRenderedOutput('AB');
await act(async () => {
await resolveFakeImport(Child);
// B suspends even though it happens to share the same import as A.
// TODO: React.lazy should implement the `status` and `value` fields, so
// we can unwrap the result synchronously if it already loaded. Like `use`.
await waitFor(['A', 'Suspend! [LazyChildB]']);
});
assertLog(['A', 'B', 'Did mount: A', 'Did mount: B']);
expect(root).toMatchRenderedOutput('AB');
// Swap the position of A and B
root.update(<Parent swap={true} />);
await waitForAll(['B', 'A', 'Did update: B', 'Did update: A']);
expect(root).toMatchRenderedOutput('BA');
});
it('resolves defaultProps, on mount and update', async () => {
function T(props) {
return <Text {...props} />;
}
T.defaultProps = {text: 'Hi'};
const LazyText = lazy(() => fakeImport(T));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('Hi');
await expect(async () => {
await act(() => resolveFakeImport(T));
assertLog(['Hi']);
}).toErrorDev(
'Warning: T: Support for defaultProps ' +
'will be removed from function components in a future major ' +
'release. Use JavaScript default parameters instead.',
);
expect(root).toMatchRenderedOutput('Hi');
T.defaultProps = {text: 'Hi again'};
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText />
</Suspense>,
);
await waitForAll(['Hi again']);
expect(root).toMatchRenderedOutput('Hi again');
});
it('resolves defaultProps without breaking memoization', async () => {
function LazyImpl(props) {
Scheduler.log('Lazy');
return (
<>
<Text text={props.siblingText} />
{props.children}
</>
);
}
LazyImpl.defaultProps = {siblingText: 'Sibling'};
const Lazy = lazy(() => fakeImport(LazyImpl));
class Stateful extends React.Component {
state = {text: 'A'};
render() {
return <Text text={this.state.text} />;
}
}
const stateful = React.createRef(null);
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<Lazy>
<Stateful ref={stateful} />
</Lazy>
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('SiblingA');
await expect(async () => {
await act(() => resolveFakeImport(LazyImpl));
assertLog(['Lazy', 'Sibling', 'A']);
}).toErrorDev(
'Warning: LazyImpl: Support for defaultProps ' +
'will be removed from function components in a future major ' +
'release. Use JavaScript default parameters instead.',
);
expect(root).toMatchRenderedOutput('SiblingA');
// Lazy should not re-render
stateful.current.setState({text: 'B'});
await waitForAll(['B']);
expect(root).toMatchRenderedOutput('SiblingB');
});
it('resolves defaultProps without breaking bailout due to unchanged props and state, #17151', async () => {
class LazyImpl extends React.Component {
static defaultProps = {value: 0};
render() {
const text = `${this.props.label}: ${this.props.value}`;
return <Text text={text} />;
}
}
const Lazy = lazy(() => fakeImport(LazyImpl));
const instance1 = React.createRef(null);
const instance2 = React.createRef(null);
const root = ReactTestRenderer.create(
<>
<LazyImpl ref={instance1} label="Not lazy" />
<Suspense fallback={<Text text="Loading..." />}>
<Lazy ref={instance2} label="Lazy" />
</Suspense>
</>,
{
isConcurrent: true,
},
);
await waitForAll(['Not lazy: 0', 'Loading...']);
expect(root).not.toMatchRenderedOutput('Not lazy: 0Lazy: 0');
await act(() => resolveFakeImport(LazyImpl));
assertLog(['Lazy: 0']);
expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0');
// Should bailout due to unchanged props and state
instance1.current.setState(null);
await waitForAll([]);
expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0');
// Should bailout due to unchanged props and state
instance2.current.setState(null);
await waitForAll([]);
expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0');
});
it('resolves defaultProps without breaking bailout in PureComponent, #17151', async () => {
class LazyImpl extends React.PureComponent {
static defaultProps = {value: 0};
state = {};
render() {
const text = `${this.props.label}: ${this.props.value}`;
return <Text text={text} />;
}
}
const Lazy = lazy(() => fakeImport(LazyImpl));
const instance1 = React.createRef(null);
const instance2 = React.createRef(null);
const root = ReactTestRenderer.create(
<>
<LazyImpl ref={instance1} label="Not lazy" />
<Suspense fallback={<Text text="Loading..." />}>
<Lazy ref={instance2} label="Lazy" />
</Suspense>
</>,
{
isConcurrent: true,
},
);
await waitForAll(['Not lazy: 0', 'Loading...']);
expect(root).not.toMatchRenderedOutput('Not lazy: 0Lazy: 0');
await act(() => resolveFakeImport(LazyImpl));
assertLog(['Lazy: 0']);
expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0');
// Should bailout due to shallow equal props and state
instance1.current.setState({});
await waitForAll([]);
expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0');
// Should bailout due to shallow equal props and state
instance2.current.setState({});
await waitForAll([]);
expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0');
});
it('sets defaultProps for modern lifecycles', async () => {
class C extends React.Component {
static defaultProps = {text: 'A'};
state = {};
static getDerivedStateFromProps(props) {
Scheduler.log(`getDerivedStateFromProps: ${props.text}`);
return null;
}
constructor(props) {
super(props);
Scheduler.log(`constructor: ${this.props.text}`);
}
componentDidMount() {
Scheduler.log(`componentDidMount: ${this.props.text}`);
}
componentDidUpdate(prevProps) {
Scheduler.log(
`componentDidUpdate: ${prevProps.text} -> ${this.props.text}`,
);
}
componentWillUnmount() {
Scheduler.log(`componentWillUnmount: ${this.props.text}`);
}
shouldComponentUpdate(nextProps) {
Scheduler.log(
`shouldComponentUpdate: ${this.props.text} -> ${nextProps.text}`,
);
return true;
}
getSnapshotBeforeUpdate(prevProps) {
Scheduler.log(
`getSnapshotBeforeUpdate: ${prevProps.text} -> ${this.props.text}`,
);
return null;
}
render() {
return <Text text={this.props.text + this.props.num} />;
}
}
const LazyClass = lazy(() => fakeImport(C));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyClass num={1} />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('A1');
await act(() => resolveFakeImport(C));
assertLog([
'constructor: A',
'getDerivedStateFromProps: A',
'A1',
'componentDidMount: A',
]);
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyClass num={2} />
</Suspense>,
);
await waitForAll([
'getDerivedStateFromProps: A',
'shouldComponentUpdate: A -> A',
'A2',
'getSnapshotBeforeUpdate: A -> A',
'componentDidUpdate: A -> A',
]);
expect(root).toMatchRenderedOutput('A2');
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyClass num={3} />
</Suspense>,
);
await waitForAll([
'getDerivedStateFromProps: A',
'shouldComponentUpdate: A -> A',
'A3',
'getSnapshotBeforeUpdate: A -> A',
'componentDidUpdate: A -> A',
]);
expect(root).toMatchRenderedOutput('A3');
});
it('sets defaultProps for legacy lifecycles', async () => {
class C extends React.Component {
static defaultProps = {text: 'A'};
state = {};
UNSAFE_componentWillMount() {
Scheduler.log(`UNSAFE_componentWillMount: ${this.props.text}`);
}
UNSAFE_componentWillUpdate(nextProps) {
Scheduler.log(
`UNSAFE_componentWillUpdate: ${this.props.text} -> ${nextProps.text}`,
);
}
UNSAFE_componentWillReceiveProps(nextProps) {
Scheduler.log(
`UNSAFE_componentWillReceiveProps: ${this.props.text} -> ${nextProps.text}`,
);
}
render() {
return <Text text={this.props.text + this.props.num} />;
}
}
const LazyClass = lazy(() => fakeImport(C));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyClass num={1} />
</Suspense>,
);
assertLog(['Loading...']);
await waitForAll([]);
expect(root).toMatchRenderedOutput('Loading...');
await resolveFakeImport(C);
assertLog([]);
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyClass num={2} />
</Suspense>,
);
assertLog(['UNSAFE_componentWillMount: A', 'A2']);
expect(root).toMatchRenderedOutput('A2');
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyClass num={3} />
</Suspense>,
);
assertLog([
'UNSAFE_componentWillReceiveProps: A -> A',
'UNSAFE_componentWillUpdate: A -> A',
'A3',
]);
await waitForAll([]);
expect(root).toMatchRenderedOutput('A3');
});
it('resolves defaultProps on the outer wrapper but warns', async () => {
function T(props) {
Scheduler.log(props.inner + ' ' + props.outer);
return props.inner + ' ' + props.outer;
}
T.defaultProps = {inner: 'Hi'};
const LazyText = lazy(() => fakeImport(T));
expect(() => {
LazyText.defaultProps = {outer: 'Bye'};
}).toErrorDev(
'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.',
{withoutStack: true},
);
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('Hi Bye');
await expect(async () => {
await act(() => resolveFakeImport(T));
assertLog(['Hi Bye']);
}).toErrorDev(
'Warning: T: Support for defaultProps ' +
'will be removed from function components in a future major ' +
'release. Use JavaScript default parameters instead.',
);
expect(root).toMatchRenderedOutput('Hi Bye');
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText outer="World" />
</Suspense>,
);
await waitForAll(['Hi World']);
expect(root).toMatchRenderedOutput('Hi World');
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText inner="Friends" />
</Suspense>,
);
await waitForAll(['Friends Bye']);
expect(root).toMatchRenderedOutput('Friends Bye');
});
it('throws with a useful error when wrapping invalid type with lazy()', async () => {
const BadLazy = lazy(() => fakeImport(42));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<BadLazy />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
await resolveFakeImport(42);
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<BadLazy />
</Suspense>,
);
await waitForThrow(
'Element type is invalid. Received a promise that resolves to: 42. ' +
'Lazy element type must resolve to a class or function.',
);
});
it('throws with a useful error when wrapping lazy() multiple times', async () => {
const Lazy1 = lazy(() => fakeImport(Text));
const Lazy2 = lazy(() => fakeImport(Lazy1));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<Lazy2 text="Hello" />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('Hello');
await resolveFakeImport(Lazy1);
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<Lazy2 text="Hello" />
</Suspense>,
);
await waitForThrow(
'Element type is invalid. Received a promise that resolves to: [object Object]. ' +
'Lazy element type must resolve to a class or function.' +
(__DEV__
? ' Did you wrap a component in React.lazy() more than once?'
: ''),
);
});
it('warns about defining propTypes on the outer wrapper', () => {
const LazyText = lazy(() => fakeImport(Text));
expect(() => {
LazyText.propTypes = {hello: () => {}};
}).toErrorDev(
'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.',
{withoutStack: true},
);
});
async function verifyInnerPropTypesAreChecked(
Add,
shouldWarnAboutFunctionDefaultProps,
shouldWarnAboutMemoDefaultProps,
) {
const LazyAdd = lazy(() => fakeImport(Add));
expect(() => {
LazyAdd.propTypes = {};
}).toErrorDev(
'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.',
{withoutStack: true},
);
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd inner="2" outer="2" />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('22');
// Mount
await expect(async () => {
await act(() => resolveFakeImport(Add));
}).toErrorDev(
shouldWarnAboutFunctionDefaultProps
? [
'Add: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.',
'Invalid prop `inner` of type `string` supplied to `Add`, expected `number`.',
]
: shouldWarnAboutMemoDefaultProps
? [
'Add: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.',
'Invalid prop `inner` of type `string` supplied to `Add`, expected `number`.',
]
: [
'Invalid prop `inner` of type `string` supplied to `Add`, expected `number`.',
],
);
expect(root).toMatchRenderedOutput('22');
// Update
await expect(async () => {
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd inner={false} outer={false} />
</Suspense>,
);
await waitForAll([]);
}).toErrorDev(
'Invalid prop `inner` of type `boolean` supplied to `Add`, expected `number`.',
);
expect(root).toMatchRenderedOutput('0');
}
// Note: all "with defaultProps" tests below also verify defaultProps works as expected.
// If we ever delete or move propTypes-related tests, make sure not to delete these.
it('respects propTypes on function component with defaultProps', async () => {
function Add(props) {
expect(props.innerWithDefault).toBe(42);
return props.inner + props.outer;
}
Add.propTypes = {
inner: PropTypes.number.isRequired,
innerWithDefault: PropTypes.number.isRequired,
};
Add.defaultProps = {
innerWithDefault: 42,
};
await verifyInnerPropTypesAreChecked(Add, true);
});
it('respects propTypes on function component without defaultProps', async () => {
function Add(props) {
return props.inner + props.outer;
}
Add.propTypes = {
inner: PropTypes.number.isRequired,
};
await verifyInnerPropTypesAreChecked(Add);
});
it('respects propTypes on class component with defaultProps', async () => {
class Add extends React.Component {
render() {
expect(this.props.innerWithDefault).toBe(42);
return this.props.inner + this.props.outer;
}
}
Add.propTypes = {
inner: PropTypes.number.isRequired,
innerWithDefault: PropTypes.number.isRequired,
};
Add.defaultProps = {
innerWithDefault: 42,
};
await verifyInnerPropTypesAreChecked(Add);
});
it('respects propTypes on class component without defaultProps', async () => {
class Add extends React.Component {
render() {
return this.props.inner + this.props.outer;
}
}
Add.propTypes = {
inner: PropTypes.number.isRequired,
};
await verifyInnerPropTypesAreChecked(Add);
});
it('respects propTypes on forwardRef component with defaultProps', async () => {
const Add = React.forwardRef((props, ref) => {
expect(props.innerWithDefault).toBe(42);
return props.inner + props.outer;
});
Add.displayName = 'Add';
Add.propTypes = {
inner: PropTypes.number.isRequired,
innerWithDefault: PropTypes.number.isRequired,
};
Add.defaultProps = {
innerWithDefault: 42,
};
await verifyInnerPropTypesAreChecked(Add);
});
it('respects propTypes on forwardRef component without defaultProps', async () => {
const Add = React.forwardRef((props, ref) => {
return props.inner + props.outer;
});
Add.displayName = 'Add';
Add.propTypes = {
inner: PropTypes.number.isRequired,
};
await verifyInnerPropTypesAreChecked(Add);
});
it('respects propTypes on outer memo component with defaultProps', async () => {
let Add = props => {
expect(props.innerWithDefault).toBe(42);
return props.inner + props.outer;
};
Add = React.memo(Add);
Add.propTypes = {
inner: PropTypes.number.isRequired,
innerWithDefault: PropTypes.number.isRequired,
};
Add.defaultProps = {
innerWithDefault: 42,
};
await verifyInnerPropTypesAreChecked(Add, false, true);
});
it('respects propTypes on outer memo component without defaultProps', async () => {
let Add = props => {
return props.inner + props.outer;
};
Add = React.memo(Add);
Add.propTypes = {
inner: PropTypes.number.isRequired,
};
await verifyInnerPropTypesAreChecked(Add);
});
it('respects propTypes on inner memo component with defaultProps', async () => {
const Add = props => {
expect(props.innerWithDefault).toBe(42);
return props.inner + props.outer;
};
Add.displayName = 'Add';
Add.propTypes = {
inner: PropTypes.number.isRequired,
innerWithDefault: PropTypes.number.isRequired,
};
Add.defaultProps = {
innerWithDefault: 42,
};
await verifyInnerPropTypesAreChecked(React.memo(Add), true);
});
it('respects propTypes on inner memo component without defaultProps', async () => {
const Add = props => {
return props.inner + props.outer;
};
Add.displayName = 'Add';
Add.propTypes = {
inner: PropTypes.number.isRequired,
};
await verifyInnerPropTypesAreChecked(React.memo(Add));
});
it('uses outer resolved props for validating propTypes on memo', async () => {
let T = props => {
return <Text text={props.text} />;
};
T.defaultProps = {
text: 'Inner default text',
};
T = React.memo(T);
T.propTypes = {
// Should not be satisfied by the *inner* defaultProps.
text: PropTypes.string.isRequired,
};
const LazyText = lazy(() => fakeImport(T));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('Inner default text');
// Mount
await expect(async () => {
await act(() => resolveFakeImport(T));
assertLog(['Inner default text']);
}).toErrorDev([
'T: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.',
'The prop `text` is marked as required in `T`, but its value is `undefined`',
]);
expect(root).toMatchRenderedOutput('Inner default text');
// Update
await expect(async () => {
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text={null} />
</Suspense>,
);
await waitForAll([null]);
}).toErrorDev(
'The prop `text` is marked as required in `T`, but its value is `null`',
);
expect(root).toMatchRenderedOutput(null);
});
it('includes lazy-loaded component in warning stack', async () => {
const Foo = props => <div>{[<Text text="A" />, <Text text="B" />]}</div>;
const LazyFoo = lazy(() => {
Scheduler.log('Started loading');
return fakeImport(Foo);
});
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyFoo />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Started loading', 'Loading...']);
expect(root).not.toMatchRenderedOutput(<div>AB</div>);
await expect(async () => {
await act(() => resolveFakeImport(Foo));
assertLog(['A', 'B']);
}).toErrorDev(' in Text (at **)\n' + ' in Foo (at **)');
expect(root).toMatchRenderedOutput(<div>AB</div>);
});
it('supports class and forwardRef components', async () => {
class Foo extends React.Component {
render() {
return <Text text="Foo" />;
}
}
const LazyClass = lazy(() => {
return fakeImport(Foo);
});
class Bar extends React.Component {
render() {
return <Text text="Bar" />;
}
}
const ForwardRefBar = React.forwardRef((props, ref) => {
Scheduler.log('forwardRef');
return <Bar ref={ref} />;
});
const LazyForwardRef = lazy(() => {
return fakeImport(ForwardRefBar);
});
const ref = React.createRef();
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyClass />
<LazyForwardRef ref={ref} />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('FooBar');
expect(ref.current).toBe(null);
await act(() => resolveFakeImport(Foo));
assertLog(['Foo']);
await act(() => resolveFakeImport(ForwardRefBar));
assertLog(['Foo', 'forwardRef', 'Bar']);
expect(root).toMatchRenderedOutput('FooBar');
expect(ref.current).not.toBe(null);
});
// Regression test for #14310
it('supports defaultProps defined on the memo() return value', async () => {
const Add = React.memo(props => {
return props.inner + props.outer;
});
Add.defaultProps = {
inner: 2,
};
const LazyAdd = lazy(() => fakeImport(Add));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={2} />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('4');
// Mount
await expect(async () => {
await act(() => resolveFakeImport(Add));
}).toErrorDev(
'Unknown: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.',
);
expect(root).toMatchRenderedOutput('4');
// Update (shallowly equal)
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={2} />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('4');
// Update
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={3} />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('5');
// Update (shallowly equal)
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={3} />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('5');
// Update (explicit props)
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={1} inner={1} />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('2');
// Update (explicit props, shallowly equal)
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={1} inner={1} />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('2');
// Update
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={1} />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('3');
});
it('merges defaultProps in the correct order', async () => {
let Add = React.memo(props => {
return props.inner + props.outer;
});
Add.defaultProps = {
inner: 100,
};
Add = React.memo(Add);
Add.defaultProps = {
inner: 2,
outer: 0,
};
const LazyAdd = lazy(() => fakeImport(Add));
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={2} />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
expect(root).not.toMatchRenderedOutput('4');
// Mount
await expect(async () => {
await act(() => resolveFakeImport(Add));
}).toErrorDev([
'Memo: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.',
'Unknown: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.',
]);
expect(root).toMatchRenderedOutput('4');
// Update
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd outer={3} />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('5');
// Update
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<LazyAdd />
</Suspense>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput('2');
});
it('warns about ref on functions for lazy-loaded components', async () => {
const Foo = props => <div />;
const LazyFoo = lazy(() => {
return fakeImport(Foo);
});
const ref = React.createRef();
ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyFoo ref={ref} />
</Suspense>,
{
isConcurrent: true,
},
);
await waitForAll(['Loading...']);
await resolveFakeImport(Foo);
await expect(async () => {
await waitForAll([]);
}).toErrorDev('Function components cannot be given refs');
});
it('should error with a component stack naming the resolved component', async () => {
let componentStackMessage;
function ResolvedText() {
throw new Error('oh no');
}
const LazyText = lazy(() => fakeImport(ResolvedText));
class ErrorBoundary extends React.Component {
state = {error: null};
componentDidCatch(error, errMessage) {
componentStackMessage = normalizeCodeLocInfo(errMessage.componentStack);
this.setState({
error,
});
}
render() {
return this.state.error ? null : this.props.children;
}
}
ReactTestRenderer.create(
<ErrorBoundary>
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>
</ErrorBoundary>,
{isConcurrent: true},
);
await waitForAll(['Loading...']);
await act(() => resolveFakeImport(ResolvedText));
assertLog([]);
expect(componentStackMessage).toContain('in ResolvedText');
});
it('should error with a component stack containing Lazy if unresolved', () => {
let componentStackMessage;
const LazyText = lazy(() => ({
then(resolve, reject) {
reject(new Error('oh no'));
},
}));
class ErrorBoundary extends React.Component {
state = {error: null};
componentDidCatch(error, errMessage) {
componentStackMessage = normalizeCodeLocInfo(errMessage.componentStack);
this.setState({
error,
});
}
render() {
return this.state.error ? null : this.props.children;
}
}
ReactTestRenderer.create(
<ErrorBoundary>
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>
</ErrorBoundary>,
);
assertLog([]);
expect(componentStackMessage).toContain('in Lazy');
});
it('mount and reorder lazy types', async () => {
class Child extends React.Component {
componentWillUnmount() {
Scheduler.log('Did unmount: ' + this.props.label);
}
componentDidMount() {
Scheduler.log('Did mount: ' + this.props.label);
}
componentDidUpdate() {
Scheduler.log('Did update: ' + this.props.label);
}
render() {
return <Text text={this.props.label} />;
}
}
function ChildA({lowerCase}) {
return <Child label={lowerCase ? 'a' : 'A'} />;
}
function ChildB({lowerCase}) {
return <Child label={lowerCase ? 'b' : 'B'} />;
}
const LazyChildA = lazy(() => {
Scheduler.log('Init A');
return fakeImport(ChildA);
});
const LazyChildB = lazy(() => {
Scheduler.log('Init B');
return fakeImport(ChildB);
});
const LazyChildA2 = lazy(() => {
Scheduler.log('Init A2');
return fakeImport(ChildA);
});
let resolveB2;
const LazyChildB2 = lazy(() => {
Scheduler.log('Init B2');
return new Promise(r => {
resolveB2 = r;
});
});
function Parent({swap}) {
return (
<Suspense fallback={<Text text="Outer..." />}>
<Suspense fallback={<Text text="Loading..." />}>
{swap
? [
<LazyChildB2 key="B" lowerCase={true} />,
<LazyChildA2 key="A" lowerCase={true} />,
]
: [<LazyChildA key="A" />, <LazyChildB key="B" />]}
</Suspense>
</Suspense>
);
}
const root = ReactTestRenderer.create(<Parent swap={false} />, {
isConcurrent: true,
});
await waitForAll(['Init A', 'Loading...']);
expect(root).not.toMatchRenderedOutput('AB');
await act(() => resolveFakeImport(ChildA));
assertLog(['A', 'Init B']);
await act(() => resolveFakeImport(ChildB));
assertLog(['A', 'B', 'Did mount: A', 'Did mount: B']);
expect(root).toMatchRenderedOutput('AB');
// Swap the position of A and B
root.update(<Parent swap={true} />);
await waitForAll([
'Init B2',
'Loading...',
'Did unmount: A',
'Did unmount: B',
]);
// The suspense boundary should've triggered now.
expect(root).toMatchRenderedOutput('Loading...');
await act(() => resolveB2({default: ChildB}));
// We need to flush to trigger the second one to load.
assertLog(['Init A2', 'b', 'a', 'Did mount: b', 'Did mount: a']);
expect(root).toMatchRenderedOutput('ba');
});
it('mount and reorder lazy types (legacy mode)', async () => {
class Child extends React.Component {
componentDidMount() {
Scheduler.log('Did mount: ' + this.props.label);
}
componentDidUpdate() {
Scheduler.log('Did update: ' + this.props.label);
}
render() {
return <Text text={this.props.label} />;
}
}
function ChildA({lowerCase}) {
return <Child label={lowerCase ? 'a' : 'A'} />;
}
function ChildB({lowerCase}) {
return <Child label={lowerCase ? 'b' : 'B'} />;
}
const LazyChildA = lazy(() => {
Scheduler.log('Init A');
return fakeImport(ChildA);
});
const LazyChildB = lazy(() => {
Scheduler.log('Init B');
return fakeImport(ChildB);
});
const LazyChildA2 = lazy(() => {
Scheduler.log('Init A2');
return fakeImport(ChildA);
});
const LazyChildB2 = lazy(() => {
Scheduler.log('Init B2');
return fakeImport(ChildB);
});
function Parent({swap}) {
return (
<Suspense fallback={<Text text="Outer..." />}>
<Suspense fallback={<Text text="Loading..." />}>
{swap
? [
<LazyChildB2 key="B" lowerCase={true} />,
<LazyChildA2 key="A" lowerCase={true} />,
]
: [<LazyChildA key="A" />, <LazyChildB key="B" />]}
</Suspense>
</Suspense>
);
}
const root = ReactTestRenderer.create(<Parent swap={false} />, {
isConcurrent: false,
});
assertLog(['Init A', 'Init B', 'Loading...']);
expect(root).not.toMatchRenderedOutput('AB');
await resolveFakeImport(ChildA);
await resolveFakeImport(ChildB);
await waitForAll(['A', 'B', 'Did mount: A', 'Did mount: B']);
expect(root).toMatchRenderedOutput('AB');
// Swap the position of A and B
root.update(<Parent swap={true} />);
assertLog(['Init B2', 'Loading...']);
await waitForAll(['Init A2', 'b', 'a', 'Did update: b', 'Did update: a']);
expect(root).toMatchRenderedOutput('ba');
});
it('mount and reorder lazy elements', async () => {
class Child extends React.Component {
componentDidMount() {
Scheduler.log('Did mount: ' + this.props.label);
}
componentDidUpdate() {
Scheduler.log('Did update: ' + this.props.label);
}
render() {
return <Text text={this.props.label} />;
}
}
const ChildA = <Child key="A" label="A" />;
const lazyChildA = lazy(() => {
Scheduler.log('Init A');
return fakeImport(ChildA);
});
const ChildB = <Child key="B" label="B" />;
const lazyChildB = lazy(() => {
Scheduler.log('Init B');
return fakeImport(ChildB);
});
const ChildA2 = <Child key="A" label="a" />;
const lazyChildA2 = lazy(() => {
Scheduler.log('Init A2');
return fakeImport(ChildA2);
});
const ChildB2 = <Child key="B" label="b" />;
const lazyChildB2 = lazy(() => {
Scheduler.log('Init B2');
return fakeImport(ChildB2);
});
function Parent({swap}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{swap ? [lazyChildB2, lazyChildA2] : [lazyChildA, lazyChildB]}
</Suspense>
);
}
const root = ReactTestRenderer.create(<Parent swap={false} />, {
isConcurrent: true,
});
await waitForAll(['Init A', 'Loading...']);
expect(root).not.toMatchRenderedOutput('AB');
await act(() => resolveFakeImport(ChildA));
// We need to flush to trigger the B to load.
await assertLog(['Init B']);
await act(() => resolveFakeImport(ChildB));
assertLog(['A', 'B', 'Did mount: A', 'Did mount: B']);
expect(root).toMatchRenderedOutput('AB');
// Swap the position of A and B
React.startTransition(() => {
root.update(<Parent swap={true} />);
});
await waitForAll(['Init B2', 'Loading...']);
await act(() => resolveFakeImport(ChildB2));
// We need to flush to trigger the second one to load.
assertLog(['Init A2', 'Loading...']);
await act(() => resolveFakeImport(ChildA2));
assertLog(['b', 'a', 'Did update: b', 'Did update: a']);
expect(root).toMatchRenderedOutput('ba');
});
it('mount and reorder lazy elements (legacy mode)', async () => {
class Child extends React.Component {
componentDidMount() {
Scheduler.log('Did mount: ' + this.props.label);
}
componentDidUpdate() {
Scheduler.log('Did update: ' + this.props.label);
}
render() {
return <Text text={this.props.label} />;
}
}
const ChildA = <Child key="A" label="A" />;
const lazyChildA = lazy(() => {
Scheduler.log('Init A');
return fakeImport(ChildA);
});
const ChildB = <Child key="B" label="B" />;
const lazyChildB = lazy(() => {
Scheduler.log('Init B');
return fakeImport(ChildB);
});
const ChildA2 = <Child key="A" label="a" />;
const lazyChildA2 = lazy(() => {
Scheduler.log('Init A2');
return fakeImport(ChildA2);
});
const ChildB2 = <Child key="B" label="b" />;
const lazyChildB2 = lazy(() => {
Scheduler.log('Init B2');
return fakeImport(ChildB2);
});
function Parent({swap}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{swap ? [lazyChildB2, lazyChildA2] : [lazyChildA, lazyChildB]}
</Suspense>
);
}
const root = ReactTestRenderer.create(<Parent swap={false} />, {
isConcurrent: false,
});
assertLog(['Init A', 'Loading...']);
expect(root).not.toMatchRenderedOutput('AB');
await resolveFakeImport(ChildA);
// We need to flush to trigger the B to load.
await waitForAll(['Init B']);
await resolveFakeImport(ChildB);
await waitForAll(['A', 'B', 'Did mount: A', 'Did mount: B']);
expect(root).toMatchRenderedOutput('AB');
// Swap the position of A and B
root.update(<Parent swap={true} />);
assertLog(['Init B2', 'Loading...']);
await resolveFakeImport(ChildB2);
// We need to flush to trigger the second one to load.
await waitForAll(['Init A2']);
await resolveFakeImport(ChildA2);
await waitForAll(['b', 'a', 'Did update: b', 'Did update: a']);
expect(root).toMatchRenderedOutput('ba');
});
});
| 27.36029 | 155 | 0.578354 |
Python-Penetration-Testing-for-Developers | let React;
let Fragment;
let ReactNoop;
let Scheduler;
let act;
let waitFor;
let waitForAll;
let waitForMicrotasks;
let assertLog;
let waitForPaint;
let Suspense;
let startTransition;
let getCacheForType;
let caches;
let seededCache;
describe('ReactSuspenseWithNoopRenderer', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
Fragment = React.Fragment;
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
Suspense = React.Suspense;
startTransition = React.startTransition;
const InternalTestUtils = require('internal-test-utils');
waitFor = InternalTestUtils.waitFor;
waitForAll = InternalTestUtils.waitForAll;
waitForPaint = InternalTestUtils.waitForPaint;
waitForMicrotasks = InternalTestUtils.waitForMicrotasks;
assertLog = InternalTestUtils.assertLog;
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;
function rejectMostRecentTextCache(text, error) {
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].reject(text, error)`.
caches[caches.length - 1].reject(text, error);
}
}
const rejectText = rejectMostRecentTextCache;
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(() => {});
}
// Note: This is based on a similar component we use in www. We can delete
// once the extra div wrapper is no longer necessary.
function LegacyHiddenDiv({children, mode}) {
return (
<div hidden={mode === 'hidden'}>
<React.unstable_LegacyHidden
mode={mode === 'hidden' ? 'unstable-defer-without-hiding' : mode}>
{children}
</React.unstable_LegacyHidden>
</div>
);
}
// @gate enableLegacyCache
it("does not restart if there's a ping during initial render", async () => {
function Bar(props) {
Scheduler.log('Bar');
return props.children;
}
function Foo() {
Scheduler.log('Foo');
return (
<>
<Suspense fallback={<Text text="Loading..." />}>
<Bar>
<AsyncText text="A" ms={100} />
<Text text="B" />
</Bar>
</Suspense>
<Text text="C" />
<Text text="D" />
</>
);
}
React.startTransition(() => {
ReactNoop.render(<Foo />);
});
await waitFor([
'Foo',
'Bar',
// A suspends
'Suspend! [A]',
// We immediately unwind and switch to a fallback without
// rendering siblings.
'Loading...',
'C',
// Yield before rendering D
]);
expect(ReactNoop).toMatchRenderedOutput(null);
// Flush the promise completely
await act(async () => {
await resolveText('A');
// Even though the promise has resolved, we should now flush
// and commit the in progress render instead of restarting.
await waitForPaint(['D']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Loading..." />
<span prop="C" />
<span prop="D" />
</>,
);
// Next, we'll flush the complete content.
await waitForAll(['Bar', 'A', 'B']);
});
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
<span prop="C" />
<span prop="D" />
</>,
);
});
// @gate enableLegacyCache
it('suspends rendering and continues later', async () => {
function Bar(props) {
Scheduler.log('Bar');
return props.children;
}
function Foo({renderBar}) {
Scheduler.log('Foo');
return (
<Suspense fallback={<Text text="Loading..." />}>
{renderBar ? (
<Bar>
<AsyncText text="A" />
<Text text="B" />
</Bar>
) : null}
</Suspense>
);
}
// Render empty shell.
ReactNoop.render(<Foo />);
await waitForAll(['Foo']);
// The update will suspend.
React.startTransition(() => {
ReactNoop.render(<Foo renderBar={true} />);
});
await waitForAll([
'Foo',
'Bar',
// A suspends
'Suspend! [A]',
// We immediately unwind and switch to a fallback without
// rendering siblings.
'Loading...',
]);
expect(ReactNoop).toMatchRenderedOutput(null);
// Resolve the data
await resolveText('A');
// Renders successfully
await waitForAll(['Foo', 'Bar', 'A', 'B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('suspends siblings and later recovers each independently', async () => {
// Render two sibling Suspense components
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading A..." />}>
<AsyncText text="A" />
</Suspense>
<Suspense fallback={<Text text="Loading B..." />}>
<AsyncText text="B" />
</Suspense>
</Fragment>,
);
await waitForAll([
'Suspend! [A]',
'Loading A...',
'Suspend! [B]',
'Loading B...',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Loading A..." />
<span prop="Loading B..." />
</>,
);
// Resolve first Suspense's promise so that it switches switches back to the
// normal view. The second Suspense should still show the placeholder.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading B..." />
</>,
);
// Resolve the second Suspense's promise so that it switches back to the
// normal view.
await act(() => resolveText('B'));
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('when something suspends, unwinds immediately without rendering siblings', async () => {
// A shell is needed. The update cause it to suspend.
ReactNoop.render(<Suspense fallback={<Text text="Loading..." />} />);
await waitForAll([]);
React.startTransition(() => {
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<Text text="A" />
<AsyncText text="B" />
<Text text="C" />
<Text text="D" />
</Suspense>,
);
});
// B suspends. Render a fallback
await waitForAll(['A', 'Suspend! [B]', 'Loading...']);
// Did not commit yet.
expect(ReactNoop).toMatchRenderedOutput(null);
// Wait for data to resolve
await resolveText('B');
await waitForAll(['A', 'B', 'C', 'D']);
// Renders successfully
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
<span prop="C" />
<span prop="D" />
</>,
);
});
// Second condition is redundant but guarantees that the test runs in prod.
// TODO: Delete this feature flag.
// @gate !replayFailedUnitOfWorkWithInvokeGuardedCallback || !__DEV__
// @gate enableLegacyCache
it('retries on error', async () => {
class ErrorBoundary extends React.Component {
state = {error: null};
componentDidCatch(error) {
this.setState({error});
}
reset() {
this.setState({error: null});
}
render() {
if (this.state.error !== null) {
return <Text text={'Caught error: ' + this.state.error.message} />;
}
return this.props.children;
}
}
const errorBoundary = React.createRef();
function App({renderContent}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{renderContent ? (
<ErrorBoundary ref={errorBoundary}>
<AsyncText text="Result" ms={1000} />
</ErrorBoundary>
) : null}
</Suspense>
);
}
ReactNoop.render(<App />);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(null);
React.startTransition(() => {
ReactNoop.render(<App renderContent={true} />);
});
await waitForAll(['Suspend! [Result]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(null);
await rejectText('Result', new Error('Failed to load: Result'));
await waitForAll([
'Error! [Result]',
// React retries one more time
'Error! [Result]',
// Errored again on retry. Now handle it.
'Caught error: Failed to load: Result',
]);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Caught error: Failed to load: Result" />,
);
});
// Second condition is redundant but guarantees that the test runs in prod.
// TODO: Delete this feature flag.
// @gate !replayFailedUnitOfWorkWithInvokeGuardedCallback || !__DEV__
// @gate enableLegacyCache
it('retries on error after falling back to a placeholder', async () => {
class ErrorBoundary extends React.Component {
state = {error: null};
componentDidCatch(error) {
this.setState({error});
}
reset() {
this.setState({error: null});
}
render() {
if (this.state.error !== null) {
return <Text text={'Caught error: ' + this.state.error.message} />;
}
return this.props.children;
}
}
const errorBoundary = React.createRef();
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<ErrorBoundary ref={errorBoundary}>
<AsyncText text="Result" />
</ErrorBoundary>
</Suspense>
);
}
ReactNoop.render(<App />);
await waitForAll(['Suspend! [Result]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
await act(() => rejectText('Result', new Error('Failed to load: Result')));
assertLog([
'Error! [Result]',
// React retries one more time
'Error! [Result]',
// Errored again on retry. Now handle it.
'Caught error: Failed to load: Result',
]);
expect(ReactNoop).toMatchRenderedOutput(
<span prop="Caught error: Failed to load: Result" />,
);
});
// @gate enableLegacyCache
it('can update at a higher priority while in a suspended state', async () => {
let setHighPri;
function HighPri() {
const [text, setText] = React.useState('A');
setHighPri = setText;
return <Text text={text} />;
}
let setLowPri;
function LowPri() {
const [text, setText] = React.useState('1');
setLowPri = setText;
return <AsyncText text={text} />;
}
function App() {
return (
<>
<HighPri />
<Suspense fallback={<Text text="Loading..." />}>
<LowPri />
</Suspense>
</>
);
}
// Initial mount
await act(() => ReactNoop.render(<App />));
assertLog(['A', 'Suspend! [1]', 'Loading...']);
await act(() => resolveText('1'));
assertLog(['1']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="1" />
</>,
);
// Update the low-pri text
await act(() => startTransition(() => setLowPri('2')));
// Suspends
assertLog(['Suspend! [2]', 'Loading...']);
// While we're still waiting for the low-pri update to complete, update the
// high-pri text at high priority.
ReactNoop.flushSync(() => {
setHighPri('B');
});
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="1" />
</>,
);
// Unblock the low-pri text and finish. Nothing in the UI changes because
// the update was overriden
await act(() => resolveText('2'));
assertLog(['2']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="2" />
</>,
);
});
// @gate enableLegacyCache
it('keeps working on lower priority work after being pinged', async () => {
function App(props) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{props.showA && <AsyncText text="A" />}
{props.showB && <Text text="B" />}
</Suspense>
);
}
ReactNoop.render(<App showA={false} showB={false} />);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(null);
React.startTransition(() => {
ReactNoop.render(<App showA={true} showB={false} />);
});
await waitForAll(['Suspend! [A]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(null);
React.startTransition(() => {
ReactNoop.render(<App showA={true} showB={true} />);
});
await waitForAll(['Suspend! [A]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(null);
await resolveText('A');
await waitForAll(['A', 'B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('tries rendering a lower priority pending update even if a higher priority one suspends', async () => {
function App(props) {
if (props.hide) {
return <Text text="(empty)" />;
}
return (
<Suspense fallback="Loading...">
<AsyncText ms={2000} text="Async" />
</Suspense>
);
}
// Schedule a default pri update and a low pri update, without rendering in between.
// Default pri
ReactNoop.render(<App />);
// Low pri
React.startTransition(() => {
ReactNoop.render(<App hide={true} />);
});
await waitForAll([
// The first update suspends
'Suspend! [Async]',
// but we have another pending update that we can work on
'(empty)',
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="(empty)" />);
});
// Note: This test was written to test a heuristic used in the expiration
// times model. Might not make sense in the new model.
// TODO: This test doesn't over what it was originally designed to test.
// Either rewrite or delete.
it('tries each subsequent level after suspending', async () => {
const root = ReactNoop.createRoot();
function App({step, shouldSuspend}) {
return (
<Suspense fallback="Loading...">
<Text text="Sibling" />
{shouldSuspend ? (
<AsyncText text={'Step ' + step} />
) : (
<Text text={'Step ' + step} />
)}
</Suspense>
);
}
function interrupt() {
// React has a heuristic to batch all updates that occur within the same
// event. This is a trick to circumvent that heuristic.
ReactNoop.flushSync(() => {
ReactNoop.renderToRootWithID(null, 'other-root');
});
}
// Mount the Suspense boundary without suspending, so that the subsequent
// updates suspend with a delay.
await act(() => {
root.render(<App step={0} shouldSuspend={false} />);
});
await advanceTimers(1000);
assertLog(['Sibling', 'Step 0']);
// Schedule an update at several distinct expiration times
await act(async () => {
React.startTransition(() => {
root.render(<App step={1} shouldSuspend={true} />);
});
Scheduler.unstable_advanceTime(1000);
await waitFor(['Sibling']);
interrupt();
React.startTransition(() => {
root.render(<App step={2} shouldSuspend={true} />);
});
Scheduler.unstable_advanceTime(1000);
await waitFor(['Sibling']);
interrupt();
React.startTransition(() => {
root.render(<App step={3} shouldSuspend={true} />);
});
Scheduler.unstable_advanceTime(1000);
await waitFor(['Sibling']);
interrupt();
root.render(<App step={4} shouldSuspend={false} />);
});
assertLog(['Sibling', 'Step 4']);
});
// @gate enableLegacyCache
it('switches to an inner fallback after suspending for a while', async () => {
// Advance the virtual time so that we're closer to the edge of a bucket.
ReactNoop.expire(200);
ReactNoop.render(
<Fragment>
<Text text="Sync" />
<Suspense fallback={<Text text="Loading outer..." />}>
<AsyncText text="Outer content" ms={300} />
<Suspense fallback={<Text text="Loading inner..." />}>
<AsyncText text="Inner content" ms={1000} />
</Suspense>
</Suspense>
</Fragment>,
);
await waitForAll([
'Sync',
// The async content suspends
'Suspend! [Outer content]',
'Loading outer...',
]);
// The outer loading state finishes immediately.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Sync" />
<span prop="Loading outer..." />
</>,
);
// Resolve the outer promise.
await resolveText('Outer content');
await waitForAll([
'Outer content',
'Suspend! [Inner content]',
'Loading inner...',
]);
// Don't commit the inner placeholder yet.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Sync" />
<span prop="Loading outer..." />
</>,
);
// Expire the inner timeout.
ReactNoop.expire(500);
await advanceTimers(500);
// Now that 750ms have elapsed since the outer placeholder timed out,
// we can timeout the inner placeholder.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Sync" />
<span prop="Outer content" />
<span prop="Loading inner..." />
</>,
);
// Finally, flush the inner promise. We should see the complete screen.
await act(() => resolveText('Inner content'));
assertLog(['Inner content']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Sync" />
<span prop="Outer content" />
<span prop="Inner content" />
</>,
);
});
// @gate enableLegacyCache
it('renders an Suspense boundary synchronously', async () => {
spyOnDev(console, 'error');
// Synchronously render a tree that suspends
ReactNoop.flushSync(() =>
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" />
</Suspense>
<Text text="Sync" />
</Fragment>,
),
);
assertLog([
// The async child suspends
'Suspend! [Async]',
// We immediately render the fallback UI
'Loading...',
// Continue on the sibling
'Sync',
]);
// The tree commits synchronously
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Loading..." />
<span prop="Sync" />
</>,
);
// Once the promise resolves, we render the suspended view
await act(() => resolveText('Async'));
assertLog(['Async']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Async" />
<span prop="Sync" />
</>,
);
});
// @gate enableLegacyCache
it('suspending inside an expired expiration boundary will bubble to the next one', async () => {
ReactNoop.flushSync(() =>
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading (outer)..." />}>
<Suspense fallback={<AsyncText text="Loading (inner)..." />}>
<AsyncText text="Async" />
</Suspense>
<Text text="Sync" />
</Suspense>
</Fragment>,
),
);
assertLog([
'Suspend! [Async]',
'Suspend! [Loading (inner)...]',
'Loading (outer)...',
]);
// The tree commits synchronously
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading (outer)..." />);
});
// @gate enableLegacyCache
it('resolves successfully even if fallback render is pending', async () => {
const root = ReactNoop.createRoot();
root.render(
<>
<Suspense fallback={<Text text="Loading..." />} />
</>,
);
await waitForAll([]);
expect(root).toMatchRenderedOutput(null);
React.startTransition(() => {
root.render(
<>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" />
<Text text="Sibling" />
</Suspense>
</>,
);
});
await waitFor(['Suspend! [Async]']);
await resolveText('Async');
// Because we're already showing a fallback, interrupt the current render
// and restart immediately.
await waitForAll(['Async', 'Sibling']);
expect(root).toMatchRenderedOutput(
<>
<span prop="Async" />
<span prop="Sibling" />
</>,
);
});
// @gate enableLegacyCache
it('in concurrent mode, does not error when an update suspends without a Suspense boundary during a sync update', () => {
// NOTE: We may change this to be a warning in the future.
expect(() => {
ReactNoop.flushSync(() => {
ReactNoop.render(<AsyncText text="Async" />);
});
}).not.toThrow();
});
// @gate enableLegacyCache
it('in legacy mode, errors when an update suspends without a Suspense boundary during a sync update', () => {
const root = ReactNoop.createLegacyRoot();
expect(() => root.render(<AsyncText text="Async" />)).toThrow(
'A component suspended while responding to synchronous input.',
);
});
// @gate enableLegacyCache
it('a Suspense component correctly handles more than one suspended child', async () => {
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="A" />
<AsyncText text="B" />
</Suspense>,
);
await waitForAll(['Suspend! [A]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
await act(() => {
resolveText('A');
resolveText('B');
});
assertLog(['A', 'B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('can resume rendering earlier than a timeout', async () => {
ReactNoop.render(<Suspense fallback={<Text text="Loading..." />} />);
await waitForAll([]);
React.startTransition(() => {
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" />
</Suspense>,
);
});
await waitForAll(['Suspend! [Async]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(null);
// Resolve the promise
await resolveText('Async');
// We can now resume rendering
await waitForAll(['Async']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Async" />);
});
// @gate enableLegacyCache
it('starts working on an update even if its priority falls between two suspended levels', async () => {
function App(props) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{props.text === 'C' || props.text === 'S' ? (
<Text text={props.text} />
) : (
<AsyncText text={props.text} />
)}
</Suspense>
);
}
// First mount without suspending. This ensures we already have content
// showing so that subsequent updates will suspend.
ReactNoop.render(<App text="S" />);
await waitForAll(['S']);
// Schedule an update, and suspend for up to 5 seconds.
React.startTransition(() => ReactNoop.render(<App text="A" />));
// The update should suspend.
await waitForAll(['Suspend! [A]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="S" />);
// Advance time until right before it expires.
await advanceTimers(4999);
ReactNoop.expire(4999);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="S" />);
// Schedule another low priority update.
React.startTransition(() => ReactNoop.render(<App text="B" />));
// This update should also suspend.
await waitForAll(['Suspend! [B]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="S" />);
// Schedule a regular update. Its expiration time will fall between
// the expiration times of the previous two updates.
ReactNoop.render(<App text="C" />);
await waitForAll(['C']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="C" />);
// Flush the remaining work.
await resolveText('A');
await resolveText('B');
// Nothing else to render.
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="C" />);
});
// @gate enableLegacyCache
it('a suspended update that expires', async () => {
// Regression test. This test used to fall into an infinite loop.
function ExpensiveText({text}) {
// This causes the update to expire.
Scheduler.unstable_advanceTime(10000);
// Then something suspends.
return <AsyncText text={text} />;
}
function App() {
return (
<Suspense fallback="Loading...">
<ExpensiveText text="A" />
<ExpensiveText text="B" />
<ExpensiveText text="C" />
</Suspense>
);
}
ReactNoop.render(<App />);
await waitForAll(['Suspend! [A]']);
expect(ReactNoop).toMatchRenderedOutput('Loading...');
await resolveText('A');
await resolveText('B');
await resolveText('C');
await waitForAll(['A', 'B', 'C']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
<span prop="C" />
</>,
);
});
describe('legacy mode mode', () => {
// @gate enableLegacyCache
it('times out immediately', async () => {
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Result" />
</Suspense>
);
}
// Times out immediately, ignoring the specified threshold.
ReactNoop.renderLegacySyncRoot(<App />);
assertLog(['Suspend! [Result]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
await act(() => {
resolveText('Result');
});
assertLog(['Result']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Result" />);
});
// @gate enableLegacyCache
it('times out immediately when Suspense is in legacy mode', async () => {
class UpdatingText extends React.Component {
state = {step: 1};
render() {
return <AsyncText text={`Step: ${this.state.step}`} />;
}
}
function Spinner() {
return (
<Fragment>
<Text text="Loading (1)" />
<Text text="Loading (2)" />
<Text text="Loading (3)" />
</Fragment>
);
}
const text = React.createRef(null);
function App() {
return (
<Suspense fallback={<Spinner />}>
<UpdatingText ref={text} />
<Text text="Sibling" />
</Suspense>
);
}
// Initial mount.
await seedNextTextCache('Step: 1');
ReactNoop.renderLegacySyncRoot(<App />);
assertLog(['Step: 1', 'Sibling']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Step: 1" />
<span prop="Sibling" />
</>,
);
// Update.
text.current.setState({step: 2}, () =>
Scheduler.log('Update did commit'),
);
expect(ReactNoop.flushNextYield()).toEqual([
'Suspend! [Step: 2]',
'Loading (1)',
'Loading (2)',
'Loading (3)',
'Update did commit',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span hidden={true} prop="Step: 1" />
<span hidden={true} prop="Sibling" />
<span prop="Loading (1)" />
<span prop="Loading (2)" />
<span prop="Loading (3)" />
</>,
);
await act(() => {
resolveText('Step: 2');
});
assertLog(['Step: 2']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Step: 2" />
<span prop="Sibling" />
</>,
);
});
// @gate enableLegacyCache
it('does not re-render siblings in loose mode', async () => {
class TextWithLifecycle extends React.Component {
componentDidMount() {
Scheduler.log(`Mount [${this.props.text}]`);
}
componentDidUpdate() {
Scheduler.log(`Update [${this.props.text}]`);
}
render() {
return <Text {...this.props} />;
}
}
class AsyncTextWithLifecycle extends React.Component {
componentDidMount() {
Scheduler.log(`Mount [${this.props.text}]`);
}
componentDidUpdate() {
Scheduler.log(`Update [${this.props.text}]`);
}
render() {
return <AsyncText {...this.props} />;
}
}
function App() {
return (
<Suspense fallback={<TextWithLifecycle text="Loading..." />}>
<TextWithLifecycle text="A" />
<AsyncTextWithLifecycle text="B" />
<TextWithLifecycle text="C" />
</Suspense>
);
}
ReactNoop.renderLegacySyncRoot(<App />, () =>
Scheduler.log('Commit root'),
);
assertLog([
'A',
'Suspend! [B]',
'C',
'Loading...',
'Mount [A]',
'Mount [B]',
'Mount [C]',
// This should be a mount, not an update.
'Mount [Loading...]',
'Commit root',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span hidden={true} prop="C" />
<span prop="Loading..." />
</>,
);
await act(() => {
resolveText('B');
});
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
<span prop="C" />
</>,
);
});
// @gate enableLegacyCache
it('suspends inside constructor', async () => {
class AsyncTextInConstructor extends React.Component {
constructor(props) {
super(props);
const text = props.text;
Scheduler.log('constructor');
readText(text);
this.state = {text};
}
componentDidMount() {
Scheduler.log('componentDidMount');
}
render() {
Scheduler.log(this.state.text);
return <span prop={this.state.text} />;
}
}
ReactNoop.renderLegacySyncRoot(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncTextInConstructor text="Hi" />
</Suspense>,
);
assertLog(['constructor', 'Suspend! [Hi]', 'Loading...']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
await act(() => {
resolveText('Hi');
});
assertLog(['constructor', 'Hi', 'componentDidMount']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Hi" />);
});
// @gate enableLegacyCache
it('does not infinite loop if fallback contains lifecycle method', async () => {
class Fallback extends React.Component {
state = {
name: 'foo',
};
componentDidMount() {
this.setState({
name: 'bar',
});
}
render() {
return <Text text="Loading..." />;
}
}
class Demo extends React.Component {
render() {
return (
<Suspense fallback={<Fallback />}>
<AsyncText text="Hi" />
</Suspense>
);
}
}
ReactNoop.renderLegacySyncRoot(<Demo />);
assertLog([
'Suspend! [Hi]',
'Loading...',
// Re-render due to lifecycle update
'Loading...',
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
await act(() => {
resolveText('Hi');
});
assertLog(['Hi']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Hi" />);
});
if (global.__PERSISTENT__) {
// @gate enableLegacyCache
it('hides/unhides suspended children before layout effects fire (persistent)', async () => {
const {useRef, useLayoutEffect} = React;
function Parent() {
const child = useRef(null);
useLayoutEffect(() => {
Scheduler.log(ReactNoop.getPendingChildrenAsJSX());
});
return (
<span ref={child} hidden={false}>
<AsyncText text="Hi" />
</span>
);
}
function App(props) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Parent />
</Suspense>
);
}
ReactNoop.renderLegacySyncRoot(<App middleText="B" />);
assertLog([
'Suspend! [Hi]',
'Loading...',
// The child should have already been hidden
<>
<span hidden={true} />
<span prop="Loading..." />
</>,
]);
await act(() => {
resolveText('Hi');
});
assertLog(['Hi']);
});
} else {
// @gate enableLegacyCache
it('hides/unhides suspended children before layout effects fire (mutation)', async () => {
const {useRef, useLayoutEffect} = React;
function Parent() {
const child = useRef(null);
useLayoutEffect(() => {
Scheduler.log('Child is hidden: ' + child.current.hidden);
});
return (
<span ref={child} hidden={false}>
<AsyncText text="Hi" />
</span>
);
}
function App(props) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Parent />
</Suspense>
);
}
ReactNoop.renderLegacySyncRoot(<App middleText="B" />);
assertLog([
'Suspend! [Hi]',
'Loading...',
// The child should have already been hidden
'Child is hidden: true',
]);
await act(() => {
resolveText('Hi');
});
assertLog(['Hi']);
});
}
// @gate enableLegacyCache
it('handles errors in the return path of a component that suspends', async () => {
// Covers an edge case where an error is thrown inside the complete phase
// of a component that is in the return path of a component that suspends.
// The second error should also be handled (i.e. able to be captured by
// an error boundary.
class ErrorBoundary extends React.Component {
state = {error: null};
static getDerivedStateFromError(error, errorInfo) {
return {error};
}
render() {
if (this.state.error) {
return `Caught an error: ${this.state.error.message}`;
}
return this.props.children;
}
}
ReactNoop.renderLegacySyncRoot(
<ErrorBoundary>
<Suspense fallback="Loading...">
<errorInCompletePhase>
<AsyncText text="Async" />
</errorInCompletePhase>
</Suspense>
</ErrorBoundary>,
);
assertLog(['Suspend! [Async]']);
expect(ReactNoop).toMatchRenderedOutput(
'Caught an error: Error in host config.',
);
});
it('does not drop mounted effects', async () => {
const never = {then() {}};
let setShouldSuspend;
function App() {
const [shouldSuspend, _setShouldSuspend] = React.useState(0);
setShouldSuspend = _setShouldSuspend;
return (
<Suspense fallback="Loading...">
<Child shouldSuspend={shouldSuspend} />
</Suspense>
);
}
function Child({shouldSuspend}) {
if (shouldSuspend) {
throw never;
}
React.useEffect(() => {
Scheduler.log('Mount');
return () => {
Scheduler.log('Unmount');
};
}, []);
return 'Child';
}
const root = ReactNoop.createLegacyRoot(null);
await act(() => {
root.render(<App />);
});
assertLog(['Mount']);
expect(root).toMatchRenderedOutput('Child');
// Suspend the child. This puts it into an inconsistent state.
await act(() => {
setShouldSuspend(true);
});
expect(root).toMatchRenderedOutput('Loading...');
// Unmount everything
await act(() => {
root.render(null);
});
assertLog(['Unmount']);
});
});
// @gate enableLegacyCache
it('does not call lifecycles of a suspended component', async () => {
class TextWithLifecycle extends React.Component {
componentDidMount() {
Scheduler.log(`Mount [${this.props.text}]`);
}
componentDidUpdate() {
Scheduler.log(`Update [${this.props.text}]`);
}
componentWillUnmount() {
Scheduler.log(`Unmount [${this.props.text}]`);
}
render() {
return <Text {...this.props} />;
}
}
class AsyncTextWithLifecycle extends React.Component {
componentDidMount() {
Scheduler.log(`Mount [${this.props.text}]`);
}
componentDidUpdate() {
Scheduler.log(`Update [${this.props.text}]`);
}
componentWillUnmount() {
Scheduler.log(`Unmount [${this.props.text}]`);
}
render() {
const text = this.props.text;
readText(text);
Scheduler.log(text);
return <span prop={text} />;
}
}
function App() {
return (
<Suspense fallback={<TextWithLifecycle text="Loading..." />}>
<TextWithLifecycle text="A" />
<AsyncTextWithLifecycle text="B" />
<TextWithLifecycle text="C" />
</Suspense>
);
}
ReactNoop.renderLegacySyncRoot(<App />, () => Scheduler.log('Commit root'));
assertLog([
'A',
'Suspend! [B]',
'C',
'Loading...',
'Mount [A]',
// B's lifecycle should not fire because it suspended
// 'Mount [B]',
'Mount [C]',
'Mount [Loading...]',
'Commit root',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span hidden={true} prop="C" />
<span prop="Loading..." />
</>,
);
});
// @gate enableLegacyCache
it('does not call lifecycles of a suspended component (hooks)', async () => {
function TextWithLifecycle(props) {
React.useLayoutEffect(() => {
Scheduler.log(`Layout Effect [${props.text}]`);
return () => {
Scheduler.log(`Destroy Layout Effect [${props.text}]`);
};
}, [props.text]);
React.useEffect(() => {
Scheduler.log(`Effect [${props.text}]`);
return () => {
Scheduler.log(`Destroy Effect [${props.text}]`);
};
}, [props.text]);
return <Text {...props} />;
}
function AsyncTextWithLifecycle(props) {
React.useLayoutEffect(() => {
Scheduler.log(`Layout Effect [${props.text}]`);
return () => {
Scheduler.log(`Destroy Layout Effect [${props.text}]`);
};
}, [props.text]);
React.useEffect(() => {
Scheduler.log(`Effect [${props.text}]`);
return () => {
Scheduler.log(`Destroy Effect [${props.text}]`);
};
}, [props.text]);
const text = props.text;
readText(text);
Scheduler.log(text);
return <span prop={text} />;
}
function App({text}) {
return (
<Suspense fallback={<TextWithLifecycle text="Loading..." />}>
<TextWithLifecycle text="A" />
<AsyncTextWithLifecycle text={text} />
<TextWithLifecycle text="C" />
</Suspense>
);
}
ReactNoop.renderLegacySyncRoot(<App text="B" />, () =>
Scheduler.log('Commit root'),
);
assertLog([
'A',
'Suspend! [B]',
'C',
'Loading...',
'Layout Effect [A]',
// B's effect should not fire because it suspended
// 'Layout Effect [B]',
'Layout Effect [C]',
'Layout Effect [Loading...]',
'Commit root',
]);
// Flush passive effects.
await waitForAll([
'Effect [A]',
// B's effect should not fire because it suspended
// 'Effect [B]',
'Effect [C]',
'Effect [Loading...]',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span hidden={true} prop="C" />
<span prop="Loading..." />
</>,
);
await act(() => {
resolveText('B');
});
assertLog([
'B',
'Destroy Layout Effect [Loading...]',
'Layout Effect [B]',
'Destroy Effect [Loading...]',
'Effect [B]',
]);
// Update
ReactNoop.renderLegacySyncRoot(<App text="B2" />, () =>
Scheduler.log('Commit root'),
);
assertLog([
'A',
'Suspend! [B2]',
'C',
'Loading...',
// B2's effect should not fire because it suspended
// 'Layout Effect [B2]',
'Layout Effect [Loading...]',
'Commit root',
]);
// Flush passive effects.
await waitForAll([
// B2's effect should not fire because it suspended
// 'Effect [B2]',
'Effect [Loading...]',
]);
await act(() => {
resolveText('B2');
});
assertLog([
'B2',
'Destroy Layout Effect [Loading...]',
'Destroy Layout Effect [B]',
'Layout Effect [B2]',
'Destroy Effect [Loading...]',
'Destroy Effect [B]',
'Effect [B2]',
]);
});
// @gate enableLegacyCache
it('does not suspends if a fallback has been shown for a long time', async () => {
function Foo() {
Scheduler.log('Foo');
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="A" />
<Suspense fallback={<Text text="Loading more..." />}>
<AsyncText text="B" />
</Suspense>
</Suspense>
);
}
ReactNoop.render(<Foo />);
// Start rendering
await waitForAll([
'Foo',
// A suspends
'Suspend! [A]',
'Loading...',
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
// Wait a long time.
Scheduler.unstable_advanceTime(5000);
await advanceTimers(5000);
// Retry with the new content.
await resolveText('A');
await waitForAll([
'A',
// B suspends
'Suspend! [B]',
'Loading more...',
]);
// Because we've already been waiting for so long we've exceeded
// our threshold and we show the next level immediately.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading more..." />
</>,
);
// Flush the last promise completely
await act(() => resolveText('B'));
// Renders successfully
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('throttles content from appearing if a fallback was shown recently', async () => {
function Foo() {
Scheduler.log('Foo');
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="A" />
<Suspense fallback={<Text text="Loading more..." />}>
<AsyncText text="B" />
</Suspense>
</Suspense>
);
}
ReactNoop.render(<Foo />);
// Start rendering
await waitForAll([
'Foo',
// A suspends
'Suspend! [A]',
'Loading...',
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
await act(async () => {
await resolveText('A');
// Retry with the new content.
await waitForAll([
'A',
// B suspends
'Suspend! [B]',
'Loading more...',
]);
// Because we've already been waiting for so long we can
// wait a bit longer. Still nothing...
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
// Before we commit another Promise resolves.
// We're still showing the first loading state.
await resolveText('B');
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
// Restart and render the complete content.
await waitForAll(['A', 'B']);
if (gate(flags => flags.alwaysThrottleRetries)) {
// Correct behavior:
//
// The tree will finish but we won't commit the result yet because the fallback appeared recently.
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
} else {
// Old behavior, gated until this rolls out at Meta:
//
// TODO: Because this render was the result of a retry, and a fallback
// was shown recently, we should suspend and remain on the fallback for
// little bit longer. We currently only do this if there's still
// remaining fallbacks in the tree, but we should do it for all retries.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
}
});
assertLog([]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('throttles content from appearing if a fallback was filled in recently', async () => {
function Foo() {
Scheduler.log('Foo');
return (
<>
<Suspense fallback={<Text text="Loading A..." />}>
<AsyncText text="A" />
</Suspense>
<Suspense fallback={<Text text="Loading B..." />}>
<AsyncText text="B" />
</Suspense>
</>
);
}
ReactNoop.render(<Foo />);
// Start rendering
await waitForAll([
'Foo',
'Suspend! [A]',
'Loading A...',
'Suspend! [B]',
'Loading B...',
]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Loading A..." />
<span prop="Loading B..." />
</>,
);
// Resolve only A. B will still be loading.
await act(async () => {
await resolveText('A');
// If we didn't advance the time here, A would not commit; it would
// be throttled because the fallback would have appeared too recently.
Scheduler.unstable_advanceTime(10000);
jest.advanceTimersByTime(10000);
await waitForPaint(['A']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading B..." />
</>,
);
});
// Advance by a small amount of time. For testing purposes, this is meant
// to be just under the throttling interval. It's a heurstic, though, so
// if we adjust the heuristic we might have to update this test, too.
Scheduler.unstable_advanceTime(200);
jest.advanceTimersByTime(200);
// Now resolve B.
await act(async () => {
await resolveText('B');
await waitForPaint(['B']);
if (gate(flags => flags.alwaysThrottleRetries)) {
// B should not commit yet. Even though it's been a long time since its
// fallback was shown, it hasn't been long since A appeared. So B's
// appearance is throttled to reduce jank.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading B..." />
</>,
);
// Advance time a little bit more. Now it commits because enough time
// has passed.
Scheduler.unstable_advanceTime(100);
jest.advanceTimersByTime(100);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
} else {
// Old behavior, gated until this rolls out at Meta:
//
// B appears immediately, without being throttled.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
}
});
});
// TODO: flip to "warns" when this is implemented again.
// @gate enableLegacyCache
it('does not warn when a low priority update suspends inside a high priority update for functional components', async () => {
let _setShow;
function App() {
const [show, setShow] = React.useState(false);
_setShow = setShow;
return (
<Suspense fallback="Loading...">
{show && <AsyncText text="A" />}
</Suspense>
);
}
await act(() => {
ReactNoop.render(<App />);
});
// TODO: assert toErrorDev() when the warning is implemented again.
await act(() => {
ReactNoop.flushSync(() => _setShow(true));
});
});
// TODO: flip to "warns" when this is implemented again.
// @gate enableLegacyCache
it('does not warn when a low priority update suspends inside a high priority update for class components', async () => {
let show;
class App extends React.Component {
state = {show: false};
render() {
show = () => this.setState({show: true});
return (
<Suspense fallback="Loading...">
{this.state.show && <AsyncText text="A" />}
</Suspense>
);
}
}
await act(() => {
ReactNoop.render(<App />);
});
// TODO: assert toErrorDev() when the warning is implemented again.
await act(() => {
ReactNoop.flushSync(() => show());
});
});
// @gate enableLegacyCache
it('does not warn about wrong Suspense priority if no new fallbacks are shown', async () => {
let showB;
class App extends React.Component {
state = {showB: false};
render() {
showB = () => this.setState({showB: true});
return (
<Suspense fallback="Loading...">
{<AsyncText text="A" />}
{this.state.showB && <AsyncText text="B" />}
</Suspense>
);
}
}
await act(() => {
ReactNoop.render(<App />);
});
assertLog(['Suspend! [A]']);
expect(ReactNoop).toMatchRenderedOutput('Loading...');
await act(() => {
ReactNoop.flushSync(() => showB());
});
assertLog(['Suspend! [A]']);
});
// TODO: flip to "warns" when this is implemented again.
// @gate enableLegacyCache
it(
'does not warn when component that triggered user-blocking update is between Suspense boundary ' +
'and component that suspended',
async () => {
let _setShow;
function A() {
const [show, setShow] = React.useState(false);
_setShow = setShow;
return show && <AsyncText text="A" />;
}
function App() {
return (
<Suspense fallback="Loading...">
<A />
</Suspense>
);
}
await act(() => {
ReactNoop.render(<App />);
});
// TODO: assert toErrorDev() when the warning is implemented again.
await act(() => {
ReactNoop.flushSync(() => _setShow(true));
});
},
);
// @gate enableLegacyCache
it('normal priority updates suspending do not warn for class components', async () => {
let show;
class App extends React.Component {
state = {show: false};
render() {
show = () => this.setState({show: true});
return (
<Suspense fallback="Loading...">
{this.state.show && <AsyncText text="A" />}
</Suspense>
);
}
}
await act(() => {
ReactNoop.render(<App />);
});
// also make sure lowpriority is okay
await act(() => show(true));
assertLog(['Suspend! [A]']);
await resolveText('A');
expect(ReactNoop).toMatchRenderedOutput('Loading...');
});
// @gate enableLegacyCache
it('normal priority updates suspending do not warn for functional components', async () => {
let _setShow;
function App() {
const [show, setShow] = React.useState(false);
_setShow = setShow;
return (
<Suspense fallback="Loading...">
{show && <AsyncText text="A" />}
</Suspense>
);
}
await act(() => {
ReactNoop.render(<App />);
});
// also make sure lowpriority is okay
await act(() => _setShow(true));
assertLog(['Suspend! [A]']);
await resolveText('A');
expect(ReactNoop).toMatchRenderedOutput('Loading...');
});
// @gate enableLegacyCache && enableSuspenseAvoidThisFallback
it('shows the parent fallback if the inner fallback should be avoided', async () => {
function Foo({showC}) {
Scheduler.log('Foo');
return (
<Suspense fallback={<Text text="Initial load..." />}>
<Suspense
unstable_avoidThisFallback={true}
fallback={<Text text="Updating..." />}>
<AsyncText text="A" />
{showC ? <AsyncText text="C" /> : null}
</Suspense>
<Text text="B" />
</Suspense>
);
}
ReactNoop.render(<Foo />);
await waitForAll(['Foo', 'Suspend! [A]', 'Initial load...']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Initial load..." />);
// Eventually we resolve and show the data.
await act(() => resolveText('A'));
assertLog(['A', 'B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
// Update to show C
ReactNoop.render(<Foo showC={true} />);
await waitForAll(['Foo', 'A', 'Suspend! [C]', 'Updating...', 'B']);
// Flush to skip suspended time.
Scheduler.unstable_advanceTime(600);
await advanceTimers(600);
// Since the optional suspense boundary is already showing its content,
// we have to use the inner fallback instead.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" hidden={true} />
<span prop="Updating..." />
<span prop="B" />
</>,
);
// Later we load the data.
await act(() => resolveText('C'));
assertLog(['A', 'C']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="C" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('does not show the parent fallback if the inner fallback is not defined', async () => {
function Foo({showC}) {
Scheduler.log('Foo');
return (
<Suspense fallback={<Text text="Initial load..." />}>
<Suspense>
<AsyncText text="A" />
{showC ? <AsyncText text="C" /> : null}
</Suspense>
<Text text="B" />
</Suspense>
);
}
ReactNoop.render(<Foo />);
await waitForAll([
'Foo',
'Suspend! [A]',
'B',
// null
]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Eventually we resolve and show the data.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
// Update to show C
ReactNoop.render(<Foo showC={true} />);
await waitForAll([
'Foo',
'A',
'Suspend! [C]',
// null
'B',
]);
// Flush to skip suspended time.
Scheduler.unstable_advanceTime(600);
await advanceTimers(600);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" hidden={true} />
<span prop="B" />
</>,
);
// Later we load the data.
await act(() => resolveText('C'));
assertLog(['A', 'C']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="C" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache
it('favors showing the inner fallback for nested top level avoided fallback', async () => {
function Foo({showB}) {
Scheduler.log('Foo');
return (
<Suspense
unstable_avoidThisFallback={true}
fallback={<Text text="Loading A..." />}>
<Text text="A" />
<Suspense
unstable_avoidThisFallback={true}
fallback={<Text text="Loading B..." />}>
<AsyncText text="B" />
</Suspense>
</Suspense>
);
}
ReactNoop.render(<Foo />);
await waitForAll(['Foo', 'A', 'Suspend! [B]', 'Loading B...']);
// Flush to skip suspended time.
Scheduler.unstable_advanceTime(600);
await advanceTimers(600);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading B..." />
</>,
);
});
// @gate enableLegacyCache && enableSuspenseAvoidThisFallback
it('keeps showing an avoided parent fallback if it is already showing', async () => {
function Foo({showB}) {
Scheduler.log('Foo');
return (
<Suspense fallback={<Text text="Initial load..." />}>
<Suspense
unstable_avoidThisFallback={true}
fallback={<Text text="Loading A..." />}>
<Text text="A" />
{showB ? (
<Suspense
unstable_avoidThisFallback={true}
fallback={<Text text="Loading B..." />}>
<AsyncText text="B" />
</Suspense>
) : null}
</Suspense>
</Suspense>
);
}
ReactNoop.render(<Foo />);
await waitForAll(['Foo', 'A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
ReactNoop.render(<Foo showB={true} />);
} else {
React.startTransition(() => {
ReactNoop.render(<Foo showB={true} />);
});
}
await waitForAll(['Foo', 'A', 'Suspend! [B]', 'Loading B...']);
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading B..." />
</>,
);
} else {
// Transitions never fall back.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
}
});
// @gate enableLegacyCache
it('keeps showing an undefined fallback if it is already showing', async () => {
function Foo({showB}) {
Scheduler.log('Foo');
return (
<Suspense fallback={<Text text="Initial load..." />}>
<Suspense fallback={undefined}>
<Text text="A" />
{showB ? (
<Suspense fallback={undefined}>
<AsyncText text="B" />
</Suspense>
) : null}
</Suspense>
</Suspense>
);
}
ReactNoop.render(<Foo />);
await waitForAll(['Foo', 'A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
React.startTransition(() => {
ReactNoop.render(<Foo showB={true} />);
});
await waitForAll([
'Foo',
'A',
'Suspend! [B]',
// Null
]);
// Still suspended.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Flush to skip suspended time.
Scheduler.unstable_advanceTime(600);
await advanceTimers(600);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
});
describe('startTransition', () => {
// @gate enableLegacyCache
it('top level render', async () => {
function App({page}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={page} />
</Suspense>
);
}
// Initial render.
React.startTransition(() => ReactNoop.render(<App page="A" />));
await waitForAll(['Suspend! [A]', 'Loading...']);
// Only a short time is needed to unsuspend the initial loading state.
Scheduler.unstable_advanceTime(400);
await advanceTimers(400);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
// Later we load the data.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Start transition.
React.startTransition(() => ReactNoop.render(<App page="B" />));
await waitForAll(['Suspend! [B]', 'Loading...']);
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
// Even after lots of time has passed, we have still not yet flushed the
// loading state.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Later we load the data.
await act(() => resolveText('B'));
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
});
// @gate enableLegacyCache
it('hooks', async () => {
let transitionToPage;
function App() {
const [page, setPage] = React.useState('none');
transitionToPage = setPage;
if (page === 'none') {
return null;
}
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={page} />
</Suspense>
);
}
ReactNoop.render(<App />);
await waitForAll([]);
// Initial render.
await act(async () => {
React.startTransition(() => transitionToPage('A'));
await waitForAll(['Suspend! [A]', 'Loading...']);
// Only a short time is needed to unsuspend the initial loading state.
Scheduler.unstable_advanceTime(400);
await advanceTimers(400);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
});
// Later we load the data.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Start transition.
await act(async () => {
React.startTransition(() => transitionToPage('B'));
await waitForAll(['Suspend! [B]', 'Loading...']);
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
// Even after lots of time has passed, we have still not yet flushed the
// loading state.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
});
// Later we load the data.
await act(() => resolveText('B'));
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
});
// @gate enableLegacyCache
it('classes', async () => {
let transitionToPage;
class App extends React.Component {
state = {page: 'none'};
render() {
transitionToPage = page => this.setState({page});
const page = this.state.page;
if (page === 'none') {
return null;
}
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={page} />
</Suspense>
);
}
}
ReactNoop.render(<App />);
await waitForAll([]);
// Initial render.
await act(async () => {
React.startTransition(() => transitionToPage('A'));
await waitForAll(['Suspend! [A]', 'Loading...']);
// Only a short time is needed to unsuspend the initial loading state.
Scheduler.unstable_advanceTime(400);
await advanceTimers(400);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
});
// Later we load the data.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Start transition.
await act(async () => {
React.startTransition(() => transitionToPage('B'));
await waitForAll(['Suspend! [B]', 'Loading...']);
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
// Even after lots of time has passed, we have still not yet flushed the
// loading state.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
});
// Later we load the data.
await act(() => resolveText('B'));
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
});
});
describe('delays transitions when using React.startTransition', () => {
// @gate enableLegacyCache
it('top level render', async () => {
function App({page}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={page} />
</Suspense>
);
}
// Initial render.
React.startTransition(() => ReactNoop.render(<App page="A" />));
await waitForAll(['Suspend! [A]', 'Loading...']);
// Only a short time is needed to unsuspend the initial loading state.
Scheduler.unstable_advanceTime(400);
await advanceTimers(400);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
// Later we load the data.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Start transition.
React.startTransition(() => ReactNoop.render(<App page="B" />));
await waitForAll(['Suspend! [B]', 'Loading...']);
Scheduler.unstable_advanceTime(2999);
await advanceTimers(2999);
// Since the timeout is infinite (or effectively infinite),
// we have still not yet flushed the loading state.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Later we load the data.
await act(() => resolveText('B'));
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Start a long (infinite) transition.
React.startTransition(() => ReactNoop.render(<App page="C" />));
await waitForAll(['Suspend! [C]', 'Loading...']);
// Even after lots of time has passed, we have still not yet flushed the
// loading state.
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
});
// @gate enableLegacyCache
it('hooks', async () => {
let transitionToPage;
function App() {
const [page, setPage] = React.useState('none');
transitionToPage = setPage;
if (page === 'none') {
return null;
}
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={page} />
</Suspense>
);
}
ReactNoop.render(<App />);
await waitForAll([]);
// Initial render.
await act(async () => {
React.startTransition(() => transitionToPage('A'));
await waitForAll(['Suspend! [A]', 'Loading...']);
// Only a short time is needed to unsuspend the initial loading state.
Scheduler.unstable_advanceTime(400);
await advanceTimers(400);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
});
// Later we load the data.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Start transition.
await act(async () => {
React.startTransition(() => transitionToPage('B'));
await waitForAll(['Suspend! [B]', 'Loading...']);
Scheduler.unstable_advanceTime(2999);
await advanceTimers(2999);
// Since the timeout is infinite (or effectively infinite),
// we have still not yet flushed the loading state.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
});
// Later we load the data.
await act(() => resolveText('B'));
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Start a long (infinite) transition.
await act(async () => {
React.startTransition(() => transitionToPage('C'));
await waitForAll(['Suspend! [C]', 'Loading...']);
// Even after lots of time has passed, we have still not yet flushed the
// loading state.
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
});
});
// @gate enableLegacyCache
it('classes', async () => {
let transitionToPage;
class App extends React.Component {
state = {page: 'none'};
render() {
transitionToPage = page => this.setState({page});
const page = this.state.page;
if (page === 'none') {
return null;
}
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={page} />
</Suspense>
);
}
}
ReactNoop.render(<App />);
await waitForAll([]);
// Initial render.
await act(async () => {
React.startTransition(() => transitionToPage('A'));
await waitForAll(['Suspend! [A]', 'Loading...']);
// Only a short time is needed to unsuspend the initial loading state.
Scheduler.unstable_advanceTime(400);
await advanceTimers(400);
expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />);
});
// Later we load the data.
await act(() => resolveText('A'));
assertLog(['A']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
// Start transition.
await act(async () => {
React.startTransition(() => transitionToPage('B'));
await waitForAll(['Suspend! [B]', 'Loading...']);
Scheduler.unstable_advanceTime(2999);
await advanceTimers(2999);
// Since the timeout is infinite (or effectively infinite),
// we have still not yet flushed the loading state.
expect(ReactNoop).toMatchRenderedOutput(<span prop="A" />);
});
// Later we load the data.
await act(() => resolveText('B'));
assertLog(['B']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Start a long (infinite) transition.
await act(async () => {
React.startTransition(() => transitionToPage('C'));
await waitForAll(['Suspend! [C]', 'Loading...']);
// Even after lots of time has passed, we have still not yet flushed the
// loading state.
Scheduler.unstable_advanceTime(100000);
await advanceTimers(100000);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
});
});
});
// @gate enableLegacyCache && enableSuspenseAvoidThisFallback
it('do not show placeholder when updating an avoided boundary with startTransition', async () => {
function App({page}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Text text="Hi!" />
<Suspense
fallback={<Text text={'Loading ' + page + '...'} />}
unstable_avoidThisFallback={true}>
<AsyncText text={page} />
</Suspense>
</Suspense>
);
}
// Initial render.
ReactNoop.render(<App page="A" />);
await waitForAll(['Hi!', 'Suspend! [A]', 'Loading...']);
await act(() => resolveText('A'));
assertLog(['Hi!', 'A']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="A" />
</>,
);
// Start transition.
React.startTransition(() => ReactNoop.render(<App page="B" />));
await waitForAll(['Hi!', 'Suspend! [B]', 'Loading B...']);
// Suspended
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="A" />
</>,
);
Scheduler.unstable_advanceTime(1800);
await advanceTimers(1800);
await waitForAll([]);
// We should still be suspended here because this loading state should be avoided.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="A" />
</>,
);
await resolveText('B');
await waitForAll(['Hi!', 'B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="B" />
</>,
);
});
// @gate enableLegacyCache && enableSuspenseAvoidThisFallback
it('do not show placeholder when mounting an avoided boundary with startTransition', async () => {
function App({page}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Text text="Hi!" />
{page === 'A' ? (
<Text text="A" />
) : (
<Suspense
fallback={<Text text={'Loading ' + page + '...'} />}
unstable_avoidThisFallback={true}>
<AsyncText text={page} />
</Suspense>
)}
</Suspense>
);
}
// Initial render.
ReactNoop.render(<App page="A" />);
await waitForAll(['Hi!', 'A']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="A" />
</>,
);
// Start transition.
React.startTransition(() => ReactNoop.render(<App page="B" />));
await waitForAll(['Hi!', 'Suspend! [B]', 'Loading B...']);
// Suspended
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="A" />
</>,
);
Scheduler.unstable_advanceTime(1800);
await advanceTimers(1800);
await waitForAll([]);
// We should still be suspended here because this loading state should be avoided.
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="A" />
</>,
);
await resolveText('B');
await waitForAll(['Hi!', 'B']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<span prop="Hi!" />
<span prop="B" />
</>,
);
});
it('regression test: resets current "debug phase" after suspending', async () => {
function App() {
return (
<Suspense fallback="Loading...">
<Foo suspend={false} />
</Suspense>
);
}
const thenable = {then() {}};
let foo;
class Foo extends React.Component {
state = {suspend: false};
render() {
foo = this;
if (this.state.suspend) {
Scheduler.log('Suspend!');
throw thenable;
}
return <Text text="Foo" />;
}
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['Foo']);
await act(async () => {
foo.setState({suspend: true});
// In the regression that this covers, we would neglect to reset the
// current debug phase after suspending (in the catch block), so React
// thinks we're still inside the render phase.
await waitFor(['Suspend!']);
// Then when this setState happens, React would incorrectly fire a warning
// about updates that happen the render phase (only fired by classes).
foo.setState({suspend: false});
});
assertLog([
// First setState
'Foo',
]);
expect(root).toMatchRenderedOutput(<span prop="Foo" />);
});
// @gate enableLegacyCache && enableLegacyHidden
it('should not render hidden content while suspended on higher pri', async () => {
function Offscreen() {
Scheduler.log('Offscreen');
return 'Offscreen';
}
function App({showContent}) {
React.useLayoutEffect(() => {
Scheduler.log('Commit');
});
return (
<>
<LegacyHiddenDiv mode="hidden">
<Offscreen />
</LegacyHiddenDiv>
<Suspense fallback={<Text text="Loading..." />}>
{showContent ? <AsyncText text="A" ms={2000} /> : null}
</Suspense>
</>
);
}
// Initial render.
ReactNoop.render(<App showContent={false} />);
await waitFor(['Commit']);
expect(ReactNoop).toMatchRenderedOutput(<div hidden={true} />);
// Start transition.
React.startTransition(() => {
ReactNoop.render(<App showContent={true} />);
});
await waitForAll(['Suspend! [A]', 'Loading...']);
await resolveText('A');
await waitFor(['A', 'Commit']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<div hidden={true} />
<span prop="A" />
</>,
);
await waitForAll(['Offscreen']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<div hidden={true}>Offscreen</div>
<span prop="A" />
</>,
);
});
// @gate enableLegacyCache && enableLegacyHidden
it('should be able to unblock higher pri content before suspended hidden', async () => {
function Offscreen() {
Scheduler.log('Offscreen');
return 'Offscreen';
}
function App({showContent}) {
React.useLayoutEffect(() => {
Scheduler.log('Commit');
});
return (
<Suspense fallback={<Text text="Loading..." />}>
<LegacyHiddenDiv mode="hidden">
<AsyncText text="A" />
<Offscreen />
</LegacyHiddenDiv>
{showContent ? <AsyncText text="A" /> : null}
</Suspense>
);
}
// Initial render.
ReactNoop.render(<App showContent={false} />);
await waitFor(['Commit']);
expect(ReactNoop).toMatchRenderedOutput(<div hidden={true} />);
// Partially render through the hidden content.
await waitFor(['Suspend! [A]']);
// Start transition.
React.startTransition(() => {
ReactNoop.render(<App showContent={true} />);
});
await waitForAll(['Suspend! [A]', 'Loading...']);
await resolveText('A');
await waitFor(['A', 'Commit']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<div hidden={true} />
<span prop="A" />
</>,
);
await waitForAll(['A', 'Offscreen']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<div hidden={true}>
<span prop="A" />
Offscreen
</div>
<span prop="A" />
</>,
);
});
// @gate enableLegacyCache
it(
'multiple updates originating inside a Suspense boundary at different ' +
'priority levels are not dropped',
async () => {
const {useState} = React;
const root = ReactNoop.createRoot();
function Parent() {
return (
<>
<Suspense fallback={<Text text="Loading..." />}>
<Child />
</Suspense>
</>
);
}
let setText;
function Child() {
const [text, _setText] = useState('A');
setText = _setText;
return <AsyncText text={text} />;
}
await seedNextTextCache('A');
await act(() => {
root.render(<Parent />);
});
assertLog(['A']);
expect(root).toMatchRenderedOutput(<span prop="A" />);
await act(async () => {
// Schedule two updates that originate inside the Suspense boundary.
// The first one causes the boundary to suspend. The second one is at
// lower priority and unsuspends the tree.
ReactNoop.discreteUpdates(() => {
setText('B');
});
startTransition(() => {
setText('C');
});
// Assert that neither update has happened yet. Both the high pri and
// low pri updates are in the queue.
assertLog([]);
// Resolve this before starting to render so that C doesn't suspend.
await resolveText('C');
});
assertLog([
// First we attempt the high pri update. It suspends.
'Suspend! [B]',
'Loading...',
// Then we attempt the low pri update, which finishes successfully.
'C',
]);
expect(root).toMatchRenderedOutput(<span prop="C" />);
},
);
// @gate enableLegacyCache
it(
'multiple updates originating inside a Suspense boundary at different ' +
'priority levels are not dropped, including Idle updates',
async () => {
const {useState} = React;
const root = ReactNoop.createRoot();
function Parent() {
return (
<>
<Suspense fallback={<Text text="Loading..." />}>
<Child />
</Suspense>
</>
);
}
let setText;
function Child() {
const [text, _setText] = useState('A');
setText = _setText;
return <AsyncText text={text} />;
}
await seedNextTextCache('A');
await act(() => {
root.render(<Parent />);
});
assertLog(['A']);
expect(root).toMatchRenderedOutput(<span prop="A" />);
await act(async () => {
// Schedule two updates that originate inside the Suspense boundary.
// The first one causes the boundary to suspend. The second one is at
// lower priority and unsuspends it by hiding the async component.
setText('B');
await resolveText('C');
ReactNoop.idleUpdates(() => {
setText('C');
});
// First we attempt the high pri update. It suspends.
await waitForPaint(['Suspend! [B]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span prop="Loading..." />
</>,
);
// Now flush the remaining work. The Idle update successfully finishes.
await waitForAll(['C']);
expect(root).toMatchRenderedOutput(<span prop="C" />);
});
},
);
// @gate enableLegacyCache
it(
'fallback component can update itself even after a high pri update to ' +
'the primary tree suspends',
async () => {
const {useState} = React;
const root = ReactNoop.createRoot();
let setAppText;
function App() {
const [text, _setText] = useState('A');
setAppText = _setText;
return (
<>
<Suspense fallback={<Fallback />}>
<AsyncText text={text} />
</Suspense>
</>
);
}
let setFallbackText;
function Fallback() {
const [text, _setText] = useState('Loading...');
setFallbackText = _setText;
return <Text text={text} />;
}
// Resolve the initial tree
await seedNextTextCache('A');
await act(() => {
root.render(<App />);
});
assertLog(['A']);
expect(root).toMatchRenderedOutput(<span prop="A" />);
await act(async () => {
// Schedule an update inside the Suspense boundary that suspends.
setAppText('B');
await waitForAll(['Suspend! [B]', 'Loading...']);
});
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span prop="Loading..." />
</>,
);
// Schedule a default pri update on the boundary, and a lower pri update
// on the fallback. We're testing to make sure the fallback can still
// update even though the primary tree is suspended.
await act(() => {
setAppText('C');
React.startTransition(() => {
setFallbackText('Still loading...');
});
});
assertLog([
// First try to render the high pri update. Still suspended.
'Suspend! [C]',
'Loading...',
// In the expiration times model, once the high pri update suspends,
// we can't be sure if there's additional work at a lower priority
// that might unblock the tree. We do know that there's a lower
// priority update *somewhere* in the entire root, though (the update
// to the fallback). So we try rendering one more time, just in case.
// TODO: We shouldn't need to do this with lanes, because we always
// know exactly which lanes have pending work in each tree.
'Suspend! [C]',
// Then complete the update to the fallback.
'Still loading...',
]);
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span prop="Still loading..." />
</>,
);
},
);
// @gate enableLegacyCache
it(
'regression: primary fragment fiber is not always part of setState ' +
'return path',
async () => {
// Reproduces a bug where updates inside a suspended tree are dropped
// because the fragment fiber we insert to wrap the hidden children is not
// part of the return path, so it doesn't get marked during setState.
const {useState} = React;
const root = ReactNoop.createRoot();
function Parent() {
return (
<>
<Suspense fallback={<Text text="Loading..." />}>
<Child />
</Suspense>
</>
);
}
let setText;
function Child() {
const [text, _setText] = useState('A');
setText = _setText;
return <AsyncText text={text} />;
}
// Mount an initial tree. Resolve A so that it doesn't suspend.
await seedNextTextCache('A');
await act(() => {
root.render(<Parent />);
});
assertLog(['A']);
// At this point, the setState return path follows current fiber.
expect(root).toMatchRenderedOutput(<span prop="A" />);
// Schedule another update. This will "flip" the alternate pairs.
await resolveText('B');
await act(() => {
setText('B');
});
assertLog(['B']);
// Now the setState return path follows the *alternate* fiber.
expect(root).toMatchRenderedOutput(<span prop="B" />);
// Schedule another update. This time, we'll suspend.
await act(() => {
setText('C');
});
assertLog(['Suspend! [C]', 'Loading...']);
// Commit. This will insert a fragment fiber to wrap around the component
// that triggered the update.
await act(async () => {
await advanceTimers(250);
});
// The fragment fiber is part of the current tree, but the setState return
// path still follows the alternate path. That means the fragment fiber is
// not part of the return path.
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="B" />
<span prop="Loading..." />
</>,
);
// Update again. This should unsuspend the tree.
await resolveText('D');
await act(() => {
setText('D');
});
// Even though the fragment fiber is not part of the return path, we should
// be able to finish rendering.
assertLog(['D']);
expect(root).toMatchRenderedOutput(<span prop="D" />);
},
);
// @gate enableLegacyCache
it(
'regression: primary fragment fiber is not always part of setState ' +
'return path (another case)',
async () => {
// Reproduces a bug where updates inside a suspended tree are dropped
// because the fragment fiber we insert to wrap the hidden children is not
// part of the return path, so it doesn't get marked during setState.
const {useState} = React;
const root = ReactNoop.createRoot();
function Parent() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Child />
</Suspense>
);
}
let setText;
function Child() {
const [text, _setText] = useState('A');
setText = _setText;
return <AsyncText text={text} />;
}
// Mount an initial tree. Resolve A so that it doesn't suspend.
await seedNextTextCache('A');
await act(() => {
root.render(<Parent />);
});
assertLog(['A']);
// At this point, the setState return path follows current fiber.
expect(root).toMatchRenderedOutput(<span prop="A" />);
// Schedule another update. This will "flip" the alternate pairs.
await resolveText('B');
await act(() => {
setText('B');
});
assertLog(['B']);
// Now the setState return path follows the *alternate* fiber.
expect(root).toMatchRenderedOutput(<span prop="B" />);
// Schedule another update. This time, we'll suspend.
await act(() => {
setText('C');
});
assertLog(['Suspend! [C]', 'Loading...']);
// Commit. This will insert a fragment fiber to wrap around the component
// that triggered the update.
await act(async () => {
await advanceTimers(250);
});
// The fragment fiber is part of the current tree, but the setState return
// path still follows the alternate path. That means the fragment fiber is
// not part of the return path.
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="B" />
<span prop="Loading..." />
</>,
);
await act(async () => {
// Schedule a normal pri update. This will suspend again.
setText('D');
// And another update at lower priority. This will unblock.
await resolveText('E');
ReactNoop.idleUpdates(() => {
setText('E');
});
});
// Even though the fragment fiber is not part of the return path, we should
// be able to finish rendering.
assertLog(['Suspend! [D]', 'E']);
expect(root).toMatchRenderedOutput(<span prop="E" />);
},
);
// @gate enableLegacyCache
it(
'after showing fallback, should not flip back to primary content until ' +
'the update that suspended finishes',
async () => {
const {useState, useEffect} = React;
const root = ReactNoop.createRoot();
let setOuterText;
function Parent({step}) {
const [text, _setText] = useState('A');
setOuterText = _setText;
return (
<>
<Text text={'Outer text: ' + text} />
<Text text={'Outer step: ' + step} />
<Suspense fallback={<Text text="Loading..." />}>
<Child step={step} outerText={text} />
</Suspense>
</>
);
}
let setInnerText;
function Child({step, outerText}) {
const [text, _setText] = useState('A');
setInnerText = _setText;
// This will log if the component commits in an inconsistent state
useEffect(() => {
if (text === outerText) {
Scheduler.log('Commit Child');
} else {
Scheduler.log('FIXME: Texts are inconsistent (tearing)');
}
}, [text, outerText]);
return (
<>
<AsyncText text={'Inner text: ' + text} />
<Text text={'Inner step: ' + step} />
</>
);
}
// These always update simultaneously. They must be consistent.
function setText(text) {
setOuterText(text);
setInnerText(text);
}
// Mount an initial tree. Resolve A so that it doesn't suspend.
await seedNextTextCache('Inner text: A');
await act(() => {
root.render(<Parent step={0} />);
});
assertLog([
'Outer text: A',
'Outer step: 0',
'Inner text: A',
'Inner step: 0',
'Commit Child',
]);
expect(root).toMatchRenderedOutput(
<>
<span prop="Outer text: A" />
<span prop="Outer step: 0" />
<span prop="Inner text: A" />
<span prop="Inner step: 0" />
</>,
);
// Update. This causes the inner component to suspend.
await act(() => {
setText('B');
});
assertLog([
'Outer text: B',
'Outer step: 0',
'Suspend! [Inner text: B]',
'Loading...',
]);
// Commit the placeholder
await advanceTimers(250);
expect(root).toMatchRenderedOutput(
<>
<span prop="Outer text: B" />
<span prop="Outer step: 0" />
<span hidden={true} prop="Inner text: A" />
<span hidden={true} prop="Inner step: 0" />
<span prop="Loading..." />
</>,
);
// Schedule a high pri update on the parent.
await act(() => {
ReactNoop.discreteUpdates(() => {
root.render(<Parent step={1} />);
});
});
// Only the outer part can update. The inner part should still show a
// fallback because we haven't finished loading B yet. Otherwise, the
// inner text would be inconsistent with the outer text.
assertLog([
'Outer text: B',
'Outer step: 1',
'Suspend! [Inner text: B]',
'Loading...',
]);
expect(root).toMatchRenderedOutput(
<>
<span prop="Outer text: B" />
<span prop="Outer step: 1" />
<span hidden={true} prop="Inner text: A" />
<span hidden={true} prop="Inner step: 0" />
<span prop="Loading..." />
</>,
);
// Now finish resolving the inner text
await act(async () => {
await resolveText('Inner text: B');
});
assertLog(['Inner text: B', 'Inner step: 1', 'Commit Child']);
expect(root).toMatchRenderedOutput(
<>
<span prop="Outer text: B" />
<span prop="Outer step: 1" />
<span prop="Inner text: B" />
<span prop="Inner step: 1" />
</>,
);
},
);
// @gate enableLegacyCache
it('a high pri update can unhide a boundary that suspended at a different level', async () => {
const {useState, useEffect} = React;
const root = ReactNoop.createRoot();
let setOuterText;
function Parent({step}) {
const [text, _setText] = useState('A');
setOuterText = _setText;
return (
<>
<Text text={'Outer: ' + text + step} />
<Suspense fallback={<Text text="Loading..." />}>
<Child step={step} outerText={text} />
</Suspense>
</>
);
}
let setInnerText;
function Child({step, outerText}) {
const [text, _setText] = useState('A');
setInnerText = _setText;
// This will log if the component commits in an inconsistent state
useEffect(() => {
if (text === outerText) {
Scheduler.log('Commit Child');
} else {
Scheduler.log('FIXME: Texts are inconsistent (tearing)');
}
}, [text, outerText]);
return (
<>
<AsyncText text={'Inner: ' + text + step} />
</>
);
}
// These always update simultaneously. They must be consistent.
function setText(text) {
setOuterText(text);
setInnerText(text);
}
// Mount an initial tree. Resolve A so that it doesn't suspend.
await seedNextTextCache('Inner: A0');
await act(() => {
root.render(<Parent step={0} />);
});
assertLog(['Outer: A0', 'Inner: A0', 'Commit Child']);
expect(root).toMatchRenderedOutput(
<>
<span prop="Outer: A0" />
<span prop="Inner: A0" />
</>,
);
// Update. This causes the inner component to suspend.
await act(() => {
setText('B');
});
assertLog(['Outer: B0', 'Suspend! [Inner: B0]', 'Loading...']);
// Commit the placeholder
await advanceTimers(250);
expect(root).toMatchRenderedOutput(
<>
<span prop="Outer: B0" />
<span hidden={true} prop="Inner: A0" />
<span prop="Loading..." />
</>,
);
// Schedule a high pri update on the parent. This will unblock the content.
await resolveText('Inner: B1');
await act(() => {
ReactNoop.discreteUpdates(() => {
root.render(<Parent step={1} />);
});
});
assertLog(['Outer: B1', 'Inner: B1', 'Commit Child']);
expect(root).toMatchRenderedOutput(
<>
<span prop="Outer: B1" />
<span prop="Inner: B1" />
</>,
);
});
// @gate enableLegacyCache
// @gate forceConcurrentByDefaultForTesting
it('regression: ping at high priority causes update to be dropped', async () => {
const {useState, useTransition} = React;
let setTextA;
function A() {
const [textA, _setTextA] = useState('A');
setTextA = _setTextA;
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={textA} />
</Suspense>
);
}
let setTextB;
let startTransitionFromB;
function B() {
const [textB, _setTextB] = useState('B');
// eslint-disable-next-line no-unused-vars
const [_, _startTransition] = useTransition();
startTransitionFromB = _startTransition;
setTextB = _setTextB;
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={textB} />
</Suspense>
);
}
function App() {
return (
<>
<A />
<B />
</>
);
}
const root = ReactNoop.createRoot();
await act(async () => {
await seedNextTextCache('A');
await seedNextTextCache('B');
root.render(<App />);
});
assertLog(['A', 'B']);
expect(root).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="B" />
</>,
);
await act(async () => {
// Triggers suspense at normal pri
setTextA('A1');
// Triggers in an unrelated tree at a different pri
startTransitionFromB(() => {
// Update A again so that it doesn't suspend on A1. That way we can ping
// the A1 update without also pinging this one. This is a workaround
// because there's currently no way to render at a lower priority (B2)
// without including all updates at higher priority (A1).
setTextA('A2');
setTextB('B2');
});
await waitFor([
'B',
'Suspend! [A1]',
'Loading...',
'Suspend! [A2]',
'Loading...',
'Suspend! [B2]',
'Loading...',
]);
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span prop="Loading..." />
<span prop="B" />
</>,
);
await resolveText('A1');
await waitFor(['A1']);
});
assertLog(['Suspend! [A2]', 'Loading...', 'Suspend! [B2]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span prop="A1" />
<span prop="B" />
</>,
);
await act(async () => {
await resolveText('A2');
await resolveText('B2');
});
assertLog(['A2', 'B2']);
expect(root).toMatchRenderedOutput(
<>
<span prop="A2" />
<span prop="B2" />
</>,
);
});
// Regression: https://github.com/facebook/react/issues/18486
// @gate enableLegacyCache
it('does not get stuck in pending state with render phase updates', async () => {
let setTextWithShortTransition;
let setTextWithLongTransition;
function App() {
const [isPending1, startShortTransition] = React.useTransition();
const [isPending2, startLongTransition] = React.useTransition();
const isPending = isPending1 || isPending2;
const [text, setText] = React.useState('');
const [mirror, setMirror] = React.useState('');
if (text !== mirror) {
// Render phase update was needed to repro the bug.
setMirror(text);
}
setTextWithShortTransition = value => {
startShortTransition(() => {
setText(value);
});
};
setTextWithLongTransition = value => {
startLongTransition(() => {
setText(value);
});
};
return (
<>
{isPending ? <Text text="Pending..." /> : null}
{text !== '' ? <AsyncText text={text} /> : <Text text={text} />}
</>
);
}
function Root() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<Root />);
});
assertLog(['']);
expect(root).toMatchRenderedOutput(<span prop="" />);
// Update to "a". That will suspend.
await act(async () => {
setTextWithShortTransition('a');
await waitForAll(['Pending...', '', 'Suspend! [a]', 'Loading...']);
});
assertLog([]);
expect(root).toMatchRenderedOutput(
<>
<span prop="Pending..." />
<span prop="" />
</>,
);
// Update to "b". That will suspend, too.
await act(async () => {
setTextWithLongTransition('b');
await waitForAll([
// Neither is resolved yet.
'Pending...',
'',
'Suspend! [b]',
'Loading...',
]);
});
assertLog([]);
expect(root).toMatchRenderedOutput(
<>
<span prop="Pending..." />
<span prop="" />
</>,
);
// Resolve "a". But "b" is still pending.
await act(async () => {
await resolveText('a');
await waitForAll(['Suspend! [b]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span prop="Pending..." />
<span prop="" />
</>,
);
// Resolve "b". This should remove the pending state.
await act(async () => {
await resolveText('b');
});
assertLog(['b']);
// The bug was that the pending state got stuck forever.
expect(root).toMatchRenderedOutput(<span prop="b" />);
});
});
// @gate enableLegacyCache
it('regression: #18657', async () => {
const {useState} = React;
let setText;
function App() {
const [text, _setText] = useState('A');
setText = _setText;
return <AsyncText text={text} />;
}
const root = ReactNoop.createRoot();
await act(async () => {
await seedNextTextCache('A');
root.render(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
);
});
assertLog(['A']);
expect(root).toMatchRenderedOutput(<span prop="A" />);
await act(async () => {
setText('B');
ReactNoop.idleUpdates(() => {
setText('C');
});
// Suspend the first update. This triggers an immediate fallback because
// it wasn't wrapped in startTransition.
await waitForPaint(['Suspend! [B]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="A" />
<span prop="Loading..." />
</>,
);
// Once the fallback renders, proceed to the Idle update. This will
// also suspend.
await waitForAll(['Suspend! [C]']);
});
// Finish loading B.
await act(async () => {
setText('B');
await resolveText('B');
});
// We did not try to render the Idle update again because there have been no
// additional updates since the last time it was attempted.
assertLog(['B']);
expect(root).toMatchRenderedOutput(<span prop="B" />);
// Finish loading C.
await act(async () => {
setText('C');
await resolveText('C');
});
assertLog(['C']);
expect(root).toMatchRenderedOutput(<span prop="C" />);
});
// @gate enableLegacyCache
it('retries have lower priority than normal updates', async () => {
const {useState} = React;
let setText;
function UpdatingText() {
const [text, _setText] = useState('A');
setText = _setText;
return <Text text={text} />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(
<>
<UpdatingText />
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" />
</Suspense>
</>,
);
});
assertLog(['A', 'Suspend! [Async]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span prop="A" />
<span prop="Loading..." />
</>,
);
await act(async () => {
// Resolve the promise. This will trigger a retry.
await resolveText('Async');
// Before the retry happens, schedule a new update.
setText('B');
// The update should be allowed to finish before the retry is attempted.
await waitForPaint(['B']);
expect(root).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="Loading..." />
</>,
);
});
// Then do the retry.
assertLog(['Async']);
expect(root).toMatchRenderedOutput(
<>
<span prop="B" />
<span prop="Async" />
</>,
);
});
// @gate enableLegacyCache
it('should fire effect clean-up when deleting suspended tree', async () => {
const {useEffect} = React;
function App({show}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Child />
{show && <AsyncText text="Async" />}
</Suspense>
);
}
function Child() {
useEffect(() => {
Scheduler.log('Mount Child');
return () => {
Scheduler.log('Unmount Child');
};
}, []);
return <span prop="Child" />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App show={false} />);
});
assertLog(['Mount Child']);
expect(root).toMatchRenderedOutput(<span prop="Child" />);
await act(() => {
root.render(<App show={true} />);
});
assertLog(['Suspend! [Async]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="Child" />
<span prop="Loading..." />
</>,
);
await act(() => {
root.render(null);
});
assertLog(['Unmount Child']);
});
// @gate enableLegacyCache
it('should fire effect clean-up when deleting suspended tree (legacy)', async () => {
const {useEffect} = React;
function App({show}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Child />
{show && <AsyncText text="Async" />}
</Suspense>
);
}
function Child() {
useEffect(() => {
Scheduler.log('Mount Child');
return () => {
Scheduler.log('Unmount Child');
};
}, []);
return <span prop="Child" />;
}
const root = ReactNoop.createLegacyRoot();
await act(() => {
root.render(<App show={false} />);
});
assertLog(['Mount Child']);
expect(root).toMatchRenderedOutput(<span prop="Child" />);
await act(() => {
root.render(<App show={true} />);
});
assertLog(['Suspend! [Async]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span hidden={true} prop="Child" />
<span prop="Loading..." />
</>,
);
await act(() => {
root.render(null);
});
assertLog(['Unmount Child']);
});
// @gate enableLegacyCache
it(
'regression test: pinging synchronously within the render phase ' +
'does not unwind the stack',
async () => {
// This is a regression test that reproduces a very specific scenario that
// used to cause a crash.
const thenable = {
then(resolve) {
resolve('hi');
},
status: 'pending',
};
function ImmediatelyPings() {
if (thenable.status === 'pending') {
thenable.status = 'fulfilled';
throw thenable;
}
return <Text text="Hi" />;
}
function App({showMore}) {
return (
<div>
<Suspense fallback={<Text text="Loading..." />}>
{showMore ? (
<>
<AsyncText text="Async" />
</>
) : null}
</Suspense>
{showMore ? (
<Suspense>
<ImmediatelyPings />
</Suspense>
) : null}
</div>
);
}
// Initial render. This mounts a Suspense boundary, so that in the next
// update we can trigger a "suspend with delay" scenario.
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App showMore={false} />);
});
assertLog([]);
expect(root).toMatchRenderedOutput(<div />);
// Update. This will cause two separate trees to suspend. The first tree
// will be inside an already mounted Suspense boundary, so it will trigger
// a "suspend with delay". The second tree will be a new Suspense
// boundary, but the thenable that is thrown will immediately call its
// ping listener.
//
// Before the bug was fixed, this would lead to a `prepareFreshStack` call
// that unwinds the work-in-progress stack. When that code was written, it
// was expected that pings always happen from an asynchronous task (or
// microtask). But this test shows an example where that's not the case.
//
// The fix was to check if we're in the render phase before calling
// `prepareFreshStack`.
await act(() => {
root.render(<App showMore={true} />);
});
assertLog(['Suspend! [Async]', 'Loading...', 'Hi']);
expect(root).toMatchRenderedOutput(
<div>
<span prop="Loading..." />
<span prop="Hi" />
</div>,
);
},
);
// @gate enableLegacyCache && enableRetryLaneExpiration
it('recurring updates in siblings should not block expensive content in suspense boundary from committing', async () => {
const {useState} = React;
let setText;
function UpdatingText() {
const [text, _setText] = useState('1');
setText = _setText;
return <Text text={text} />;
}
function ExpensiveText({text, ms}) {
Scheduler.log(text);
Scheduler.unstable_advanceTime(ms);
return <span prop={text} />;
}
function App() {
return (
<>
<UpdatingText />
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" />
<ExpensiveText text="A" ms={1000} />
<ExpensiveText text="B" ms={3999} />
<ExpensiveText text="C" ms={100000} />
</Suspense>
</>
);
}
const root = ReactNoop.createRoot();
root.render(<App />);
await waitForAll(['1', 'Suspend! [Async]', 'Loading...']);
expect(root).toMatchRenderedOutput(
<>
<span prop="1" />
<span prop="Loading..." />
</>,
);
await resolveText('Async');
expect(root).toMatchRenderedOutput(
<>
<span prop="1" />
<span prop="Loading..." />
</>,
);
await waitFor(['Async', 'A', 'B']);
ReactNoop.expire(100000);
await advanceTimers(100000);
setText('2');
await waitForPaint(['2']);
await waitForMicrotasks();
Scheduler.unstable_flushNumberOfYields(1);
assertLog(['Async', 'A', 'B', 'C']);
expect(root).toMatchRenderedOutput(
<>
<span prop="2" />
<span prop="Async" />
<span prop="A" />
<span prop="B" />
<span prop="C" />
</>,
);
});
});
| 27.278893 | 127 | 0.539241 |
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';
// Requires
let React;
let ReactDOM;
let ReactTestUtils;
// Test components
let LowerLevelComposite;
let MyCompositeComponent;
let expectSingleChildlessDiv;
/**
* Integration test, testing the combination of JSX with our unit of
* abstraction, `ReactCompositeComponent` does not ever add superfluous DOM
* nodes.
*/
describe('ReactCompositeComponentDOMMinimalism', () => {
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-dom/test-utils');
LowerLevelComposite = class extends React.Component {
render() {
return <div>{this.props.children}</div>;
}
};
MyCompositeComponent = class extends React.Component {
render() {
return <LowerLevelComposite>{this.props.children}</LowerLevelComposite>;
}
};
expectSingleChildlessDiv = function (instance) {
const el = ReactDOM.findDOMNode(instance);
expect(el.tagName).toBe('DIV');
expect(el.children.length).toBe(0);
};
});
it('should not render extra nodes for non-interpolated text', () => {
let instance = <MyCompositeComponent>A string child</MyCompositeComponent>;
instance = ReactTestUtils.renderIntoDocument(instance);
expectSingleChildlessDiv(instance);
});
it('should not render extra nodes for non-interpolated text', () => {
let instance = (
<MyCompositeComponent>{'Interpolated String Child'}</MyCompositeComponent>
);
instance = ReactTestUtils.renderIntoDocument(instance);
expectSingleChildlessDiv(instance);
});
it('should not render extra nodes for non-interpolated text', () => {
let instance = (
<MyCompositeComponent>
<ul>This text causes no children in ul, just innerHTML</ul>
</MyCompositeComponent>
);
instance = ReactTestUtils.renderIntoDocument(instance);
const el = ReactDOM.findDOMNode(instance);
expect(el.tagName).toBe('DIV');
expect(el.children.length).toBe(1);
expect(el.children[0].tagName).toBe('UL');
expect(el.children[0].children.length).toBe(0);
});
});
| 27.777778 | 80 | 0.684979 |
owtf | import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
| 23.142857 | 58 | 0.708333 |
Python-Penetration-Testing-Cookbook | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
*/
import type {
HookMap,
HookMapEntry,
HookMapLine,
HookMapMappings,
} from './generateHookMap';
import type {Position} from './astUtils';
import {NO_HOOK_NAME} from './astUtils';
/**
* Finds the Hook name assigned to a given location in the source code,
* and a HookMap extracted from an extended source map.
* The given location must correspond to the location in the *original*
* source code (i.e. *not* the generated one).
*
* Note that all locations in the source code are guaranteed to map
* to a name, including a sentinel value that represents a missing
* Hook name: '<no-hook>'.
*
* For more details on the format of the HookMap, see generateHookMap
* and the tests for that function and this function.
*/
export function getHookNameForLocation(
location: Position,
hookMap: HookMap,
): string | null {
const {names, mappings} = hookMap;
// The HookMap mappings are grouped by lines, so first we look up
// which line of mappings covers the target location.
// Note that we expect to find a line since all the locations in the
// source code are guaranteed to map to a name, including a '<no-hook>'
// name.
const foundLine = binSearch(location, mappings, compareLinePositions);
if (foundLine == null) {
throw new Error(
`Expected to find a line in the HookMap that covers the target location at line: ${location.line}, column: ${location.column}`,
);
}
let foundEntry;
const foundLineNumber = getLineNumberFromLine(foundLine);
// The line found in the mappings will never be larger than the target
// line, and vice-versa, so if the target line doesn't match the found
// line, we immediately know that it must correspond to the last mapping
// entry for that line.
if (foundLineNumber !== location.line) {
foundEntry = foundLine[foundLine.length - 1];
} else {
foundEntry = binSearch(location, foundLine, compareColumnPositions);
}
if (foundEntry == null) {
throw new Error(
`Expected to find a mapping in the HookMap that covers the target location at line: ${location.line}, column: ${location.column}`,
);
}
const foundNameIndex = getHookNameIndexFromEntry(foundEntry);
if (foundNameIndex == null) {
throw new Error(
`Expected to find a name index in the HookMap that covers the target location at line: ${location.line}, column: ${location.column}`,
);
}
const foundName = names[foundNameIndex];
if (foundName == null) {
throw new Error(
`Expected to find a name in the HookMap that covers the target location at line: ${location.line}, column: ${location.column}`,
);
}
if (foundName === NO_HOOK_NAME) {
return null;
}
return foundName;
}
function binSearch<T>(
location: Position,
items: T[],
compare: (
location: Position,
items: T[],
index: number,
) => {index: number | null, direction: number},
): T | null {
let count = items.length;
let index = 0;
let firstElementIndex = 0;
let step;
while (count > 0) {
index = firstElementIndex;
step = Math.floor(count / 2);
index += step;
const comparison = compare(location, items, index);
if (comparison.direction === 0) {
if (comparison.index == null) {
throw new Error('Expected an index when matching element is found.');
}
firstElementIndex = comparison.index;
break;
}
if (comparison.direction > 0) {
index++;
firstElementIndex = index;
count -= step + 1;
} else {
count = step;
}
}
return firstElementIndex != null ? items[firstElementIndex] : null;
}
/**
* Compares the target line location to the current location
* given by the provided index.
*
* If the target line location matches the current location, returns
* the index of the matching line in the mappings. In order for a line
* to match, the target line must match the line exactly, or be within
* the line range of the current line entries and the adjacent line
* entries.
*
* If the line doesn't match, returns the search direction for the
* next step in the binary search.
*/
function compareLinePositions(
location: Position,
mappings: HookMapMappings,
index: number,
): {index: number | null, direction: number} {
const startIndex = index;
const start = mappings[startIndex];
if (start == null) {
throw new Error(`Unexpected line missing in HookMap at index ${index}.`);
}
const startLine = getLineNumberFromLine(start);
let endLine;
let endIndex = index + 1;
const end = mappings[endIndex];
if (end != null) {
endLine = getLineNumberFromLine(end);
} else {
endIndex = startIndex;
endLine = startLine;
}
// When the line matches exactly, return the matching index
if (startLine === location.line) {
return {index: startIndex, direction: 0};
}
if (endLine === location.line) {
return {index: endIndex, direction: 0};
}
// If we're at the end of the mappings, and the target line is greater
// than the current line, then this final line must cover the
// target location, so we return it.
if (location.line > endLine && end == null) {
return {index: endIndex, direction: 0};
}
// If the location is within the current line and the adjacent one,
// we know that the target location must be covered by the current line.
if (startLine < location.line && location.line < endLine) {
return {index: startIndex, direction: 0};
}
// Otherwise, return the next direction in the search.
return {index: null, direction: location.line - startLine};
}
/**
* Compares the target column location to the current location
* given by the provided index.
*
* If the target column location matches the current location, returns
* the index of the matching entry in the mappings. In order for a column
* to match, the target column must match the column exactly, or be within
* the column range of the current entry and the adjacent entry.
*
* If the column doesn't match, returns the search direction for the
* next step in the binary search.
*/
function compareColumnPositions(
location: Position,
line: HookMapLine,
index: number,
): {index: number | null, direction: number} {
const startIndex = index;
const start = line[index];
if (start == null) {
throw new Error(
`Unexpected mapping missing in HookMap line at index ${index}.`,
);
}
const startColumn = getColumnNumberFromEntry(start);
let endColumn;
let endIndex = index + 1;
const end = line[endIndex];
if (end != null) {
endColumn = getColumnNumberFromEntry(end);
} else {
endIndex = startIndex;
endColumn = startColumn;
}
// When the column matches exactly, return the matching index
if (startColumn === location.column) {
return {index: startIndex, direction: 0};
}
if (endColumn === location.column) {
return {index: endIndex, direction: 0};
}
// If we're at the end of the entries for this line, and the target
// column is greater than the current column, then this final entry
// must cover the target location, so we return it.
if (location.column > endColumn && end == null) {
return {index: endIndex, direction: 0};
}
// If the location is within the current column and the adjacent one,
// we know that the target location must be covered by the current entry.
if (startColumn < location.column && location.column < endColumn) {
return {index: startIndex, direction: 0};
}
// Otherwise, return the next direction in the search.
return {index: null, direction: location.column - startColumn};
}
function getLineNumberFromLine(line: HookMapLine): number {
return getLineNumberFromEntry(line[0]);
}
function getLineNumberFromEntry(entry: HookMapEntry): number {
const lineNumber = entry[0];
if (lineNumber == null) {
throw new Error('Unexpected line number missing in entry in HookMap');
}
return lineNumber;
}
function getColumnNumberFromEntry(entry: HookMapEntry): number {
const columnNumber = entry[1];
if (columnNumber == null) {
throw new Error('Unexpected column number missing in entry in HookMap');
}
return columnNumber;
}
function getHookNameIndexFromEntry(entry: HookMapEntry): number {
const hookNameIndex = entry[2];
if (hookNameIndex == null) {
throw new Error('Unexpected hook name index missing in entry in HookMap');
}
return hookNameIndex;
}
| 30.330909 | 139 | 0.690772 |
Ethical-Hacking-Scripts | /** @flow */
import * as React from 'react';
import {Fragment} from 'react';
import {createPortal} from 'react-dom';
export default function Iframe(): React.Node {
return (
<Fragment>
<h2>Iframe</h2>
<div>
<Frame>
<Greeting />
</Frame>
</div>
</Fragment>
);
}
const iframeStyle = {border: '2px solid #eee', height: 80};
// $FlowFixMe[missing-local-annot]
function Frame(props) {
const [element, setElement] = React.useState(null);
const ref = React.useRef();
React.useLayoutEffect(function () {
const iframe = ref.current;
if (iframe) {
const html = `
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
</body>
</html>
`;
const document = iframe.contentDocument;
document.open();
document.write(html);
document.close();
setElement(document.getElementById('root'));
}
}, []);
return (
<Fragment>
<iframe title="Test Iframe" ref={ref} style={iframeStyle} />
<iframe
title="Secured Iframe"
src="https://example.com"
style={iframeStyle}
/>
{element ? createPortal(props.children, element) : null}
</Fragment>
);
}
function Greeting() {
return (
<p>
Hello from within an <code><iframe></code>!
</p>
);
}
| 17.611111 | 66 | 0.5646 |
null | /**
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {
enableCache,
enableFetchInstrumentation,
} from 'shared/ReactFeatureFlags';
import ReactCurrentCache from './ReactCurrentCache';
function createFetchCache(): Map<string, Array<any>> {
return new Map();
}
const simpleCacheKey = '["GET",[],null,"follow",null,null,null,null]'; // generateCacheKey(new Request('https://blank'));
function generateCacheKey(request: Request): string {
// We pick the fields that goes into the key used to dedupe requests.
// We don't include the `cache` field, because we end up using whatever
// caching resulted from the first request.
// Notably we currently don't consider non-standard (or future) options.
// This might not be safe. TODO: warn for non-standard extensions differing.
// IF YOU CHANGE THIS UPDATE THE simpleCacheKey ABOVE.
return JSON.stringify([
request.method,
Array.from(request.headers.entries()),
request.mode,
request.redirect,
request.credentials,
request.referrer,
request.referrerPolicy,
request.integrity,
]);
}
if (enableCache && enableFetchInstrumentation) {
if (typeof fetch === 'function') {
const originalFetch = fetch;
const cachedFetch = function fetch(
resource: URL | RequestInfo,
options?: RequestOptions,
) {
const dispatcher = ReactCurrentCache.current;
if (!dispatcher) {
// We're outside a cached scope.
return originalFetch(resource, options);
}
if (
options &&
options.signal &&
options.signal !== dispatcher.getCacheSignal()
) {
// If we're passed a signal that is not ours, then we assume that
// someone else controls the lifetime of this object and opts out of
// caching. It's effectively the opt-out mechanism.
// Ideally we should be able to check this on the Request but
// it always gets initialized with its own signal so we don't
// know if it's supposed to override - unless we also override the
// Request constructor.
return originalFetch(resource, options);
}
// Normalize the Request
let url: string;
let cacheKey: string;
if (typeof resource === 'string' && !options) {
// Fast path.
cacheKey = simpleCacheKey;
url = resource;
} else {
// Normalize the request.
// if resource is not a string or a URL (its an instance of Request)
// then do not instantiate a new Request but instead
// reuse the request as to not disturb the body in the event it's a ReadableStream.
const request =
typeof resource === 'string' || resource instanceof URL
? new Request(resource, options)
: resource;
if (
(request.method !== 'GET' && request.method !== 'HEAD') ||
// $FlowFixMe[prop-missing]: keepalive is real
request.keepalive
) {
// We currently don't dedupe requests that might have side-effects. Those
// have to be explicitly cached. We assume that the request doesn't have a
// body if it's GET or HEAD.
// keepalive gets treated the same as if you passed a custom cache signal.
return originalFetch(resource, options);
}
cacheKey = generateCacheKey(request);
url = request.url;
}
const cache = dispatcher.getCacheForType(createFetchCache);
const cacheEntries = cache.get(url);
let match;
if (cacheEntries === undefined) {
// We pass the original arguments here in case normalizing the Request
// doesn't include all the options in this environment.
match = originalFetch(resource, options);
cache.set(url, [cacheKey, match]);
} else {
// We use an array as the inner data structure since it's lighter and
// we typically only expect to see one or two entries here.
for (let i = 0, l = cacheEntries.length; i < l; i += 2) {
const key = cacheEntries[i];
const value = cacheEntries[i + 1];
if (key === cacheKey) {
match = value;
// I would've preferred a labelled break but lint says no.
return match.then(response => response.clone());
}
}
match = originalFetch(resource, options);
cacheEntries.push(cacheKey, match);
}
// We clone the response so that each time you call this you get a new read
// of the body so that it can be read multiple times.
return match.then(response => response.clone());
};
// We don't expect to see any extra properties on fetch but if there are any,
// copy them over. Useful for extended fetch environments or mocks.
Object.assign(cachedFetch, originalFetch);
try {
// eslint-disable-next-line no-native-reassign
fetch = cachedFetch;
} catch (error1) {
try {
// In case assigning it globally fails, try globalThis instead just in case it exists.
globalThis.fetch = cachedFetch;
} catch (error2) {
// Log even in production just to make sure this is seen if only prod is frozen.
// eslint-disable-next-line react-internal/no-production-logging
console.warn(
'React was unable to patch the fetch() function in this environment. ' +
'Suspensey APIs might not work correctly as a result.',
);
}
}
}
}
| 37.678082 | 121 | 0.633369 |
null | 'use strict';
const fs = require('fs');
const path = require('path');
const ts = require('typescript');
const tsOptions = {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.React,
};
function formatErrorMessage(error) {
if (error.file) {
const message = ts.flattenDiagnosticMessageText(error.messageText, '\n');
return (
error.file.fileName +
'(' +
error.file.getLineAndCharacterOfPosition(error.start).line +
'): ' +
message
);
} else {
return ts.flattenDiagnosticMessageText(error.messageText, '\n');
}
}
function compile(content, contentFilename) {
let output = null;
const compilerHost = {
fileExists(filename) {
return ts.sys.fileExists(filename);
},
getCanonicalFileName(filename) {
return filename;
},
getCurrentDirectory() {
return '';
},
getDefaultLibFileName: () => 'lib.d.ts',
getNewLine: () => ts.sys.newLine,
getSourceFile(filename, languageVersion) {
let source;
const libRegex = /lib\.(.+\.)?d\.ts$/;
const jestRegex = /jest\.d\.ts/;
const reactRegex =
/(?:React|ReactDOM|ReactDOMClient|ReactInternalAct|PropTypes)(?:\.d)?\.ts$/;
// `path.normalize` is used to turn forward slashes in
// the file path into backslashes on Windows.
filename = path.normalize(filename);
if (filename.match(libRegex)) {
source = fs
.readFileSync(require.resolve('typescript/lib/' + filename))
.toString();
} else if (filename.match(jestRegex)) {
source = fs.readFileSync(path.join(__dirname, 'jest.d.ts')).toString();
} else if (filename === contentFilename) {
source = content;
} else if (reactRegex.test(filename)) {
// TypeScript will look for the .d.ts files in each ancestor directory,
// so there may not be a file at the referenced path as it climbs the
// hierarchy.
try {
source = fs.readFileSync(filename).toString();
} catch (e) {
if (e.code === 'ENOENT') {
return undefined;
}
throw e;
}
} else {
throw new Error('Unexpected filename ' + filename);
}
return ts.createSourceFile(filename, source, 'ES5', '0');
},
readFile(filename) {
return ts.sys.readFile(filename);
},
useCaseSensitiveFileNames() {
return ts.sys.useCaseSensitiveFileNames;
},
writeFile(name, text, writeByteOrderMark) {
if (output === null) {
output = text;
} else {
throw new Error('Expected only one dependency.');
}
},
};
const program = ts.createProgram(
['lib.d.ts', 'jest.d.ts', contentFilename],
tsOptions,
compilerHost
);
const emitResult = program.emit();
const errors = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
if (errors.length) {
throw new Error(errors.map(formatErrorMessage).join('\n'));
}
return output;
}
module.exports = {
compile: compile,
};
| 27.175926 | 84 | 0.605194 |
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';
let React = require('react');
const ReactTestUtils = require('react-dom/test-utils');
class TextWithStringRef extends React.Component {
render() {
jest.resetModules();
React = require('react');
return <span ref="foo">Hello world!</span>;
}
}
describe('when different React version is used with string ref', () => {
it('throws the "Refs must have owner" warning', () => {
expect(() => {
ReactTestUtils.renderIntoDocument(<TextWithStringRef />);
}).toThrow(
'Element ref was specified as a string (foo) but no owner was set. This could happen for one of' +
' the following reasons:\n' +
'1. You may be adding a ref to a function component\n' +
"2. You may be adding a ref to a component that was not created inside a component's render method\n" +
'3. You have multiple copies of React loaded\n' +
'See https://reactjs.org/link/refs-must-have-owner for more information.',
);
});
});
| 31.459459 | 111 | 0.656667 |
Effective-Python-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 {copy} from 'clipboard-js';
import EventEmitter from '../events';
import {inspect} from 'util';
import {
PROFILING_FLAG_BASIC_SUPPORT,
PROFILING_FLAG_TIMELINE_SUPPORT,
TREE_OPERATION_ADD,
TREE_OPERATION_REMOVE,
TREE_OPERATION_REMOVE_ROOT,
TREE_OPERATION_REORDER_CHILDREN,
TREE_OPERATION_SET_SUBTREE_MODE,
TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS,
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
} from '../constants';
import {ElementTypeRoot} from '../frontend/types';
import {
getSavedComponentFilters,
setSavedComponentFilters,
shallowDiffers,
utfDecodeStringWithRanges,
parseElementDisplayNameFromBackend,
} from '../utils';
import {localStorageGetItem, localStorageSetItem} from '../storage';
import {__DEBUG__} from '../constants';
import {printStore} from './utils';
import ProfilerStore from './ProfilerStore';
import {
BRIDGE_PROTOCOL,
currentBridgeProtocol,
} from 'react-devtools-shared/src/bridge';
import {StrictMode} from 'react-devtools-shared/src/frontend/types';
import type {
Element,
ComponentFilter,
ElementType,
} from 'react-devtools-shared/src/frontend/types';
import type {
FrontendBridge,
BridgeProtocol,
} from 'react-devtools-shared/src/bridge';
import UnsupportedBridgeOperationError from 'react-devtools-shared/src/UnsupportedBridgeOperationError';
const debug = (methodName: string, ...args: Array<string>) => {
if (__DEBUG__) {
console.log(
`%cStore %c${methodName}`,
'color: green; font-weight: bold;',
'font-weight: bold;',
...args,
);
}
};
const LOCAL_STORAGE_COLLAPSE_ROOTS_BY_DEFAULT_KEY =
'React::DevTools::collapseNodesByDefault';
const LOCAL_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY =
'React::DevTools::recordChangeDescriptions';
type ErrorAndWarningTuples = Array<{id: number, index: number}>;
type Config = {
checkBridgeProtocolCompatibility?: boolean,
isProfiling?: boolean,
supportsNativeInspection?: boolean,
supportsProfiling?: boolean,
supportsReloadAndProfile?: boolean,
supportsTimeline?: boolean,
supportsTraceUpdates?: boolean,
};
export type Capabilities = {
supportsBasicProfiling: boolean,
hasOwnerMetadata: boolean,
supportsStrictMode: boolean,
supportsTimeline: boolean,
};
/**
* The store is the single source of truth for updates from the backend.
* ContextProviders can subscribe to the Store for specific things they want to provide.
*/
export default class Store extends EventEmitter<{
backendVersion: [],
collapseNodesByDefault: [],
componentFilters: [],
error: [Error],
mutated: [[Array<number>, Map<number, number>]],
recordChangeDescriptions: [],
roots: [],
rootSupportsBasicProfiling: [],
rootSupportsTimelineProfiling: [],
supportsNativeStyleEditor: [],
supportsReloadAndProfile: [],
unsupportedBridgeProtocolDetected: [],
unsupportedRendererVersionDetected: [],
}> {
// If the backend version is new enough to report its (NPM) version, this is it.
// This version may be displayed by the frontend for debugging purposes.
_backendVersion: string | null = null;
_bridge: FrontendBridge;
// Computed whenever _errorsAndWarnings Map changes.
_cachedErrorCount: number = 0;
_cachedWarningCount: number = 0;
_cachedErrorAndWarningTuples: ErrorAndWarningTuples | null = null;
// Should new nodes be collapsed by default when added to the tree?
_collapseNodesByDefault: boolean = true;
_componentFilters: Array<ComponentFilter>;
// Map of ID to number of recorded error and warning message IDs.
_errorsAndWarnings: Map<number, {errorCount: number, warningCount: number}> =
new Map();
// At least one of the injected renderers contains (DEV only) owner metadata.
_hasOwnerMetadata: boolean = false;
// Map of ID to (mutable) Element.
// Elements are mutated to avoid excessive cloning during tree updates.
// The InspectedElement Suspense cache also relies on this mutability for its WeakMap usage.
_idToElement: Map<number, Element> = new Map();
// Should the React Native style editor panel be shown?
_isNativeStyleEditorSupported: boolean = false;
// Can the backend use the Storage API (e.g. localStorage)?
// If not, features like reload-and-profile will not work correctly and must be disabled.
_isBackendStorageAPISupported: boolean = false;
// Can DevTools use sync XHR requests?
// If not, features like reload-and-profile will not work correctly and must be disabled.
// This current limitation applies only to web extension builds
// and will need to be reconsidered in the future if we add support for reload to React Native.
_isSynchronousXHRSupported: boolean = false;
_nativeStyleEditorValidAttributes: $ReadOnlyArray<string> | null = null;
// Older backends don't support an explicit bridge protocol,
// so we should timeout eventually and show a downgrade message.
_onBridgeProtocolTimeoutID: TimeoutID | null = null;
// Map of element (id) to the set of elements (ids) it owns.
// This map enables getOwnersListForElement() to avoid traversing the entire tree.
_ownersMap: Map<number, Set<number>> = new Map();
_profilerStore: ProfilerStore;
_recordChangeDescriptions: boolean = false;
// Incremented each time the store is mutated.
// This enables a passive effect to detect a mutation between render and commit phase.
_revision: number = 0;
// This Array must be treated as immutable!
// Passive effects will check it for changes between render and mount.
_roots: $ReadOnlyArray<number> = [];
_rootIDToCapabilities: Map<number, Capabilities> = new Map();
// Renderer ID is needed to support inspection fiber props, state, and hooks.
_rootIDToRendererID: Map<number, number> = new Map();
// These options may be initially set by a configuration option when constructing the Store.
_supportsNativeInspection: boolean = true;
_supportsProfiling: boolean = false;
_supportsReloadAndProfile: boolean = false;
_supportsTimeline: boolean = false;
_supportsTraceUpdates: boolean = false;
// These options default to false but may be updated as roots are added and removed.
_rootSupportsBasicProfiling: boolean = false;
_rootSupportsTimelineProfiling: boolean = false;
_bridgeProtocol: BridgeProtocol | null = null;
_unsupportedBridgeProtocolDetected: boolean = false;
_unsupportedRendererVersionDetected: boolean = false;
// Total number of visible elements (within all roots).
// Used for windowing purposes.
_weightAcrossRoots: number = 0;
constructor(bridge: FrontendBridge, config?: Config) {
super();
if (__DEBUG__) {
debug('constructor', 'subscribing to Bridge');
}
this._collapseNodesByDefault =
localStorageGetItem(LOCAL_STORAGE_COLLAPSE_ROOTS_BY_DEFAULT_KEY) ===
'true';
this._recordChangeDescriptions =
localStorageGetItem(LOCAL_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY) ===
'true';
this._componentFilters = getSavedComponentFilters();
let isProfiling = false;
if (config != null) {
isProfiling = config.isProfiling === true;
const {
supportsNativeInspection,
supportsProfiling,
supportsReloadAndProfile,
supportsTimeline,
supportsTraceUpdates,
} = config;
this._supportsNativeInspection = supportsNativeInspection !== false;
if (supportsProfiling) {
this._supportsProfiling = true;
}
if (supportsReloadAndProfile) {
this._supportsReloadAndProfile = true;
}
if (supportsTimeline) {
this._supportsTimeline = true;
}
if (supportsTraceUpdates) {
this._supportsTraceUpdates = true;
}
}
this._bridge = bridge;
bridge.addListener('operations', this.onBridgeOperations);
bridge.addListener(
'overrideComponentFilters',
this.onBridgeOverrideComponentFilters,
);
bridge.addListener('shutdown', this.onBridgeShutdown);
bridge.addListener(
'isBackendStorageAPISupported',
this.onBackendStorageAPISupported,
);
bridge.addListener(
'isNativeStyleEditorSupported',
this.onBridgeNativeStyleEditorSupported,
);
bridge.addListener(
'isSynchronousXHRSupported',
this.onBridgeSynchronousXHRSupported,
);
bridge.addListener(
'unsupportedRendererVersion',
this.onBridgeUnsupportedRendererVersion,
);
this._profilerStore = new ProfilerStore(bridge, this, isProfiling);
// Verify that the frontend version is compatible with the connected backend.
// See github.com/facebook/react/issues/21326
if (config != null && config.checkBridgeProtocolCompatibility) {
// Older backends don't support an explicit bridge protocol,
// so we should timeout eventually and show a downgrade message.
this._onBridgeProtocolTimeoutID = setTimeout(
this.onBridgeProtocolTimeout,
10000,
);
bridge.addListener('bridgeProtocol', this.onBridgeProtocol);
bridge.send('getBridgeProtocol');
}
bridge.addListener('backendVersion', this.onBridgeBackendVersion);
bridge.send('getBackendVersion');
bridge.addListener('saveToClipboard', this.onSaveToClipboard);
}
// This is only used in tests to avoid memory leaks.
assertExpectedRootMapSizes() {
if (this.roots.length === 0) {
// The only safe time to assert these maps are empty is when the store is empty.
this.assertMapSizeMatchesRootCount(this._idToElement, '_idToElement');
this.assertMapSizeMatchesRootCount(this._ownersMap, '_ownersMap');
}
// These maps should always be the same size as the number of roots
this.assertMapSizeMatchesRootCount(
this._rootIDToCapabilities,
'_rootIDToCapabilities',
);
this.assertMapSizeMatchesRootCount(
this._rootIDToRendererID,
'_rootIDToRendererID',
);
}
// This is only used in tests to avoid memory leaks.
assertMapSizeMatchesRootCount(map: Map<any, any>, mapName: string) {
const expectedSize = this.roots.length;
if (map.size !== expectedSize) {
this._throwAndEmitError(
Error(
`Expected ${mapName} to contain ${expectedSize} items, but it contains ${
map.size
} items\n\n${inspect(map, {
depth: 20,
})}`,
),
);
}
}
get backendVersion(): string | null {
return this._backendVersion;
}
get collapseNodesByDefault(): boolean {
return this._collapseNodesByDefault;
}
set collapseNodesByDefault(value: boolean): void {
this._collapseNodesByDefault = value;
localStorageSetItem(
LOCAL_STORAGE_COLLAPSE_ROOTS_BY_DEFAULT_KEY,
value ? 'true' : 'false',
);
this.emit('collapseNodesByDefault');
}
get componentFilters(): Array<ComponentFilter> {
return this._componentFilters;
}
set componentFilters(value: Array<ComponentFilter>): void {
if (this._profilerStore.isProfiling) {
// Re-mounting a tree while profiling is in progress might break a lot of assumptions.
// If necessary, we could support this- but it doesn't seem like a necessary use case.
this._throwAndEmitError(
Error('Cannot modify filter preferences while profiling'),
);
}
// Filter updates are expensive to apply (since they impact the entire tree).
// Let's determine if they've changed and avoid doing this work if they haven't.
const prevEnabledComponentFilters = this._componentFilters.filter(
filter => filter.isEnabled,
);
const nextEnabledComponentFilters = value.filter(
filter => filter.isEnabled,
);
let haveEnabledFiltersChanged =
prevEnabledComponentFilters.length !== nextEnabledComponentFilters.length;
if (!haveEnabledFiltersChanged) {
for (let i = 0; i < nextEnabledComponentFilters.length; i++) {
const prevFilter = prevEnabledComponentFilters[i];
const nextFilter = nextEnabledComponentFilters[i];
if (shallowDiffers(prevFilter, nextFilter)) {
haveEnabledFiltersChanged = true;
break;
}
}
}
this._componentFilters = value;
// Update persisted filter preferences stored in localStorage.
setSavedComponentFilters(value);
// Notify the renderer that filter preferences have changed.
// This is an expensive operation; it unmounts and remounts the entire tree,
// so only do it if the set of enabled component filters has changed.
if (haveEnabledFiltersChanged) {
this._bridge.send('updateComponentFilters', value);
}
this.emit('componentFilters');
}
get bridgeProtocol(): BridgeProtocol | null {
return this._bridgeProtocol;
}
get errorCount(): number {
return this._cachedErrorCount;
}
get hasOwnerMetadata(): boolean {
return this._hasOwnerMetadata;
}
get nativeStyleEditorValidAttributes(): $ReadOnlyArray<string> | null {
return this._nativeStyleEditorValidAttributes;
}
get numElements(): number {
return this._weightAcrossRoots;
}
get profilerStore(): ProfilerStore {
return this._profilerStore;
}
get recordChangeDescriptions(): boolean {
return this._recordChangeDescriptions;
}
set recordChangeDescriptions(value: boolean): void {
this._recordChangeDescriptions = value;
localStorageSetItem(
LOCAL_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,
value ? 'true' : 'false',
);
this.emit('recordChangeDescriptions');
}
get revision(): number {
return this._revision;
}
get rootIDToRendererID(): Map<number, number> {
return this._rootIDToRendererID;
}
get roots(): $ReadOnlyArray<number> {
return this._roots;
}
// At least one of the currently mounted roots support the Legacy profiler.
get rootSupportsBasicProfiling(): boolean {
return this._rootSupportsBasicProfiling;
}
// At least one of the currently mounted roots support the Timeline profiler.
get rootSupportsTimelineProfiling(): boolean {
return this._rootSupportsTimelineProfiling;
}
get supportsNativeInspection(): boolean {
return this._supportsNativeInspection;
}
get supportsNativeStyleEditor(): boolean {
return this._isNativeStyleEditorSupported;
}
// This build of DevTools supports the legacy profiler.
// This is a static flag, controlled by the Store config.
get supportsProfiling(): boolean {
return this._supportsProfiling;
}
get supportsReloadAndProfile(): boolean {
// Does the DevTools shell support reloading and eagerly injecting the renderer interface?
// And if so, can the backend use the localStorage API and sync XHR?
// All of these are currently required for the reload-and-profile feature to work.
return (
this._supportsReloadAndProfile &&
this._isBackendStorageAPISupported &&
this._isSynchronousXHRSupported
);
}
// This build of DevTools supports the Timeline profiler.
// This is a static flag, controlled by the Store config.
get supportsTimeline(): boolean {
return this._supportsTimeline;
}
get supportsTraceUpdates(): boolean {
return this._supportsTraceUpdates;
}
get unsupportedBridgeProtocolDetected(): boolean {
return this._unsupportedBridgeProtocolDetected;
}
get unsupportedRendererVersionDetected(): boolean {
return this._unsupportedRendererVersionDetected;
}
get warningCount(): number {
return this._cachedWarningCount;
}
containsElement(id: number): boolean {
return this._idToElement.has(id);
}
getElementAtIndex(index: number): Element | null {
if (index < 0 || index >= this.numElements) {
console.warn(
`Invalid index ${index} specified; store contains ${this.numElements} items.`,
);
return null;
}
// Find which root this element is in...
let root;
let rootWeight = 0;
for (let i = 0; i < this._roots.length; i++) {
const rootID = this._roots[i];
root = this._idToElement.get(rootID);
if (root === undefined) {
this._throwAndEmitError(
Error(
`Couldn't find root with id "${rootID}": no matching node was found in the Store.`,
),
);
return null;
}
if (root.children.length === 0) {
continue;
}
if (rootWeight + root.weight > index) {
break;
} else {
rootWeight += root.weight;
}
}
if (root === undefined) {
return null;
}
// Find the element in the tree using the weight of each node...
// Skip over the root itself, because roots aren't visible in the Elements tree.
let currentElement: Element = root;
let currentWeight = rootWeight - 1;
while (index !== currentWeight) {
const numChildren = currentElement.children.length;
for (let i = 0; i < numChildren; i++) {
const childID = currentElement.children[i];
const child = this._idToElement.get(childID);
if (child === undefined) {
this._throwAndEmitError(
Error(
`Couldn't child element with id "${childID}": no matching node was found in the Store.`,
),
);
return null;
}
const childWeight = child.isCollapsed ? 1 : child.weight;
if (index <= currentWeight + childWeight) {
currentWeight++;
currentElement = child;
break;
} else {
currentWeight += childWeight;
}
}
}
return currentElement || null;
}
getElementIDAtIndex(index: number): number | null {
const element = this.getElementAtIndex(index);
return element === null ? null : element.id;
}
getElementByID(id: number): Element | null {
const element = this._idToElement.get(id);
if (element === undefined) {
console.warn(`No element found with id "${id}"`);
return null;
}
return element;
}
// Returns a tuple of [id, index]
getElementsWithErrorsAndWarnings(): Array<{id: number, index: number}> {
if (this._cachedErrorAndWarningTuples !== null) {
return this._cachedErrorAndWarningTuples;
}
const errorAndWarningTuples: ErrorAndWarningTuples = [];
this._errorsAndWarnings.forEach((_, id) => {
const index = this.getIndexOfElementID(id);
if (index !== null) {
let low = 0;
let high = errorAndWarningTuples.length;
while (low < high) {
const mid = (low + high) >> 1;
if (errorAndWarningTuples[mid].index > index) {
high = mid;
} else {
low = mid + 1;
}
}
errorAndWarningTuples.splice(low, 0, {id, index});
}
});
// Cache for later (at least until the tree changes again).
this._cachedErrorAndWarningTuples = errorAndWarningTuples;
return errorAndWarningTuples;
}
getErrorAndWarningCountForElementID(id: number): {
errorCount: number,
warningCount: number,
} {
return this._errorsAndWarnings.get(id) || {errorCount: 0, warningCount: 0};
}
getIndexOfElementID(id: number): number | null {
const element = this.getElementByID(id);
if (element === null || element.parentID === 0) {
return null;
}
// Walk up the tree to the root.
// Increment the index by one for each node we encounter,
// and by the weight of all nodes to the left of the current one.
// This should be a relatively fast way of determining the index of a node within the tree.
let previousID = id;
let currentID = element.parentID;
let index = 0;
while (true) {
const current = this._idToElement.get(currentID);
if (current === undefined) {
return null;
}
const {children} = current;
for (let i = 0; i < children.length; i++) {
const childID = children[i];
if (childID === previousID) {
break;
}
const child = this._idToElement.get(childID);
if (child === undefined) {
return null;
}
index += child.isCollapsed ? 1 : child.weight;
}
if (current.parentID === 0) {
// We found the root; stop crawling.
break;
}
index++;
previousID = current.id;
currentID = current.parentID;
}
// At this point, the current ID is a root (from the previous loop).
// We also need to offset the index by previous root weights.
for (let i = 0; i < this._roots.length; i++) {
const rootID = this._roots[i];
if (rootID === currentID) {
break;
}
const root = this._idToElement.get(rootID);
if (root === undefined) {
return null;
}
index += root.weight;
}
return index;
}
getOwnersListForElement(ownerID: number): Array<Element> {
const list: Array<Element> = [];
const element = this._idToElement.get(ownerID);
if (element !== undefined) {
list.push({
...element,
depth: 0,
});
const unsortedIDs = this._ownersMap.get(ownerID);
if (unsortedIDs !== undefined) {
const depthMap: Map<number, number> = new Map([[ownerID, 0]]);
// Items in a set are ordered based on insertion.
// This does not correlate with their order in the tree.
// So first we need to order them.
// I wish we could avoid this sorting operation; we could sort at insertion time,
// but then we'd have to pay sorting costs even if the owners list was never used.
// Seems better to defer the cost, since the set of ids is probably pretty small.
const sortedIDs = Array.from(unsortedIDs).sort(
(idA, idB) =>
(this.getIndexOfElementID(idA) || 0) -
(this.getIndexOfElementID(idB) || 0),
);
// Next we need to determine the appropriate depth for each element in the list.
// The depth in the list may not correspond to the depth in the tree,
// because the list has been filtered to remove intermediate components.
// Perhaps the easiest way to do this is to walk up the tree until we reach either:
// (1) another node that's already in the tree, or (2) the root (owner)
// at which point, our depth is just the depth of that node plus one.
sortedIDs.forEach(id => {
const innerElement = this._idToElement.get(id);
if (innerElement !== undefined) {
let parentID = innerElement.parentID;
let depth = 0;
while (parentID > 0) {
if (parentID === ownerID || unsortedIDs.has(parentID)) {
// $FlowFixMe[unsafe-addition] addition with possible null/undefined value
depth = depthMap.get(parentID) + 1;
depthMap.set(id, depth);
break;
}
const parent = this._idToElement.get(parentID);
if (parent === undefined) {
break;
}
parentID = parent.parentID;
}
if (depth === 0) {
this._throwAndEmitError(Error('Invalid owners list'));
}
list.push({...innerElement, depth});
}
});
}
}
return list;
}
getRendererIDForElement(id: number): number | null {
let current = this._idToElement.get(id);
while (current !== undefined) {
if (current.parentID === 0) {
const rendererID = this._rootIDToRendererID.get(current.id);
return rendererID == null ? null : rendererID;
} else {
current = this._idToElement.get(current.parentID);
}
}
return null;
}
getRootIDForElement(id: number): number | null {
let current = this._idToElement.get(id);
while (current !== undefined) {
if (current.parentID === 0) {
return current.id;
} else {
current = this._idToElement.get(current.parentID);
}
}
return null;
}
isInsideCollapsedSubTree(id: number): boolean {
let current = this._idToElement.get(id);
while (current != null) {
if (current.parentID === 0) {
return false;
} else {
current = this._idToElement.get(current.parentID);
if (current != null && current.isCollapsed) {
return true;
}
}
}
return false;
}
// TODO Maybe split this into two methods: expand() and collapse()
toggleIsCollapsed(id: number, isCollapsed: boolean): void {
let didMutate = false;
const element = this.getElementByID(id);
if (element !== null) {
if (isCollapsed) {
if (element.type === ElementTypeRoot) {
this._throwAndEmitError(Error('Root nodes cannot be collapsed'));
}
if (!element.isCollapsed) {
didMutate = true;
element.isCollapsed = true;
const weightDelta = 1 - element.weight;
let parentElement = this._idToElement.get(element.parentID);
while (parentElement !== undefined) {
// We don't need to break on a collapsed parent in the same way as the expand case below.
// That's because collapsing a node doesn't "bubble" and affect its parents.
parentElement.weight += weightDelta;
parentElement = this._idToElement.get(parentElement.parentID);
}
}
} else {
let currentElement: ?Element = element;
while (currentElement != null) {
const oldWeight = currentElement.isCollapsed
? 1
: currentElement.weight;
if (currentElement.isCollapsed) {
didMutate = true;
currentElement.isCollapsed = false;
const newWeight = currentElement.isCollapsed
? 1
: currentElement.weight;
const weightDelta = newWeight - oldWeight;
let parentElement = this._idToElement.get(currentElement.parentID);
while (parentElement !== undefined) {
parentElement.weight += weightDelta;
if (parentElement.isCollapsed) {
// It's important to break on a collapsed parent when expanding nodes.
// That's because expanding a node "bubbles" up and expands all parents as well.
// Breaking in this case prevents us from over-incrementing the expanded weights.
break;
}
parentElement = this._idToElement.get(parentElement.parentID);
}
}
currentElement =
currentElement.parentID !== 0
? this.getElementByID(currentElement.parentID)
: null;
}
}
// Only re-calculate weights and emit an "update" event if the store was mutated.
if (didMutate) {
let weightAcrossRoots = 0;
this._roots.forEach(rootID => {
const {weight} = ((this.getElementByID(rootID): any): Element);
weightAcrossRoots += weight;
});
this._weightAcrossRoots = weightAcrossRoots;
// The Tree context's search reducer expects an explicit list of ids for nodes that were added or removed.
// In this case, we can pass it empty arrays since nodes in a collapsed tree are still there (just hidden).
// Updating the selected search index later may require auto-expanding a collapsed subtree though.
this.emit('mutated', [[], new Map()]);
}
}
}
_adjustParentTreeWeight: (
parentElement: ?Element,
weightDelta: number,
) => void = (parentElement, weightDelta) => {
let isInsideCollapsedSubTree = false;
while (parentElement != null) {
parentElement.weight += weightDelta;
// Additions and deletions within a collapsed subtree should not bubble beyond the collapsed parent.
// Their weight will bubble up when the parent is expanded.
if (parentElement.isCollapsed) {
isInsideCollapsedSubTree = true;
break;
}
parentElement = this._idToElement.get(parentElement.parentID);
}
// Additions and deletions within a collapsed subtree should not affect the overall number of elements.
if (!isInsideCollapsedSubTree) {
this._weightAcrossRoots += weightDelta;
}
};
_recursivelyUpdateSubtree(
id: number,
callback: (element: Element) => void,
): void {
const element = this._idToElement.get(id);
if (element) {
callback(element);
element.children.forEach(child =>
this._recursivelyUpdateSubtree(child, callback),
);
}
}
onBridgeNativeStyleEditorSupported: ({
isSupported: boolean,
validAttributes: ?$ReadOnlyArray<string>,
}) => void = ({isSupported, validAttributes}) => {
this._isNativeStyleEditorSupported = isSupported;
this._nativeStyleEditorValidAttributes = validAttributes || null;
this.emit('supportsNativeStyleEditor');
};
onBridgeOperations: (operations: Array<number>) => void = operations => {
if (__DEBUG__) {
console.groupCollapsed('onBridgeOperations');
debug('onBridgeOperations', operations.join(','));
}
let haveRootsChanged = false;
let haveErrorsOrWarningsChanged = false;
// The first two values are always rendererID and rootID
const rendererID = operations[0];
const addedElementIDs: Array<number> = [];
// This is a mapping of removed ID -> parent ID:
const removedElementIDs: Map<number, number> = new Map();
// We'll use the parent ID to adjust selection if it gets deleted.
let i = 2;
// Reassemble the string table.
const stringTable: Array<string | null> = [
null, // ID = 0 corresponds to the null string.
];
const stringTableSize = operations[i];
i++;
const stringTableEnd = i + stringTableSize;
while (i < stringTableEnd) {
const nextLength = operations[i];
i++;
const nextString = utfDecodeStringWithRanges(
operations,
i,
i + nextLength - 1,
);
stringTable.push(nextString);
i += nextLength;
}
while (i < operations.length) {
const operation = operations[i];
switch (operation) {
case TREE_OPERATION_ADD: {
const id = operations[i + 1];
const type = ((operations[i + 2]: any): ElementType);
i += 3;
if (this._idToElement.has(id)) {
this._throwAndEmitError(
Error(
`Cannot add node "${id}" because a node with that id is already in the Store.`,
),
);
}
if (type === ElementTypeRoot) {
if (__DEBUG__) {
debug('Add', `new root node ${id}`);
}
const isStrictModeCompliant = operations[i] > 0;
i++;
const supportsBasicProfiling =
(operations[i] & PROFILING_FLAG_BASIC_SUPPORT) !== 0;
const supportsTimeline =
(operations[i] & PROFILING_FLAG_TIMELINE_SUPPORT) !== 0;
i++;
let supportsStrictMode = false;
let hasOwnerMetadata = false;
// If we don't know the bridge protocol, guess that we're dealing with the latest.
// If we do know it, we can take it into consideration when parsing operations.
if (
this._bridgeProtocol === null ||
this._bridgeProtocol.version >= 2
) {
supportsStrictMode = operations[i] > 0;
i++;
hasOwnerMetadata = operations[i] > 0;
i++;
}
this._roots = this._roots.concat(id);
this._rootIDToRendererID.set(id, rendererID);
this._rootIDToCapabilities.set(id, {
supportsBasicProfiling,
hasOwnerMetadata,
supportsStrictMode,
supportsTimeline,
});
// Not all roots support StrictMode;
// don't flag a root as non-compliant unless it also supports StrictMode.
const isStrictModeNonCompliant =
!isStrictModeCompliant && supportsStrictMode;
this._idToElement.set(id, {
children: [],
depth: -1,
displayName: null,
hocDisplayNames: null,
id,
isCollapsed: false, // Never collapse roots; it would hide the entire tree.
isStrictModeNonCompliant,
key: null,
ownerID: 0,
parentID: 0,
type,
weight: 0,
compiledWithForget: false,
});
haveRootsChanged = true;
} else {
const parentID = operations[i];
i++;
const ownerID = operations[i];
i++;
const displayNameStringID = operations[i];
const displayName = stringTable[displayNameStringID];
i++;
const keyStringID = operations[i];
const key = stringTable[keyStringID];
i++;
if (__DEBUG__) {
debug(
'Add',
`node ${id} (${displayName || 'null'}) as child of ${parentID}`,
);
}
const parentElement = this._idToElement.get(parentID);
if (parentElement === undefined) {
this._throwAndEmitError(
Error(
`Cannot add child "${id}" to parent "${parentID}" because parent node was not found in the Store.`,
),
);
break;
}
parentElement.children.push(id);
const {
formattedDisplayName: displayNameWithoutHOCs,
hocDisplayNames,
compiledWithForget,
} = parseElementDisplayNameFromBackend(displayName, type);
const element: Element = {
children: [],
depth: parentElement.depth + 1,
displayName: displayNameWithoutHOCs,
hocDisplayNames,
id,
isCollapsed: this._collapseNodesByDefault,
isStrictModeNonCompliant: parentElement.isStrictModeNonCompliant,
key,
ownerID,
parentID,
type,
weight: 1,
compiledWithForget,
};
this._idToElement.set(id, element);
addedElementIDs.push(id);
this._adjustParentTreeWeight(parentElement, 1);
if (ownerID > 0) {
let set = this._ownersMap.get(ownerID);
if (set === undefined) {
set = new Set();
this._ownersMap.set(ownerID, set);
}
set.add(id);
}
}
break;
}
case TREE_OPERATION_REMOVE: {
const removeLength = operations[i + 1];
i += 2;
for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) {
const id = operations[i];
const element = this._idToElement.get(id);
if (element === undefined) {
this._throwAndEmitError(
Error(
`Cannot remove node "${id}" because no matching node was found in the Store.`,
),
);
break;
}
i += 1;
const {children, ownerID, parentID, weight} = element;
if (children.length > 0) {
this._throwAndEmitError(
Error(`Node "${id}" was removed before its children.`),
);
}
this._idToElement.delete(id);
let parentElement: ?Element = null;
if (parentID === 0) {
if (__DEBUG__) {
debug('Remove', `node ${id} root`);
}
this._roots = this._roots.filter(rootID => rootID !== id);
this._rootIDToRendererID.delete(id);
this._rootIDToCapabilities.delete(id);
haveRootsChanged = true;
} else {
if (__DEBUG__) {
debug('Remove', `node ${id} from parent ${parentID}`);
}
parentElement = this._idToElement.get(parentID);
if (parentElement === undefined) {
this._throwAndEmitError(
Error(
`Cannot remove node "${id}" from parent "${parentID}" because no matching node was found in the Store.`,
),
);
break;
}
const index = parentElement.children.indexOf(id);
parentElement.children.splice(index, 1);
}
this._adjustParentTreeWeight(parentElement, -weight);
removedElementIDs.set(id, parentID);
this._ownersMap.delete(id);
if (ownerID > 0) {
const set = this._ownersMap.get(ownerID);
if (set !== undefined) {
set.delete(id);
}
}
if (this._errorsAndWarnings.has(id)) {
this._errorsAndWarnings.delete(id);
haveErrorsOrWarningsChanged = true;
}
}
break;
}
case TREE_OPERATION_REMOVE_ROOT: {
i += 1;
const id = operations[1];
if (__DEBUG__) {
debug(`Remove root ${id}`);
}
const recursivelyDeleteElements = (elementID: number) => {
const element = this._idToElement.get(elementID);
this._idToElement.delete(elementID);
if (element) {
// Mostly for Flow's sake
for (let index = 0; index < element.children.length; index++) {
recursivelyDeleteElements(element.children[index]);
}
}
};
const root = this._idToElement.get(id);
if (root === undefined) {
this._throwAndEmitError(
Error(
`Cannot remove root "${id}": no matching node was found in the Store.`,
),
);
break;
}
recursivelyDeleteElements(id);
this._rootIDToCapabilities.delete(id);
this._rootIDToRendererID.delete(id);
this._roots = this._roots.filter(rootID => rootID !== id);
this._weightAcrossRoots -= root.weight;
break;
}
case TREE_OPERATION_REORDER_CHILDREN: {
const id = operations[i + 1];
const numChildren = operations[i + 2];
i += 3;
const element = this._idToElement.get(id);
if (element === undefined) {
this._throwAndEmitError(
Error(
`Cannot reorder children for node "${id}" because no matching node was found in the Store.`,
),
);
break;
}
const children = element.children;
if (children.length !== numChildren) {
this._throwAndEmitError(
Error(
`Children cannot be added or removed during a reorder operation.`,
),
);
}
for (let j = 0; j < numChildren; j++) {
const childID = operations[i + j];
children[j] = childID;
if (__DEV__) {
// This check is more expensive so it's gated by __DEV__.
const childElement = this._idToElement.get(childID);
if (childElement == null || childElement.parentID !== id) {
console.error(
`Children cannot be added or removed during a reorder operation.`,
);
}
}
}
i += numChildren;
if (__DEBUG__) {
debug('Re-order', `Node ${id} children ${children.join(',')}`);
}
break;
}
case TREE_OPERATION_SET_SUBTREE_MODE: {
const id = operations[i + 1];
const mode = operations[i + 2];
i += 3;
// If elements have already been mounted in this subtree, update them.
// (In practice, this likely only applies to the root element.)
if (mode === StrictMode) {
this._recursivelyUpdateSubtree(id, element => {
element.isStrictModeNonCompliant = false;
});
}
if (__DEBUG__) {
debug(
'Subtree mode',
`Subtree with root ${id} set to mode ${mode}`,
);
}
break;
}
case TREE_OPERATION_UPDATE_TREE_BASE_DURATION:
// Base duration updates are only sent while profiling is in progress.
// We can ignore them at this point.
// The profiler UI uses them lazily in order to generate the tree.
i += 3;
break;
case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS:
const id = operations[i + 1];
const errorCount = operations[i + 2];
const warningCount = operations[i + 3];
i += 4;
if (errorCount > 0 || warningCount > 0) {
this._errorsAndWarnings.set(id, {errorCount, warningCount});
} else if (this._errorsAndWarnings.has(id)) {
this._errorsAndWarnings.delete(id);
}
haveErrorsOrWarningsChanged = true;
break;
default:
this._throwAndEmitError(
new UnsupportedBridgeOperationError(
`Unsupported Bridge operation "${operation}"`,
),
);
}
}
this._revision++;
// Any time the tree changes (e.g. elements added, removed, or reordered) cached indices may be invalid.
this._cachedErrorAndWarningTuples = null;
if (haveErrorsOrWarningsChanged) {
let errorCount = 0;
let warningCount = 0;
this._errorsAndWarnings.forEach(entry => {
errorCount += entry.errorCount;
warningCount += entry.warningCount;
});
this._cachedErrorCount = errorCount;
this._cachedWarningCount = warningCount;
}
if (haveRootsChanged) {
const prevRootSupportsProfiling = this._rootSupportsBasicProfiling;
const prevRootSupportsTimelineProfiling =
this._rootSupportsTimelineProfiling;
this._hasOwnerMetadata = false;
this._rootSupportsBasicProfiling = false;
this._rootSupportsTimelineProfiling = false;
this._rootIDToCapabilities.forEach(
({supportsBasicProfiling, hasOwnerMetadata, supportsTimeline}) => {
if (supportsBasicProfiling) {
this._rootSupportsBasicProfiling = true;
}
if (hasOwnerMetadata) {
this._hasOwnerMetadata = true;
}
if (supportsTimeline) {
this._rootSupportsTimelineProfiling = true;
}
},
);
this.emit('roots');
if (this._rootSupportsBasicProfiling !== prevRootSupportsProfiling) {
this.emit('rootSupportsBasicProfiling');
}
if (
this._rootSupportsTimelineProfiling !==
prevRootSupportsTimelineProfiling
) {
this.emit('rootSupportsTimelineProfiling');
}
}
if (__DEBUG__) {
console.log(printStore(this, true));
console.groupEnd();
}
this.emit('mutated', [addedElementIDs, removedElementIDs]);
};
// Certain backends save filters on a per-domain basis.
// In order to prevent filter preferences and applied filters from being out of sync,
// this message enables the backend to override the frontend's current ("saved") filters.
// This action should also override the saved filters too,
// else reloading the frontend without reloading the backend would leave things out of sync.
onBridgeOverrideComponentFilters: (
componentFilters: Array<ComponentFilter>,
) => void = componentFilters => {
this._componentFilters = componentFilters;
setSavedComponentFilters(componentFilters);
};
onBridgeShutdown: () => void = () => {
if (__DEBUG__) {
debug('onBridgeShutdown', 'unsubscribing from Bridge');
}
const bridge = this._bridge;
bridge.removeListener('operations', this.onBridgeOperations);
bridge.removeListener(
'overrideComponentFilters',
this.onBridgeOverrideComponentFilters,
);
bridge.removeListener('shutdown', this.onBridgeShutdown);
bridge.removeListener(
'isBackendStorageAPISupported',
this.onBackendStorageAPISupported,
);
bridge.removeListener(
'isNativeStyleEditorSupported',
this.onBridgeNativeStyleEditorSupported,
);
bridge.removeListener(
'isSynchronousXHRSupported',
this.onBridgeSynchronousXHRSupported,
);
bridge.removeListener(
'unsupportedRendererVersion',
this.onBridgeUnsupportedRendererVersion,
);
bridge.removeListener('backendVersion', this.onBridgeBackendVersion);
bridge.removeListener('bridgeProtocol', this.onBridgeProtocol);
bridge.removeListener('saveToClipboard', this.onSaveToClipboard);
if (this._onBridgeProtocolTimeoutID !== null) {
clearTimeout(this._onBridgeProtocolTimeoutID);
this._onBridgeProtocolTimeoutID = null;
}
};
onBackendStorageAPISupported: (
isBackendStorageAPISupported: boolean,
) => void = isBackendStorageAPISupported => {
this._isBackendStorageAPISupported = isBackendStorageAPISupported;
this.emit('supportsReloadAndProfile');
};
onBridgeSynchronousXHRSupported: (
isSynchronousXHRSupported: boolean,
) => void = isSynchronousXHRSupported => {
this._isSynchronousXHRSupported = isSynchronousXHRSupported;
this.emit('supportsReloadAndProfile');
};
onBridgeUnsupportedRendererVersion: () => void = () => {
this._unsupportedRendererVersionDetected = true;
this.emit('unsupportedRendererVersionDetected');
};
onBridgeBackendVersion: (backendVersion: string) => void = backendVersion => {
this._backendVersion = backendVersion;
this.emit('backendVersion');
};
onBridgeProtocol: (bridgeProtocol: BridgeProtocol) => void =
bridgeProtocol => {
if (this._onBridgeProtocolTimeoutID !== null) {
clearTimeout(this._onBridgeProtocolTimeoutID);
this._onBridgeProtocolTimeoutID = null;
}
this._bridgeProtocol = bridgeProtocol;
if (bridgeProtocol.version !== currentBridgeProtocol.version) {
// Technically newer versions of the frontend can, at least for now,
// gracefully handle older versions of the backend protocol.
// So for now we don't need to display the unsupported dialog.
}
};
onBridgeProtocolTimeout: () => void = () => {
this._onBridgeProtocolTimeoutID = null;
// If we timed out, that indicates the backend predates the bridge protocol,
// so we can set a fake version (0) to trigger the downgrade message.
this._bridgeProtocol = BRIDGE_PROTOCOL[0];
this.emit('unsupportedBridgeProtocolDetected');
};
onSaveToClipboard: (text: string) => void = text => {
copy(text);
};
// The Store should never throw an Error without also emitting an event.
// Otherwise Store errors will be invisible to users,
// but the downstream errors they cause will be reported as bugs.
// For example, https://github.com/facebook/react/issues/21402
// Emitting an error event allows the ErrorBoundary to show the original error.
_throwAndEmitError(error: Error): empty {
this.emit('error', error);
// Throwing is still valuable for local development
// and for unit testing the Store itself.
throw error;
}
}
| 30.779987 | 124 | 0.615786 |
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 {Request} from 'react-server/src/ReactFlightServer';
export * from 'react-server-dom-turbopack/src/ReactFlightServerConfigTurbopackBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';
export const supportsRequestStorage = false;
export const requestStorage: AsyncLocalStorage<Request> = (null: any);
export * from '../ReactFlightServerConfigDebugNoop';
| 30.789474 | 87 | 0.769486 |
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
*/
export * from 'react-client/src/ReactFlightClientConfigBrowser';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export type Response = any;
export opaque type ModuleLoading = mixed;
export opaque type SSRModuleMap = mixed;
export opaque type ServerManifest = mixed;
export opaque type ServerReferenceId = string;
export opaque type ClientReferenceMetadata = mixed;
export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars
export const resolveClientReference: any = null;
export const resolveServerReference: any = null;
export const preloadModule: any = null;
export const requireModule: any = null;
export const prepareDestinationForModule: any = null;
export const usedWithSSR = true;
| 35.461538 | 84 | 0.781415 |
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.
*/
'use strict';
const {
parse,
SimpleTraverser: {traverse},
} = require('hermes-parser');
const fs = require('fs');
const through = require('through2');
const gs = require('glob-stream');
const {evalStringConcat} = require('../shared/evalToString');
const warnings = new Set();
function transform(file, enc, cb) {
fs.readFile(file.path, 'utf8', function (err, source) {
if (err) {
cb(err);
return;
}
let ast;
try {
ast = parse(source);
} catch (error) {
console.error('Failed to parse source file:', file.path);
throw error;
}
traverse(ast, {
enter() {},
leave(node) {
if (node.type !== 'CallExpression') {
return;
}
const callee = node.callee;
if (
callee.type === 'MemberExpression' &&
callee.object.type === 'Identifier' &&
callee.object.name === 'console' &&
callee.property.type === 'Identifier' &&
(callee.property.name === 'warn' || callee.property.name === 'error')
) {
// warning messages can be concatenated (`+`) at runtime, so here's
// a trivial partial evaluator that interprets the literal value
try {
const warningMsgLiteral = evalStringConcat(node.arguments[0]);
warnings.add(warningMsgLiteral);
} catch {
// Silently skip over this call. We have a lint rule to enforce
// that all calls are extractable, so if this one fails, assume
// it's intentional.
}
}
},
});
cb(null);
});
}
gs([
'packages/**/*.js',
'!packages/*/npm/**/*.js',
'!packages/shared/consoleWithStackDev.js',
'!packages/react-devtools*/**/*.js',
'!**/__tests__/**/*.js',
'!**/__mocks__/**/*.js',
'!**/node_modules/**/*.js',
]).pipe(
through.obj(transform, cb => {
const warningsArray = Array.from(warnings);
warningsArray.sort();
process.stdout.write(
`/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @noformat
* @oncall react_core
*/
export default ${JSON.stringify(warningsArray, null, 2)};
`
);
cb();
})
);
| 24.622449 | 79 | 0.576494 |
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
*/
// Below code forked from dom-accessibility-api
const tagToRoleMappings = {
ARTICLE: 'article',
ASIDE: 'complementary',
BODY: 'document',
BUTTON: 'button',
DATALIST: 'listbox',
DD: 'definition',
DETAILS: 'group',
DIALOG: 'dialog',
DT: 'term',
FIELDSET: 'group',
FIGURE: 'figure',
// WARNING: Only with an accessible name
FORM: 'form',
FOOTER: 'contentinfo',
H1: 'heading',
H2: 'heading',
H3: 'heading',
H4: 'heading',
H5: 'heading',
H6: 'heading',
HEADER: 'banner',
HR: 'separator',
LEGEND: 'legend',
LI: 'listitem',
MATH: 'math',
MAIN: 'main',
MENU: 'list',
NAV: 'navigation',
OL: 'list',
OPTGROUP: 'group',
// WARNING: Only in certain context
OPTION: 'option',
OUTPUT: 'status',
PROGRESS: 'progressbar',
// WARNING: Only with an accessible name
SECTION: 'region',
SUMMARY: 'button',
TABLE: 'table',
TBODY: 'rowgroup',
TEXTAREA: 'textbox',
TFOOT: 'rowgroup',
// WARNING: Only in certain context
TD: 'cell',
TH: 'columnheader',
THEAD: 'rowgroup',
TR: 'row',
UL: 'list',
};
function getImplicitRole(element: Element): string | null {
const mappedByTag = tagToRoleMappings[element.tagName];
if (mappedByTag !== undefined) {
return mappedByTag;
}
switch (element.tagName) {
case 'A':
case 'AREA':
case 'LINK':
if (element.hasAttribute('href')) {
return 'link';
}
break;
case 'IMG':
if ((element.getAttribute('alt') || '').length > 0) {
return 'img';
}
break;
case 'INPUT': {
const type = (element: any).type;
switch (type) {
case 'button':
case 'image':
case 'reset':
case 'submit':
return 'button';
case 'checkbox':
case 'radio':
return type;
case 'range':
return 'slider';
case 'email':
case 'tel':
case 'text':
case 'url':
if (element.hasAttribute('list')) {
return 'combobox';
}
return 'textbox';
case 'search':
if (element.hasAttribute('list')) {
return 'combobox';
}
return 'searchbox';
default:
return null;
}
}
case 'SELECT':
if (element.hasAttribute('multiple') || (element: any).size > 1) {
return 'listbox';
}
return 'combobox';
}
return null;
}
function getExplicitRoles(element: Element): Array<string> | null {
const role = element.getAttribute('role');
if (role) {
return role.trim().split(' ');
}
return null;
}
// https://w3c.github.io/html-aria/#document-conformance-requirements-for-use-of-aria-attributes-in-html
export function hasRole(element: Element, role: string): boolean {
const explicitRoles = getExplicitRoles(element);
if (explicitRoles !== null && explicitRoles.indexOf(role) >= 0) {
return true;
}
return role === getImplicitRole(element);
}
| 21.65 | 104 | 0.582019 |
PenetrationTestingScripts | #!/usr/bin/env node
'use strict';
const chalk = require('chalk');
const {execSync} = require('child_process');
const {join} = require('path');
const {argv} = require('yargs');
const build = require('../build');
const main = async () => {
const {crx} = argv;
await build('edge');
const cwd = join(__dirname, 'build');
if (crx) {
const crxPath = join(__dirname, '..', 'node_modules', '.bin', 'crx');
execSync(`${crxPath} pack ./unpacked -o ReactDevTools.crx`, {
cwd,
});
}
console.log(chalk.green('\nThe Microsoft Edge extension has been built!'));
console.log(chalk.green('\nTo load this extension:'));
console.log(chalk.yellow('Navigate to edge://extensions/'));
console.log(chalk.yellow('Enable "Developer mode"'));
console.log(chalk.yellow('Click "LOAD UNPACKED"'));
console.log(chalk.yellow('Select extension folder - ' + cwd + '\\unpacked'));
console.log(chalk.green('\nYou can test this build by running:'));
console.log(chalk.gray('\n# From the react-devtools root directory:'));
console.log('yarn run test:edge\n');
};
main();
| 26.3 | 79 | 0.64253 |
Hands-On-Penetration-Testing-with-Python | "use strict";
/**
* 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.
*
*
*/
const {
useMemo,
useState
} = require('react');
function Component(props) {
const InnerComponent = useMemo(() => () => {
const [state] = useState(0);
return state;
});
props.callback(InnerComponent);
return null;
}
module.exports = {
Component
};
//# sourceMappingURL=ComponentWithNestedHooks.js.map?foo=bar¶m=some_value | 19.071429 | 77 | 0.675579 |
null | #!/usr/bin/env node
'use strict';
const {join} = require('path');
const {getPublicPackages, handleError} = require('./utils');
const checkOutPackages = require('./prepare-release-from-npm-commands/check-out-packages');
const confirmStableVersionNumbers = require('./prepare-release-from-npm-commands/confirm-stable-version-numbers');
const getLatestNextVersion = require('./prepare-release-from-npm-commands/get-latest-next-version');
const guessStableVersionNumbers = require('./prepare-release-from-npm-commands/guess-stable-version-numbers');
const parseParams = require('./prepare-release-from-npm-commands/parse-params');
const printPrereleaseSummary = require('./shared-commands/print-prerelease-summary');
const testPackagingFixture = require('./shared-commands/test-packaging-fixture');
const updateStableVersionNumbers = require('./prepare-release-from-npm-commands/update-stable-version-numbers');
const theme = require('./theme');
const run = async () => {
try {
const params = parseParams();
params.cwd = join(__dirname, '..', '..');
const isExperimental = params.version.includes('experimental');
if (!params.version) {
params.version = await getLatestNextVersion();
}
params.packages = await getPublicPackages(isExperimental);
// Map of package name to upcoming stable version.
// This Map is initially populated with guesses based on local versions.
// The developer running the release later confirms or overrides each version.
const versionsMap = new Map();
if (isExperimental) {
console.error(
theme.error`Cannot promote an experimental build to stable.`
);
process.exit(1);
}
await checkOutPackages(params);
await guessStableVersionNumbers(params, versionsMap);
await confirmStableVersionNumbers(params, versionsMap);
await updateStableVersionNumbers(params, versionsMap);
if (!params.skipTests) {
await testPackagingFixture(params);
}
await printPrereleaseSummary(params, true);
} catch (error) {
handleError(error);
}
};
run();
| 34.372881 | 114 | 0.724832 |
cybersecurity-penetration-testing | 'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-interactions-events/press.production.min.js');
} else {
module.exports = require('./cjs/react-interactions-events/press.development.js');
}
| 29.375 | 86 | 0.710744 |
PenTesting | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export type ImportManifestEntry = {
id: string,
// chunks is an array of filenames
chunks: Array<string>,
name: string,
};
// This is the parsed shape of the wire format which is why it is
// condensed to only the essentialy information
export type ImportMetadata =
| [
/* id */ string,
/* chunk filenames */ Array<string>,
/* name */ string,
/* async */ 1,
]
| [/* id */ string, /* chunk filenames */ Array<string>, /* name */ string];
export const ID = 0;
export const CHUNKS = 1;
export const NAME = 2;
// export const ASYNC = 3;
// This logic is correct because currently only include the 4th tuple member
// when the module is async. If that changes we will need to actually assert
// the value is true. We don't index into the 4th slot because flow does not
// like the potential out of bounds access
export function isAsyncImport(metadata: ImportMetadata): boolean {
return metadata.length === 4;
}
| 27.9 | 78 | 0.681385 |
null | 'use strict';
const {exec} = require('child-process-promise');
const {createPatch} = require('diff');
const {hashElement} = require('folder-hash');
const {existsSync, readFileSync, writeFileSync} = require('fs');
const {readJson, writeJson} = require('fs-extra');
const fetch = require('node-fetch');
const logUpdate = require('log-update');
const {join} = require('path');
const createLogger = require('progress-estimator');
const prompt = require('prompt-promise');
const theme = require('./theme');
const {stablePackages, experimentalPackages} = require('../../ReactVersions');
// https://www.npmjs.com/package/progress-estimator#configuration
const logger = createLogger({
storagePath: join(__dirname, '.progress-estimator'),
});
const addDefaultParamValue = (optionalShortName, longName, defaultValue) => {
let found = false;
for (let i = 0; i < process.argv.length; i++) {
const current = process.argv[i];
if (current === optionalShortName || current.startsWith(`${longName}=`)) {
found = true;
break;
}
}
if (!found) {
process.argv.push(`${longName}=${defaultValue}`);
}
};
const confirm = async message => {
const confirmation = await prompt(theme`\n{caution ${message}} (y/N) `);
prompt.done();
if (confirmation !== 'y' && confirmation !== 'Y') {
console.log(theme`\n{caution Release cancelled.}`);
process.exit(0);
}
};
const execRead = async (command, options) => {
const {stdout} = await exec(command, options);
return stdout.trim();
};
const extractCommitFromVersionNumber = version => {
// Support stable version format e.g. "0.0.0-0e526bcec-20210202"
// and experimental version format e.g. "0.0.0-experimental-0e526bcec-20210202"
const match = version.match(/0\.0\.0\-([a-z]+\-){0,1}([^-]+).+/);
if (match === null) {
throw Error(`Could not extra commit from version "${version}"`);
}
return match[2];
};
const getArtifactsList = async buildID => {
const headers = {};
const {CIRCLE_CI_API_TOKEN} = process.env;
if (CIRCLE_CI_API_TOKEN != null) {
headers['Circle-Token'] = CIRCLE_CI_API_TOKEN;
}
const jobArtifactsURL = `https://circleci.com/api/v1.1/project/github/facebook/react/${buildID}/artifacts`;
const jobArtifacts = await fetch(jobArtifactsURL, {headers});
return jobArtifacts.json();
};
const getBuildInfo = async () => {
const cwd = join(__dirname, '..', '..');
const isExperimental = process.env.RELEASE_CHANNEL === 'experimental';
const branch = await execRead('git branch | grep \\* | cut -d " " -f2', {
cwd,
});
const commit = await execRead('git show -s --no-show-signature --format=%h', {
cwd,
});
const checksum = await getChecksumForCurrentRevision(cwd);
const dateString = await getDateStringForCommit(commit);
const version = isExperimental
? `0.0.0-experimental-${commit}-${dateString}`
: `0.0.0-${commit}-${dateString}`;
// Only available for Circle CI builds.
// https://circleci.com/docs/2.0/env-vars/
const buildNumber = process.env.CIRCLE_BUILD_NUM;
// React version is stored explicitly, separately for DevTools support.
// See updateVersionsForNext() below for more info.
const packageJSON = await readJson(
join(cwd, 'packages', 'react', 'package.json')
);
const reactVersion = isExperimental
? `${packageJSON.version}-experimental-${commit}-${dateString}`
: `${packageJSON.version}-${commit}-${dateString}`;
return {branch, buildNumber, checksum, commit, reactVersion, version};
};
const getChecksumForCurrentRevision = async cwd => {
const packagesDir = join(cwd, 'packages');
const hashedPackages = await hashElement(packagesDir, {
encoding: 'hex',
files: {exclude: ['.DS_Store']},
});
return hashedPackages.hash.slice(0, 7);
};
const getDateStringForCommit = async commit => {
let dateString = await execRead(
`git show -s --no-show-signature --format=%cd --date=format:%Y%m%d ${commit}`
);
// On CI environment, this string is wrapped with quotes '...'s
if (dateString.startsWith("'")) {
dateString = dateString.slice(1, 9);
}
return dateString;
};
const getCommitFromCurrentBuild = async () => {
const cwd = join(__dirname, '..', '..');
// If this build includes a build-info.json file, extract the commit from it.
// Otherwise fall back to parsing from the package version number.
// This is important to make the build reproducible (e.g. by Mozilla reviewers).
const buildInfoJSON = join(
cwd,
'build',
'oss-experimental',
'react',
'build-info.json'
);
if (existsSync(buildInfoJSON)) {
const buildInfo = await readJson(buildInfoJSON);
return buildInfo.commit;
} else {
const packageJSON = join(
cwd,
'build',
'oss-experimental',
'react',
'package.json'
);
const {version} = await readJson(packageJSON);
return extractCommitFromVersionNumber(version);
}
};
const getPublicPackages = isExperimental => {
const packageNames = Object.keys(stablePackages);
if (isExperimental) {
packageNames.push(...experimentalPackages);
}
return packageNames;
};
const handleError = error => {
logUpdate.clear();
const message = error.message.trim().replace(/\n +/g, '\n');
const stack = error.stack.replace(error.message, '');
console.log(theme`{error ${message}}\n\n{path ${stack}}`);
process.exit(1);
};
const logPromise = async (promise, text, estimate) =>
logger(promise, text, {estimate});
const printDiff = (path, beforeContents, afterContents) => {
const patch = createPatch(path, beforeContents, afterContents);
const coloredLines = patch
.split('\n')
.slice(2) // Trim index file
.map((line, index) => {
if (index <= 1) {
return theme.diffHeader(line);
}
switch (line[0]) {
case '+':
return theme.diffAdded(line);
case '-':
return theme.diffRemoved(line);
case ' ':
return line;
case '@':
return null;
case '\\':
return null;
}
})
.filter(line => line);
console.log(coloredLines.join('\n'));
return patch;
};
// Convert an array param (expected format "--foo bar baz")
// to also accept comma input (e.g. "--foo bar,baz")
const splitCommaParams = array => {
for (let i = array.length - 1; i >= 0; i--) {
const param = array[i];
if (param.includes(',')) {
array.splice(i, 1, ...param.split(','));
}
}
};
// This method is used by both local Node release scripts and Circle CI bash scripts.
// It updates version numbers in package JSONs (both the version field and dependencies),
// As well as the embedded renderer version in "packages/shared/ReactVersion".
// Canaries version numbers use the format of 0.0.0-<sha>-<date> to be easily recognized (e.g. 0.0.0-01974a867-20200129).
// A separate "React version" is used for the embedded renderer version to support DevTools,
// since it needs to distinguish between different version ranges of React.
// It is based on the version of React in the local package.json (e.g. 16.12.0-01974a867-20200129).
// Both numbers will be replaced if the "next" release is promoted to a stable release.
const updateVersionsForNext = async (cwd, reactVersion, version) => {
const isExperimental = reactVersion.includes('experimental');
const packages = getPublicPackages(isExperimental);
const packagesDir = join(cwd, 'packages');
// Update the shared React version source file.
// This is bundled into built renderers.
// The promote script will replace this with a final version later.
const sourceReactVersionPath = join(cwd, 'packages/shared/ReactVersion.js');
const sourceReactVersion = readFileSync(
sourceReactVersionPath,
'utf8'
).replace(/export default '[^']+';/, `export default '${reactVersion}';`);
writeFileSync(sourceReactVersionPath, sourceReactVersion);
// Update the root package.json.
// This is required to pass a later version check script.
{
const packageJSONPath = join(cwd, 'package.json');
const packageJSON = await readJson(packageJSONPath);
packageJSON.version = version;
await writeJson(packageJSONPath, packageJSON, {spaces: 2});
}
for (let i = 0; i < packages.length; i++) {
const packageName = packages[i];
const packagePath = join(packagesDir, packageName);
// Update version numbers in package JSONs
const packageJSONPath = join(packagePath, 'package.json');
const packageJSON = await readJson(packageJSONPath);
packageJSON.version = version;
// Also update inter-package dependencies.
// Next releases always have exact version matches.
// The promote script may later relax these (e.g. "^x.x.x") based on source package JSONs.
const {dependencies, peerDependencies} = packageJSON;
for (let j = 0; j < packages.length; j++) {
const dependencyName = packages[j];
if (dependencies && dependencies[dependencyName]) {
dependencies[dependencyName] = version;
}
if (peerDependencies && peerDependencies[dependencyName]) {
peerDependencies[dependencyName] = version;
}
}
await writeJson(packageJSONPath, packageJSON, {spaces: 2});
}
};
module.exports = {
addDefaultParamValue,
confirm,
execRead,
getArtifactsList,
getBuildInfo,
getChecksumForCurrentRevision,
getCommitFromCurrentBuild,
getDateStringForCommit,
getPublicPackages,
handleError,
logPromise,
printDiff,
splitCommaParams,
theme,
updateVersionsForNext,
};
| 31.728522 | 121 | 0.671637 |
PenetrationTestingScripts | 'use strict';
const {resolve} = require('path');
const Webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('./utils');
const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils');
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
console.error('NODE_ENV not set');
process.exit(1);
}
const builtModulesDir = resolve(
__dirname,
'..',
'..',
'build',
'oss-experimental',
);
const __DEV__ = NODE_ENV === 'development';
const DEVTOOLS_VERSION = getVersionString(process.env.DEVTOOLS_VERSION);
const EDITOR_URL = process.env.EDITOR_URL || null;
const LOGGING_URL = process.env.LOGGING_URL || null;
const IS_CHROME = process.env.IS_CHROME === 'true';
const IS_FIREFOX = process.env.IS_FIREFOX === 'true';
const IS_EDGE = process.env.IS_EDGE === 'true';
const featureFlagTarget = process.env.FEATURE_FLAG_TARGET || 'extension-oss';
const babelOptions = {
configFile: resolve(
__dirname,
'..',
'react-devtools-shared',
'babel.config.js',
),
};
module.exports = {
mode: __DEV__ ? 'development' : 'production',
devtool: __DEV__ ? 'cheap-module-source-map' : false,
entry: {
background: './src/background/index.js',
backendManager: './src/contentScripts/backendManager.js',
fileFetcher: './src/contentScripts/fileFetcher.js',
main: './src/main/index.js',
panel: './src/panel.js',
proxy: './src/contentScripts/proxy.js',
prepareInjection: './src/contentScripts/prepareInjection.js',
renderer: './src/contentScripts/renderer.js',
installHook: './src/contentScripts/installHook.js',
},
output: {
path: __dirname + '/build',
publicPath: '/build/',
filename: '[name].js',
chunkFilename: '[name].chunk.js',
},
node: {
global: false,
},
resolve: {
alias: {
react: resolve(builtModulesDir, 'react'),
'react-debug-tools': resolve(builtModulesDir, 'react-debug-tools'),
'react-devtools-feature-flags': resolveFeatureFlags(featureFlagTarget),
'react-dom/client': resolve(builtModulesDir, 'react-dom/client'),
'react-dom': resolve(builtModulesDir, 'react-dom'),
'react-is': resolve(builtModulesDir, 'react-is'),
scheduler: resolve(builtModulesDir, 'scheduler'),
},
},
optimization: {
minimize: !__DEV__,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
unused: true,
dead_code: true,
},
mangle: {
keep_fnames: true,
},
format: {
comments: false,
},
},
extractComments: false,
}),
],
},
plugins: [
new Webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer'],
}),
new Webpack.DefinePlugin({
__DEV__,
__EXPERIMENTAL__: true,
__EXTENSION__: true,
__PROFILE__: false,
__TEST__: NODE_ENV === 'test',
__IS_CHROME__: IS_CHROME,
__IS_FIREFOX__: IS_FIREFOX,
__IS_EDGE__: IS_EDGE,
'process.env.DEVTOOLS_PACKAGE': `"react-devtools-extensions"`,
'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`,
'process.env.EDITOR_URL': EDITOR_URL != null ? `"${EDITOR_URL}"` : null,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.LOGGING_URL': `"${LOGGING_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
}),
],
module: {
defaultRules: [
{
type: 'javascript/auto',
resolve: {},
},
{
test: /\.json$/i,
type: 'json',
},
],
rules: [
{
test: /\.worker\.js$/,
use: [
{
loader: 'workerize-loader',
options: {
inline: true,
name: '[name]',
},
},
{
loader: 'babel-loader',
options: babelOptions,
},
],
},
{
test: /\.js$/,
loader: 'babel-loader',
options: babelOptions,
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
localIdentName: '[local]___[hash:base64:5]',
},
},
],
},
],
},
};
| 26.386243 | 92 | 0.560193 |
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 {ReactNodeList} from 'shared/ReactTypes';
import {version, renderToStringImpl} from './ReactDOMLegacyServerImpl';
type ServerOptions = {
identifierPrefix?: string,
};
function renderToString(
children: ReactNodeList,
options?: ServerOptions,
): string {
return renderToStringImpl(
children,
options,
false,
'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server',
);
}
function renderToStaticMarkup(
children: ReactNodeList,
options?: ServerOptions,
): string {
return renderToStringImpl(
children,
options,
true,
'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server',
);
}
function renderToNodeStream() {
throw new Error(
'ReactDOMServer.renderToNodeStream(): The streaming API is not available ' +
'in the browser. Use ReactDOMServer.renderToString() instead.',
);
}
function renderToStaticNodeStream() {
throw new Error(
'ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' +
'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.',
);
}
export {
renderToString,
renderToStaticMarkup,
renderToNodeStream,
renderToStaticNodeStream,
version,
};
| 28.873016 | 375 | 0.750133 |
owtf | var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
| 21.375 | 50 | 0.702247 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useTheme;
exports.ThemeContext = void 0;
var _react = require("react");
/**
* 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.
*
*
*/
const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright');
exports.ThemeContext = ThemeContext;
function useTheme() {
const theme = (0, _react.useContext)(ThemeContext);
(0, _react.useDebugValue)(theme);
return theme;
}
//# sourceMappingURL=useTheme.js.map?foo=bar¶m=some_value | 23.851852 | 70 | 0.701493 |
null | 'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/use-sync-external-store-with-selector.production.min.js');
} else {
module.exports = require('./cjs/use-sync-external-store-with-selector.development.js');
}
| 30.875 | 92 | 0.708661 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
/**
* 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.
*
*
*/
function Component() {
const [count] = require('react').useState(0);
return count;
}
//# sourceMappingURL=InlineRequire.js.map?foo=bar¶m=some_value | 21.238095 | 66 | 0.701717 |
PenetrationTestingScripts | /* global chrome */
class CouldNotFindReactOnThePageError extends Error {
constructor() {
super("Could not find React, or it hasn't been loaded yet");
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CouldNotFindReactOnThePageError);
}
this.name = 'CouldNotFindReactOnThePageError';
}
}
export function startReactPolling(
onReactFound,
attemptsThreshold,
onCouldNotFindReactAfterReachingAttemptsThreshold,
) {
let status = 'idle';
function abort() {
status = 'aborted';
}
// This function will call onSuccess only if React was found and polling is not aborted, onError will be called for every other case
function checkIfReactPresentInInspectedWindow(onSuccess, onError) {
chrome.devtools.inspectedWindow.eval(
'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0',
(pageHasReact, exceptionInfo) => {
if (status === 'aborted') {
onError(
'Polling was aborted, user probably navigated to the other page',
);
return;
}
if (exceptionInfo) {
const {code, description, isError, isException, value} =
exceptionInfo;
if (isException) {
onError(
`Received error while checking if react has loaded: ${value}`,
);
return;
}
if (isError) {
onError(
`Received error with code ${code} while checking if react has loaded: "${description}"`,
);
return;
}
}
if (pageHasReact) {
onSuccess();
return;
}
onError(new CouldNotFindReactOnThePageError());
},
);
}
// Just a Promise wrapper around `checkIfReactPresentInInspectedWindow`
// returns a Promise, which will resolve only if React has been found on the page
function poll(attempt) {
return new Promise((resolve, reject) => {
checkIfReactPresentInInspectedWindow(resolve, reject);
}).catch(error => {
if (error instanceof CouldNotFindReactOnThePageError) {
if (attempt === attemptsThreshold) {
onCouldNotFindReactAfterReachingAttemptsThreshold();
}
// Start next attempt in 0.5s
return new Promise(r => setTimeout(r, 500)).then(() =>
poll(attempt + 1),
);
}
// Propagating every other Error
throw error;
});
}
poll(1)
.then(onReactFound)
.catch(error => {
// Log propagated errors only if polling was not aborted
// Some errors are expected when user performs in-tab navigation and `.eval()` is still being executed
if (status === 'aborted') {
return;
}
console.error(error);
});
return {abort};
}
| 27.057692 | 134 | 0.613301 |
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
*/
'use strict';
let React;
let ReactNoop;
let Scheduler;
let ContinuousEventPriority;
let act;
let waitForAll;
let waitFor;
let assertLog;
describe('ReactIncrementalUpdates', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
ContinuousEventPriority =
require('react-reconciler/constants').ContinuousEventPriority;
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
waitFor = InternalTestUtils.waitFor;
assertLog = InternalTestUtils.assertLog;
});
function Text({text}) {
Scheduler.log(text);
return text;
}
it('applies updates in order of priority', async () => {
let state;
class Foo extends React.Component {
state = {};
componentDidMount() {
Scheduler.log('commit');
React.startTransition(() => {
// Has low priority
this.setState({b: 'b'});
this.setState({c: 'c'});
});
// Has Task priority
this.setState({a: 'a'});
}
render() {
state = this.state;
return <div />;
}
}
ReactNoop.render(<Foo />);
await waitFor(['commit']);
expect(state).toEqual({a: 'a'});
await waitForAll([]);
expect(state).toEqual({a: 'a', b: 'b', c: 'c'});
});
it('applies updates with equal priority in insertion order', async () => {
let state;
class Foo extends React.Component {
state = {};
componentDidMount() {
// All have Task priority
this.setState({a: 'a'});
this.setState({b: 'b'});
this.setState({c: 'c'});
}
render() {
state = this.state;
return <div />;
}
}
ReactNoop.render(<Foo />);
await waitForAll([]);
expect(state).toEqual({a: 'a', b: 'b', c: 'c'});
});
it('only drops updates with equal or lesser priority when replaceState is called', async () => {
let instance;
class Foo extends React.Component {
state = {};
componentDidMount() {
Scheduler.log('componentDidMount');
}
componentDidUpdate() {
Scheduler.log('componentDidUpdate');
}
render() {
Scheduler.log('render');
instance = this;
return <div />;
}
}
ReactNoop.render(<Foo />);
await waitForAll(['render', 'componentDidMount']);
ReactNoop.flushSync(() => {
React.startTransition(() => {
instance.setState({x: 'x'});
instance.setState({y: 'y'});
});
instance.setState({a: 'a'});
instance.setState({b: 'b'});
React.startTransition(() => {
instance.updater.enqueueReplaceState(instance, {c: 'c'});
instance.setState({d: 'd'});
});
});
// Even though a replaceState has been already scheduled, it hasn't been
// flushed yet because it has async priority.
expect(instance.state).toEqual({a: 'a', b: 'b'});
assertLog(['render', 'componentDidUpdate']);
await waitForAll(['render', 'componentDidUpdate']);
// Now the rest of the updates are flushed, including the replaceState.
expect(instance.state).toEqual({c: 'c', d: 'd'});
});
it('can abort an update, schedule additional updates, and resume', async () => {
let instance;
class Foo extends React.Component {
state = {};
render() {
instance = this;
return <span prop={Object.keys(this.state).sort().join('')} />;
}
}
ReactNoop.render(<Foo />);
await waitForAll([]);
function createUpdate(letter) {
return () => {
Scheduler.log(letter);
return {
[letter]: letter,
};
};
}
// Schedule some async updates
if (
gate(
flags =>
!flags.forceConcurrentByDefaultForTesting ||
flags.enableUnifiedSyncLane,
)
) {
React.startTransition(() => {
instance.setState(createUpdate('a'));
instance.setState(createUpdate('b'));
instance.setState(createUpdate('c'));
});
} else {
instance.setState(createUpdate('a'));
instance.setState(createUpdate('b'));
instance.setState(createUpdate('c'));
}
// Begin the updates but don't flush them yet
await waitFor(['a', 'b', 'c']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="" />);
// Schedule some more updates at different priorities
instance.setState(createUpdate('d'));
ReactNoop.flushSync(() => {
instance.setState(createUpdate('e'));
instance.setState(createUpdate('f'));
});
React.startTransition(() => {
instance.setState(createUpdate('g'));
});
// The sync updates should have flushed, but not the async ones.
if (
gate(
flags =>
!flags.forceConcurrentByDefaultForTesting &&
flags.enableUnifiedSyncLane,
)
) {
assertLog(['d', 'e', 'f']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="def" />);
} else {
// Update d was dropped and replaced by e.
assertLog(['e', 'f']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="ef" />);
}
// Now flush the remaining work. Even though e and f were already processed,
// they should be processed again, to ensure that the terminal state
// is deterministic.
if (
gate(
flags =>
!flags.forceConcurrentByDefaultForTesting &&
!flags.enableUnifiedSyncLane,
)
) {
await waitForAll([
// Since 'g' is in a transition, we'll process 'd' separately first.
// That causes us to process 'd' with 'e' and 'f' rebased.
'd',
'e',
'f',
// Then we'll re-process everything for 'g'.
'a',
'b',
'c',
'd',
'e',
'f',
'g',
]);
} else {
await waitForAll([
// Then we'll re-process everything for 'g'.
'a',
'b',
'c',
'd',
'e',
'f',
'g',
]);
}
expect(ReactNoop).toMatchRenderedOutput(<span prop="abcdefg" />);
});
it('can abort an update, schedule a replaceState, and resume', async () => {
let instance;
class Foo extends React.Component {
state = {};
render() {
instance = this;
return <span prop={Object.keys(this.state).sort().join('')} />;
}
}
ReactNoop.render(<Foo />);
await waitForAll([]);
function createUpdate(letter) {
return () => {
Scheduler.log(letter);
return {
[letter]: letter,
};
};
}
// Schedule some async updates
if (
gate(
flags =>
!flags.forceConcurrentByDefaultForTesting ||
flags.enableUnifiedSyncLane,
)
) {
React.startTransition(() => {
instance.setState(createUpdate('a'));
instance.setState(createUpdate('b'));
instance.setState(createUpdate('c'));
});
} else {
instance.setState(createUpdate('a'));
instance.setState(createUpdate('b'));
instance.setState(createUpdate('c'));
}
// Begin the updates but don't flush them yet
await waitFor(['a', 'b', 'c']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="" />);
// Schedule some more updates at different priorities
instance.setState(createUpdate('d'));
ReactNoop.flushSync(() => {
instance.setState(createUpdate('e'));
// No longer a public API, but we can test that it works internally by
// reaching into the updater.
instance.updater.enqueueReplaceState(instance, createUpdate('f'));
});
React.startTransition(() => {
instance.setState(createUpdate('g'));
});
// The sync updates should have flushed, but not the async ones.
if (
gate(
flags =>
!flags.forceConcurrentByDefaultForTesting &&
flags.enableUnifiedSyncLane,
)
) {
assertLog(['d', 'e', 'f']);
} else {
// Update d was dropped and replaced by e.
assertLog(['e', 'f']);
}
expect(ReactNoop).toMatchRenderedOutput(<span prop="f" />);
// Now flush the remaining work. Even though e and f were already processed,
// they should be processed again, to ensure that the terminal state
// is deterministic.
if (
gate(
flags =>
!flags.forceConcurrentByDefaultForTesting &&
!flags.enableUnifiedSyncLane,
)
) {
await waitForAll([
// Since 'g' is in a transition, we'll process 'd' separately first.
// That causes us to process 'd' with 'e' and 'f' rebased.
'd',
'e',
'f',
// Then we'll re-process everything for 'g'.
'a',
'b',
'c',
'd',
'e',
'f',
'g',
]);
} else {
await waitForAll([
// Then we'll re-process everything for 'g'.
'a',
'b',
'c',
'd',
'e',
'f',
'g',
]);
}
expect(ReactNoop).toMatchRenderedOutput(<span prop="fg" />);
});
it('passes accumulation of previous updates to replaceState updater function', async () => {
let instance;
class Foo extends React.Component {
state = {};
render() {
instance = this;
return <span />;
}
}
ReactNoop.render(<Foo />);
await waitForAll([]);
instance.setState({a: 'a'});
instance.setState({b: 'b'});
// No longer a public API, but we can test that it works internally by
// reaching into the updater.
instance.updater.enqueueReplaceState(instance, previousState => ({
previousState,
}));
await waitForAll([]);
expect(instance.state).toEqual({previousState: {a: 'a', b: 'b'}});
});
it('does not call callbacks that are scheduled by another callback until a later commit', async () => {
class Foo extends React.Component {
state = {};
componentDidMount() {
Scheduler.log('did mount');
this.setState({a: 'a'}, () => {
Scheduler.log('callback a');
this.setState({b: 'b'}, () => {
Scheduler.log('callback b');
});
});
}
render() {
Scheduler.log('render');
return <div />;
}
}
ReactNoop.render(<Foo />);
await waitForAll([
'render',
'did mount',
'render',
'callback a',
'render',
'callback b',
]);
});
it('gives setState during reconciliation the same priority as whatever level is currently reconciling', async () => {
let instance;
class Foo extends React.Component {
state = {};
UNSAFE_componentWillReceiveProps() {
Scheduler.log('componentWillReceiveProps');
this.setState({b: 'b'});
}
render() {
Scheduler.log('render');
instance = this;
return <div />;
}
}
ReactNoop.render(<Foo />);
await waitForAll(['render']);
ReactNoop.flushSync(() => {
instance.setState({a: 'a'});
ReactNoop.render(<Foo />); // Trigger componentWillReceiveProps
});
expect(instance.state).toEqual({a: 'a', b: 'b'});
assertLog(['componentWillReceiveProps', 'render']);
});
it('updates triggered from inside a class setState updater', async () => {
let instance;
class Foo extends React.Component {
state = {};
render() {
Scheduler.log('render');
instance = this;
return <div />;
}
}
ReactNoop.render(<Foo />);
await waitForAll([
// Initial render
'render',
]);
instance.setState(function a() {
Scheduler.log('setState updater');
this.setState({b: 'b'});
return {a: 'a'};
});
await expect(
async () =>
await waitForAll([
'setState updater',
// Updates in the render phase receive the currently rendering
// lane, so the update flushes immediately in the same render.
'render',
]),
).toErrorDev(
'An update (setState, replaceState, or forceUpdate) was scheduled ' +
'from inside an update function. Update functions should be pure, ' +
'with zero side-effects. Consider using componentDidUpdate or a ' +
'callback.\n\nPlease update the following component: Foo',
);
expect(instance.state).toEqual({a: 'a', b: 'b'});
// Test deduplication (no additional warnings expected)
instance.setState(function a() {
this.setState({a: 'a'});
return {b: 'b'};
});
await waitForAll(
gate(flags =>
// Updates in the render phase receive the currently rendering
// lane, so the update flushes immediately in the same render.
['render'],
),
);
});
it('getDerivedStateFromProps should update base state of updateQueue (based on product bug)', () => {
// Based on real-world bug.
let foo;
class Foo extends React.Component {
state = {value: 'initial state'};
static getDerivedStateFromProps() {
return {value: 'derived state'};
}
render() {
foo = this;
return (
<>
<span prop={this.state.value} />
<Bar />
</>
);
}
}
let bar;
class Bar extends React.Component {
render() {
bar = this;
return null;
}
}
ReactNoop.flushSync(() => {
ReactNoop.render(<Foo />);
});
expect(ReactNoop).toMatchRenderedOutput(<span prop="derived state" />);
ReactNoop.flushSync(() => {
// Triggers getDerivedStateFromProps again
ReactNoop.render(<Foo />);
// The noop callback is needed to trigger the specific internal path that
// led to this bug. Removing it causes it to "accidentally" work.
foo.setState({value: 'update state'}, function noop() {});
});
expect(ReactNoop).toMatchRenderedOutput(<span prop="derived state" />);
ReactNoop.flushSync(() => {
bar.setState({});
});
expect(ReactNoop).toMatchRenderedOutput(<span prop="derived state" />);
});
it('regression: does not expire soon due to layout effects in the last batch', async () => {
const {useState, useLayoutEffect} = React;
let setCount;
function App() {
const [count, _setCount] = useState(0);
setCount = _setCount;
Scheduler.log('Render: ' + count);
useLayoutEffect(() => {
setCount(1);
Scheduler.log('Commit: ' + count);
}, []);
return <Text text="Child" />;
}
await act(async () => {
React.startTransition(() => {
ReactNoop.render(<App />);
});
assertLog([]);
await waitForAll([
'Render: 0',
'Child',
'Commit: 0',
'Render: 1',
'Child',
]);
Scheduler.unstable_advanceTime(10000);
React.startTransition(() => {
setCount(2);
});
// The transition should not have expired, so we should be able to
// partially render it.
await waitFor(['Render: 2']);
// Now do the rest
await waitForAll(['Child']);
});
});
it('regression: does not expire soon due to previous flushSync', async () => {
ReactNoop.flushSync(() => {
ReactNoop.render(<Text text="A" />);
});
assertLog(['A']);
Scheduler.unstable_advanceTime(10000);
React.startTransition(() => {
ReactNoop.render(
<>
<Text text="A" />
<Text text="B" />
<Text text="C" />
<Text text="D" />
</>,
);
});
// The transition should not have expired, so we should be able to
// partially render it.
await waitFor(['A']);
await waitFor(['B']);
await waitForAll(['C', 'D']);
});
it('regression: does not expire soon due to previous expired work', async () => {
React.startTransition(() => {
ReactNoop.render(
<>
<Text text="A" />
<Text text="B" />
<Text text="C" />
<Text text="D" />
</>,
);
});
await waitFor(['A']);
// This will expire the rest of the update
Scheduler.unstable_advanceTime(10000);
await waitFor(['B'], {
additionalLogsAfterAttemptingToYield: ['C', 'D'],
});
Scheduler.unstable_advanceTime(10000);
// Now do another transition. This one should not expire.
React.startTransition(() => {
ReactNoop.render(
<>
<Text text="A" />
<Text text="B" />
<Text text="C" />
<Text text="D" />
</>,
);
});
// The transition should not have expired, so we should be able to
// partially render it.
await waitFor(['A']);
await waitFor(['B']);
await waitForAll(['C', 'D']);
});
it('when rebasing, does not exclude updates that were already committed, regardless of priority', async () => {
const {useState, useLayoutEffect} = React;
let pushToLog;
function App() {
const [log, setLog] = useState('');
pushToLog = msg => {
setLog(prevLog => prevLog + msg);
};
useLayoutEffect(() => {
Scheduler.log('Committed: ' + log);
if (log === 'B') {
// Right after B commits, schedule additional updates.
ReactNoop.unstable_runWithPriority(ContinuousEventPriority, () =>
pushToLog('C'),
);
setLog(prevLog => prevLog + 'D');
}
}, [log]);
return log;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['Committed: ']);
expect(root).toMatchRenderedOutput(null);
await act(() => {
React.startTransition(() => {
pushToLog('A');
});
ReactNoop.unstable_runWithPriority(ContinuousEventPriority, () =>
pushToLog('B'),
);
});
if (gate(flags => flags.enableUnifiedSyncLane)) {
assertLog(['Committed: B', 'Committed: BCD', 'Committed: ABCD']);
} else {
assertLog([
// A and B are pending. B is higher priority, so we'll render that first.
'Committed: B',
// Because A comes first in the queue, we're now in rebase mode. B must
// be rebased on top of A. Also, in a layout effect, we received two new
// updates: C and D. C is user-blocking and D is synchronous.
//
// First render the synchronous update. What we're testing here is that
// B *is not dropped* even though it has lower than sync priority. That's
// because we already committed it. However, this render should not
// include C, because that update wasn't already committed.
'Committed: BD',
'Committed: BCD',
'Committed: ABCD',
]);
}
expect(root).toMatchRenderedOutput('ABCD');
});
it('when rebasing, does not exclude updates that were already committed, regardless of priority (classes)', async () => {
let pushToLog;
class App extends React.Component {
state = {log: ''};
pushToLog = msg => {
this.setState(prevState => ({log: prevState.log + msg}));
};
componentDidUpdate() {
Scheduler.log('Committed: ' + this.state.log);
if (this.state.log === 'B') {
// Right after B commits, schedule additional updates.
ReactNoop.unstable_runWithPriority(ContinuousEventPriority, () =>
this.pushToLog('C'),
);
this.pushToLog('D');
}
}
render() {
pushToLog = this.pushToLog;
return this.state.log;
}
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog([]);
expect(root).toMatchRenderedOutput(null);
await act(() => {
React.startTransition(() => {
pushToLog('A');
});
ReactNoop.unstable_runWithPriority(ContinuousEventPriority, () =>
pushToLog('B'),
);
});
if (gate(flags => flags.enableUnifiedSyncLane)) {
assertLog(['Committed: B', 'Committed: BCD', 'Committed: ABCD']);
} else {
assertLog([
// A and B are pending. B is higher priority, so we'll render that first.
'Committed: B',
// Because A comes first in the queue, we're now in rebase mode. B must
// be rebased on top of A. Also, in a layout effect, we received two new
// updates: C and D. C is user-blocking and D is synchronous.
//
// First render the synchronous update. What we're testing here is that
// B *is not dropped* even though it has lower than sync priority. That's
// because we already committed it. However, this render should not
// include C, because that update wasn't already committed.
'Committed: BD',
'Committed: BCD',
'Committed: ABCD',
]);
}
expect(root).toMatchRenderedOutput('ABCD');
});
it("base state of update queue is initialized to its fiber's memoized state", async () => {
// This test is very weird because it tests an implementation detail but
// is tested in terms of public APIs. When it was originally written, the
// test failed because the update queue was initialized to the state of
// the alternate fiber.
let app;
class App extends React.Component {
state = {prevProp: 'A', count: 0};
static getDerivedStateFromProps(props, state) {
// Add 100 whenever the label prop changes. The prev label is stored
// in state. If the state is dropped incorrectly, we'll fail to detect
// prop changes.
if (props.prop !== state.prevProp) {
return {
prevProp: props.prop,
count: state.count + 100,
};
}
return null;
}
render() {
app = this;
return this.state.count;
}
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App prop="A" />);
});
expect(root).toMatchRenderedOutput('0');
// Changing the prop causes the count to increase by 100
await act(() => {
root.render(<App prop="B" />);
});
expect(root).toMatchRenderedOutput('100');
// Now increment the count by 1 with a state update. And, in the same
// batch, change the prop back to its original value.
await act(() => {
root.render(<App prop="A" />);
app.setState(state => ({count: state.count + 1}));
});
// There were two total prop changes, plus an increment.
expect(root).toMatchRenderedOutput('201');
});
});
| 27.173807 | 123 | 0.559977 |
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
*/
export * from 'react-client/src/ReactFlightClientConfigNode';
export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigBundlerTurbopack';
export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigBundlerTurbopackServer';
export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigTargetTurbopackServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWithSSR = true;
| 39.5625 | 93 | 0.79321 |
owtf | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
| 20.625 | 50 | 0.726744 |
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';
let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
describe('ReactDOM', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
});
it('should bubble onSubmit', function () {
const container = document.createElement('div');
let count = 0;
let buttonRef;
function Parent() {
return (
<div
onSubmit={event => {
event.preventDefault();
count++;
}}>
<Child />
</div>
);
}
function Child() {
return (
<form>
<input type="submit" ref={button => (buttonRef = button)} />
</form>
);
}
document.body.appendChild(container);
try {
ReactDOM.render(<Parent />, container);
buttonRef.click();
expect(count).toBe(1);
} finally {
document.body.removeChild(container);
}
});
it('allows a DOM element to be used with a string', () => {
const element = React.createElement('div', {className: 'foo'});
const node = ReactTestUtils.renderIntoDocument(element);
expect(node.tagName).toBe('DIV');
});
it('should allow children to be passed as an argument', () => {
const argNode = ReactTestUtils.renderIntoDocument(
React.createElement('div', null, 'child'),
);
expect(argNode.innerHTML).toBe('child');
});
it('should overwrite props.children with children argument', () => {
const conflictNode = ReactTestUtils.renderIntoDocument(
React.createElement('div', {children: 'fakechild'}, 'child'),
);
expect(conflictNode.innerHTML).toBe('child');
});
/**
* We need to make sure that updates occur to the actual node that's in the
* DOM, instead of a stale cache.
*/
it('should purge the DOM cache when removing nodes', () => {
let myDiv = ReactTestUtils.renderIntoDocument(
<div>
<div key="theDog" className="dog" />,
<div key="theBird" className="bird" />
</div>,
);
// Warm the cache with theDog
myDiv = ReactTestUtils.renderIntoDocument(
<div>
<div key="theDog" className="dogbeforedelete" />,
<div key="theBird" className="bird" />,
</div>,
);
// Remove theDog - this should purge the cache
myDiv = ReactTestUtils.renderIntoDocument(
<div>
<div key="theBird" className="bird" />,
</div>,
);
// Now, put theDog back. It's now a different DOM node.
myDiv = ReactTestUtils.renderIntoDocument(
<div>
<div key="theDog" className="dog" />,
<div key="theBird" className="bird" />,
</div>,
);
// Change the className of theDog. It will use the same element
myDiv = ReactTestUtils.renderIntoDocument(
<div>
<div key="theDog" className="bigdog" />,
<div key="theBird" className="bird" />,
</div>,
);
const dog = myDiv.childNodes[0];
expect(dog.className).toBe('bigdog');
});
it('throws in render() if the mount callback is not a function', () => {
function Foo() {
this.a = 1;
this.b = 2;
}
class A extends React.Component {
state = {};
render() {
return <div />;
}
}
const myDiv = document.createElement('div');
expect(() => {
expect(() => {
ReactDOM.render(<A />, myDiv, 'no');
}).toErrorDev(
'render(...): Expected the last optional `callback` argument to be ' +
'a function. Instead received: no.',
);
}).toThrowError(
'Invalid argument passed as callback. Expected a function. Instead ' +
'received: no',
);
expect(() => {
expect(() => {
ReactDOM.render(<A />, myDiv, {foo: 'bar'});
}).toErrorDev(
'render(...): Expected the last optional `callback` argument to be ' +
'a function. Instead received: [object Object].',
);
}).toThrowError(
'Invalid argument passed as callback. Expected a function. Instead ' +
'received: [object Object]',
);
expect(() => {
expect(() => {
ReactDOM.render(<A />, myDiv, new Foo());
}).toErrorDev(
'render(...): Expected the last optional `callback` argument to be ' +
'a function. Instead received: [object Object].',
);
}).toThrowError(
'Invalid argument passed as callback. Expected a function. Instead ' +
'received: [object Object]',
);
});
it('throws in render() if the update callback is not a function', () => {
function Foo() {
this.a = 1;
this.b = 2;
}
class A extends React.Component {
state = {};
render() {
return <div />;
}
}
const myDiv = document.createElement('div');
ReactDOM.render(<A />, myDiv);
expect(() => {
expect(() => {
ReactDOM.render(<A />, myDiv, 'no');
}).toErrorDev(
'render(...): Expected the last optional `callback` argument to be ' +
'a function. Instead received: no.',
);
}).toThrowError(
'Invalid argument passed as callback. Expected a function. Instead ' +
'received: no',
);
ReactDOM.render(<A />, myDiv); // Re-mount
expect(() => {
expect(() => {
ReactDOM.render(<A />, myDiv, {foo: 'bar'});
}).toErrorDev(
'render(...): Expected the last optional `callback` argument to be ' +
'a function. Instead received: [object Object].',
);
}).toThrowError(
'Invalid argument passed as callback. Expected a function. Instead ' +
'received: [object Object]',
);
ReactDOM.render(<A />, myDiv); // Re-mount
expect(() => {
expect(() => {
ReactDOM.render(<A />, myDiv, new Foo());
}).toErrorDev(
'render(...): Expected the last optional `callback` argument to be ' +
'a function. Instead received: [object Object].',
);
}).toThrowError(
'Invalid argument passed as callback. Expected a function. Instead ' +
'received: [object Object]',
);
});
it('preserves focus', () => {
let input;
let input2;
class A extends React.Component {
render() {
return (
<div>
<input id="one" ref={r => (input = input || r)} />
{this.props.showTwo && (
<input id="two" ref={r => (input2 = input2 || r)} />
)}
</div>
);
}
componentDidUpdate() {
// Focus should have been restored to the original input
expect(document.activeElement.id).toBe('one');
input2.focus();
expect(document.activeElement.id).toBe('two');
log.push('input2 focused');
}
}
const log = [];
const container = document.createElement('div');
document.body.appendChild(container);
try {
ReactDOM.render(<A showTwo={false} />, container);
input.focus();
// When the second input is added, let's simulate losing focus, which is
// something that could happen when manipulating DOM nodes (but is hard to
// deterministically force without relying intensely on React DOM
// implementation details)
const div = container.firstChild;
['appendChild', 'insertBefore'].forEach(name => {
const mutator = div[name];
div[name] = function () {
if (input) {
input.blur();
expect(document.activeElement.tagName).toBe('BODY');
log.push('input2 inserted');
}
return mutator.apply(this, arguments);
};
});
expect(document.activeElement.id).toBe('one');
ReactDOM.render(<A showTwo={true} />, container);
// input2 gets added, which causes input to get blurred. Then
// componentDidUpdate focuses input2 and that should make it down to here,
// not get overwritten by focus restoration.
expect(document.activeElement.id).toBe('two');
expect(log).toEqual(['input2 inserted', 'input2 focused']);
} finally {
document.body.removeChild(container);
}
});
it('calls focus() on autoFocus elements after they have been mounted to the DOM', () => {
const originalFocus = HTMLElement.prototype.focus;
try {
let focusedElement;
let inputFocusedAfterMount = false;
// This test needs to determine that focus is called after mount.
// Can't check document.activeElement because PhantomJS is too permissive;
// It doesn't require element to be in the DOM to be focused.
HTMLElement.prototype.focus = function () {
focusedElement = this;
inputFocusedAfterMount = !!this.parentNode;
};
const container = document.createElement('div');
document.body.appendChild(container);
ReactDOM.render(
<div>
<h1>Auto-focus Test</h1>
<input autoFocus={true} />
<p>The above input should be focused after mount.</p>
</div>,
container,
);
expect(inputFocusedAfterMount).toBe(true);
expect(focusedElement.tagName).toBe('INPUT');
} finally {
HTMLElement.prototype.focus = originalFocus;
}
});
it("shouldn't fire duplicate event handler while handling other nested dispatch", () => {
const actual = [];
class Wrapper extends React.Component {
componentDidMount() {
this.ref1.click();
}
render() {
return (
<div>
<div
onClick={() => {
actual.push('1st node clicked');
this.ref2.click();
}}
ref={ref => (this.ref1 = ref)}
/>
<div
onClick={ref => {
actual.push("2nd node clicked imperatively from 1st's handler");
}}
ref={ref => (this.ref2 = ref)}
/>
</div>
);
}
}
const container = document.createElement('div');
document.body.appendChild(container);
try {
ReactDOM.render(<Wrapper />, container);
const expected = [
'1st node clicked',
"2nd node clicked imperatively from 1st's handler",
];
expect(actual).toEqual(expected);
} finally {
document.body.removeChild(container);
}
});
it('should not crash with devtools installed', () => {
try {
global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
inject: function () {},
onCommitFiberRoot: function () {},
onCommitFiberUnmount: function () {},
supportsFiber: true,
};
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
class Component extends React.Component {
render() {
return <div />;
}
}
ReactDOM.render(<Component />, document.createElement('container'));
} finally {
delete global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
}
});
it('should not crash calling findDOMNode inside a function component', () => {
const container = document.createElement('div');
class Component extends React.Component {
render() {
return <div />;
}
}
const instance = ReactTestUtils.renderIntoDocument(<Component />);
const App = () => {
ReactDOM.findDOMNode(instance);
return <div />;
};
if (__DEV__) {
ReactDOM.render(<App />, container);
}
});
it('reports stacks with re-entrant renderToString() calls on the client', () => {
function Child2(props) {
return <span ariaTypo3="no">{props.children}</span>;
}
function App2() {
return (
<Child2>
{ReactDOMServer.renderToString(<blink ariaTypo2="no" />)}
</Child2>
);
}
function Child() {
return (
<span ariaTypo4="no">{ReactDOMServer.renderToString(<App2 />)}</span>
);
}
function ServerEntry() {
return ReactDOMServer.renderToString(<Child />);
}
function App() {
return (
<div>
<span ariaTypo="no" />
<ServerEntry />
<font ariaTypo5="no" />
</div>
);
}
const container = document.createElement('div');
expect(() => ReactDOM.render(<App />, container)).toErrorDev([
// ReactDOM(App > div > span)
'Invalid ARIA attribute `ariaTypo`. ARIA attributes follow the pattern aria-* and must be lowercase.\n' +
' in span (at **)\n' +
' in div (at **)\n' +
' in App (at **)',
// ReactDOM(App > div > ServerEntry) >>> ReactDOMServer(Child) >>> ReactDOMServer(App2) >>> ReactDOMServer(blink)
'Invalid ARIA attribute `ariaTypo2`. ARIA attributes follow the pattern aria-* and must be lowercase.\n' +
' in blink (at **)',
// ReactDOM(App > div > ServerEntry) >>> ReactDOMServer(Child) >>> ReactDOMServer(App2 > Child2 > span)
'Invalid ARIA attribute `ariaTypo3`. ARIA attributes follow the pattern aria-* and must be lowercase.\n' +
' in span (at **)\n' +
' in Child2 (at **)\n' +
' in App2 (at **)',
// ReactDOM(App > div > ServerEntry) >>> ReactDOMServer(Child > span)
'Invalid ARIA attribute `ariaTypo4`. ARIA attributes follow the pattern aria-* and must be lowercase.\n' +
' in span (at **)\n' +
' in Child (at **)',
// ReactDOM(App > div > font)
'Invalid ARIA attribute `ariaTypo5`. ARIA attributes follow the pattern aria-* and must be lowercase.\n' +
' in font (at **)\n' +
' in div (at **)\n' +
' in App (at **)',
]);
});
});
| 28.694268 | 119 | 0.562603 |
PenetrationTestingScripts | module.exports = require('./dist/standalone');
| 23 | 46 | 0.723404 |
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 interface Destination {
push(chunk: string | null): boolean;
destroy(error: Error): mixed;
}
export opaque type PrecomputedChunk = string;
export opaque type Chunk = string;
export opaque type BinaryChunk = string;
export function scheduleWork(callback: () => void) {
callback();
}
export function flushBuffered(destination: Destination) {}
export function beginWriting(destination: Destination) {}
export function writeChunk(
destination: Destination,
chunk: Chunk | PrecomputedChunk | BinaryChunk,
): void {
writeChunkAndReturn(destination, chunk);
}
export function writeChunkAndReturn(
destination: Destination,
chunk: Chunk | PrecomputedChunk | BinaryChunk,
): boolean {
return destination.push(chunk);
}
export function completeWriting(destination: Destination) {}
export function close(destination: Destination) {
destination.push(null);
}
export function stringToChunk(content: string): Chunk {
return content;
}
export function stringToPrecomputedChunk(content: string): PrecomputedChunk {
return content;
}
export function typedArrayToBinaryChunk(
content: $ArrayBufferView,
): BinaryChunk {
throw new Error('Not implemented.');
}
export function clonePrecomputedChunk(
chunk: PrecomputedChunk,
): PrecomputedChunk {
return chunk;
}
export function byteLengthOfChunk(chunk: Chunk | PrecomputedChunk): number {
throw new Error('Not implemented.');
}
export function byteLengthOfBinaryChunk(chunk: BinaryChunk): number {
throw new Error('Not implemented.');
}
export function closeWithError(destination: Destination, error: mixed): void {
// $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types.
destination.destroy(error);
}
export {createFastHashJS as createFastHash} from 'react-server/src/createFastHashJS';
| 24.049383 | 99 | 0.760848 |
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 {
TransitionTracingCallbacks,
Fiber,
FiberRoot,
} from './ReactInternalTypes';
import type {OffscreenInstance} from './ReactFiberActivityComponent';
import type {StackCursor} from './ReactFiberStack';
import {enableTransitionTracing} from 'shared/ReactFeatureFlags';
import {createCursor, push, pop} from './ReactFiberStack';
import {getWorkInProgressTransitions} from './ReactFiberWorkLoop';
export type SuspenseInfo = {name: string | null};
export type PendingTransitionCallbacks = {
transitionStart: Array<Transition> | null,
transitionProgress: Map<Transition, PendingBoundaries> | null,
transitionComplete: Array<Transition> | null,
markerProgress: Map<
string,
{pendingBoundaries: PendingBoundaries, transitions: Set<Transition>},
> | null,
markerIncomplete: Map<
string,
{aborts: Array<TransitionAbort>, transitions: Set<Transition>},
> | null,
markerComplete: Map<string, Set<Transition>> | null,
};
export type Transition = {
name: string,
startTime: number,
};
export type BatchConfigTransition = {
name?: string,
startTime?: number,
_updatedFibers?: Set<Fiber>,
};
// TODO: Is there a way to not include the tag or name here?
export type TracingMarkerInstance = {
tag?: TracingMarkerTag,
transitions: Set<Transition> | null,
pendingBoundaries: PendingBoundaries | null,
aborts: Array<TransitionAbort> | null,
name: string | null,
};
export type TransitionAbort = {
reason: 'error' | 'unknown' | 'marker' | 'suspense',
name?: string | null,
};
export const TransitionRoot = 0;
export const TransitionTracingMarker = 1;
export type TracingMarkerTag = 0 | 1;
export type PendingBoundaries = Map<OffscreenInstance, SuspenseInfo>;
export function processTransitionCallbacks(
pendingTransitions: PendingTransitionCallbacks,
endTime: number,
callbacks: TransitionTracingCallbacks,
): void {
if (enableTransitionTracing) {
if (pendingTransitions !== null) {
const transitionStart = pendingTransitions.transitionStart;
const onTransitionStart = callbacks.onTransitionStart;
if (transitionStart !== null && onTransitionStart != null) {
transitionStart.forEach(transition =>
onTransitionStart(transition.name, transition.startTime),
);
}
const markerProgress = pendingTransitions.markerProgress;
const onMarkerProgress = callbacks.onMarkerProgress;
if (onMarkerProgress != null && markerProgress !== null) {
markerProgress.forEach((markerInstance, markerName) => {
if (markerInstance.transitions !== null) {
// TODO: Clone the suspense object so users can't modify it
const pending =
markerInstance.pendingBoundaries !== null
? Array.from(markerInstance.pendingBoundaries.values())
: [];
markerInstance.transitions.forEach(transition => {
onMarkerProgress(
transition.name,
markerName,
transition.startTime,
endTime,
pending,
);
});
}
});
}
const markerComplete = pendingTransitions.markerComplete;
const onMarkerComplete = callbacks.onMarkerComplete;
if (markerComplete !== null && onMarkerComplete != null) {
markerComplete.forEach((transitions, markerName) => {
transitions.forEach(transition => {
onMarkerComplete(
transition.name,
markerName,
transition.startTime,
endTime,
);
});
});
}
const markerIncomplete = pendingTransitions.markerIncomplete;
const onMarkerIncomplete = callbacks.onMarkerIncomplete;
if (onMarkerIncomplete != null && markerIncomplete !== null) {
markerIncomplete.forEach(({transitions, aborts}, markerName) => {
transitions.forEach(transition => {
const filteredAborts = [];
aborts.forEach(abort => {
switch (abort.reason) {
case 'marker': {
filteredAborts.push({
type: 'marker',
name: abort.name,
endTime,
});
break;
}
case 'suspense': {
filteredAborts.push({
type: 'suspense',
name: abort.name,
endTime,
});
break;
}
default: {
break;
}
}
});
if (filteredAborts.length > 0) {
onMarkerIncomplete(
transition.name,
markerName,
transition.startTime,
filteredAborts,
);
}
});
});
}
const transitionProgress = pendingTransitions.transitionProgress;
const onTransitionProgress = callbacks.onTransitionProgress;
if (onTransitionProgress != null && transitionProgress !== null) {
transitionProgress.forEach((pending, transition) => {
onTransitionProgress(
transition.name,
transition.startTime,
endTime,
Array.from(pending.values()),
);
});
}
const transitionComplete = pendingTransitions.transitionComplete;
const onTransitionComplete = callbacks.onTransitionComplete;
if (transitionComplete !== null && onTransitionComplete != null) {
transitionComplete.forEach(transition =>
onTransitionComplete(transition.name, transition.startTime, endTime),
);
}
}
}
}
// For every tracing marker, store a pointer to it. We will later access it
// to get the set of suspense boundaries that need to resolve before the
// tracing marker can be logged as complete
// This code lives separate from the ReactFiberTransition code because
// we push and pop on the tracing marker, not the suspense boundary
const markerInstanceStack: StackCursor<Array<TracingMarkerInstance> | null> =
createCursor(null);
export function pushRootMarkerInstance(workInProgress: Fiber): void {
if (enableTransitionTracing) {
// On the root, every transition gets mapped to it's own map of
// suspense boundaries. The transition is marked as complete when
// the suspense boundaries map is empty. We do this because every
// transition completes at different times and depends on different
// suspense boundaries to complete. We store all the transitions
// along with its map of suspense boundaries in the root incomplete
// transitions map. Each entry in this map functions like a tracing
// marker does, so we can push it onto the marker instance stack
const transitions = getWorkInProgressTransitions();
const root: FiberRoot = workInProgress.stateNode;
if (transitions !== null) {
transitions.forEach(transition => {
if (!root.incompleteTransitions.has(transition)) {
const markerInstance: TracingMarkerInstance = {
tag: TransitionRoot,
transitions: new Set([transition]),
pendingBoundaries: null,
aborts: null,
name: null,
};
root.incompleteTransitions.set(transition, markerInstance);
}
});
}
const markerInstances = [];
// For ever transition on the suspense boundary, we push the transition
// along with its map of pending suspense boundaries onto the marker
// instance stack.
root.incompleteTransitions.forEach(markerInstance => {
markerInstances.push(markerInstance);
});
push(markerInstanceStack, markerInstances, workInProgress);
}
}
export function popRootMarkerInstance(workInProgress: Fiber) {
if (enableTransitionTracing) {
pop(markerInstanceStack, workInProgress);
}
}
export function pushMarkerInstance(
workInProgress: Fiber,
markerInstance: TracingMarkerInstance,
): void {
if (enableTransitionTracing) {
if (markerInstanceStack.current === null) {
push(markerInstanceStack, [markerInstance], workInProgress);
} else {
push(
markerInstanceStack,
markerInstanceStack.current.concat(markerInstance),
workInProgress,
);
}
}
}
export function popMarkerInstance(workInProgress: Fiber): void {
if (enableTransitionTracing) {
pop(markerInstanceStack, workInProgress);
}
}
export function getMarkerInstances(): Array<TracingMarkerInstance> | null {
if (enableTransitionTracing) {
return markerInstanceStack.current;
}
return null;
}
| 31.99262 | 79 | 0.640268 |
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 {createContext, useContext} from 'react';
const A = createContext(1);
const B = createContext(2);
export function Component() {
const a = useContext(A);
const b = useContext(B);
// prettier-ignore
const c = useContext(A), d = useContext(B); // eslint-disable-line one-var
return a + b + c + d;
}
| 20.75 | 76 | 0.673704 |