prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
const path = require('path');
const rimraf = require('rimraf');
const webpack = require('webpack');
const isProduction = ... | test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
},
(err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details); | -map' : 'cheap-module-source-map',
entry: [path.resolve(__dirname, '../src/index.js')],
output: {
path: path.resolve(__dirname, '../build'),
filename: 'main.js',
},
module: {
rules: [
{
| {
"filepath": "fixtures/fizz/scripts/build.js",
"language": "javascript",
"file_size": 1316,
"cut_index": 524,
"middle_length": 229
} |
-js/es6/symbol';
import 'core-js/es6/promise';
import 'core-js/es6/set';
import 'core-js/es6/map';
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes... | ionFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTime | nFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x] + 'CancelAnimationFrame'] ||
window[vendors[x] + 'CancelRequestAnimat | {
"filepath": "fixtures/dom/src/polyfills.js",
"language": "javascript",
"file_size": 1279,
"cut_index": 524,
"middle_length": 229
} |
w.React;
export default class MediaEvents extends React.Component {
state = {
playbackRate: 2,
events: {
onCanPlay: false,
onCanPlayThrough: false,
onDurationChange: false,
onEmptied: false,
onEnded: false,
onError: false,
onLoadedData: false,
onLoadedMetadata:... | = el => {
this.video = el;
};
eventDidFire(event) {
this.setState({
events: Object.assign({}, this.state.events, {[event]: true}),
});
}
getProgress() {
const events = Object.keys(this.state.events);
const total = events | false,
onSeeking: false,
onSuspend: false,
onTimeUpdate: false,
onVolumeChange: false,
onWaiting: false,
},
};
updatePlaybackRate = () => {
this.video.playbackRate = 2;
};
setVideo | {
"filepath": "fixtures/dom/src/components/fixtures/media-events/index.js",
"language": "javascript",
"file_size": 3250,
"cut_index": 614,
"middle_length": 229
} |
;
}
declare class MediaList {
@@iterator(): Iterator<string>;
mediaText: string;
length: number;
item(index: number): ?string;
deleteMedium(oldMedium: string): void;
appendMedium(newMedium: string): void;
[index: number]: string;
}
declare class CSSStyleSheet extends StyleSheet {
+cssRules: CSSRuleLis... | conditionText: string;
}
declare class CSSMediaRule extends CSSConditionRule {
+media: MediaList;
}
declare class CSSStyleRule extends CSSRule {
selectorText: string;
+style: CSSStyleDeclaration;
}
declare class CSSSupportsRule extends CSSConditi | oid;
}
declare class CSSGroupingRule extends CSSRule {
+cssRules: CSSRuleList;
deleteRule(index: number): void;
insertRule(rule: string, index: number): number;
}
declare class CSSConditionRule extends CSSGroupingRule {
| {
"filepath": "flow-typed/environments/cssom.js",
"language": "javascript",
"file_size": 10446,
"cut_index": 921,
"middle_length": 229
} |
entHandler, ...}
| WheelEventHandler;
type AbortProgressEventHandler = (event: ProgressEvent) => mixed;
type AbortProgressEventListener =
| {handleEvent: AbortProgressEventHandler, ...}
| AbortProgressEventHandler;
type ProgressEventHandler = (event: ProgressEvent) => mixed;
type ProgressEventListener =
| {hand... |
type AnimationEventListener =
| {handleEvent: AnimationEventHandler, ...}
| AnimationEventHandler;
type ClipboardEventHandler = (event: ClipboardEvent) => mixed;
type ClipboardEventListener =
| {handleEvent: ClipboardEventHandler, ...}
| Clipboard | ntHandler;
type PointerEventHandler = (event: PointerEvent) => mixed;
type PointerEventListener =
| {handleEvent: PointerEventHandler, ...}
| PointerEventHandler;
type AnimationEventHandler = (event: AnimationEvent) => mixed; | {
"filepath": "flow-typed/environments/dom.js",
"language": "javascript",
"file_size": 112294,
"cut_index": 3790,
"middle_length": 229
} |
b: number,
c: number,
d: number,
e: number,
f: number,
|}
| {|
m11: number,
m12: number,
m21: number,
m22: number,
m41: number,
m42: number,
|};
type DOMMatrixInit =
| {|
...DOMMatrix2DInit,
is2D: true,
|}
| {|
...DOMM... | e DOMRectInit = {|
height: number,
width: number,
x: number,
y: number,
|};
declare class DOMMatrix extends DOMMatrixReadOnly {
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
m11: number;
m12: number;
m13: numb | 3: number,
m44: number,
|};
type DOMPointInit = {|
w: number,
x: number,
y: number,
z: number,
|};
type DOMQuadInit = {|
p1: DOMPointInit,
p2: DOMPointInit,
p3: DOMPointInit,
p4: DOMPointInit,
|};
typ | {
"filepath": "flow-typed/environments/geometry.js",
"language": "javascript",
"file_size": 5688,
"cut_index": 716,
"middle_length": 229
} |
@iterator(): Iterator<string>;
+[key: number]: string;
+length: number;
item(number): string | null;
contains(string): boolean;
}
declare type ElementDefinitionOptions = {|extends?: string|};
declare interface CustomElementRegistry {
define(
name: string,
ctor: Class<Element>,
options?: ElementD... | onmessage: MessageEventListener;
onopen: () => void;
close: () => void;
}
// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
declare class ErrorEvent extends Event {
constructor(
type: string,
eventInitDict?: | structor(
url: string,
configuration?: {withCredentials: boolean, ...}
): void;
+CLOSED: 2;
+CONNECTING: 0;
+OPEN: 1;
+readyState: 0 | 1 | 2;
+url: string;
+withCredentials: boolean;
onerror: () => void;
| {
"filepath": "flow-typed/environments/html.js",
"language": "javascript",
"file_size": 40609,
"cut_index": 2151,
"middle_length": 229
} |
r$Encoding, start?: number, end?: number): string;
values(): Iterator<number>;
write(
string: string,
offset?: number,
length?: number,
encoding?: buffer$Encoding
): number;
writeDoubleBE(value: number, offset?: number, noAssert?: boolean): number;
writeDoubleLE(value: number, offset?: number,... | 2LE(value: number, offset?: number, noAssert?: boolean): number;
writeInt8(value: number, offset?: number, noAssert?: boolean): number;
writeIntBE(
value: number,
offset: number,
byteLength: number,
noAssert?: boolean
): number;
wri | 16BE(value: number, offset?: number, noAssert?: boolean): number;
writeInt16LE(value: number, offset?: number, noAssert?: boolean): number;
writeInt32BE(value: number, offset?: number, noAssert?: boolean): number;
writeInt3 | {
"filepath": "flow-typed/environments/node.js",
"language": "javascript",
"file_size": 123344,
"cut_index": 3790,
"middle_length": 229
} |
tate = 'hidden' | 'visible' | 'prerender' | 'unloaded';
declare class WindowClient extends Client {
visibilityState: VisibilityState;
focused: boolean;
focus(): Promise<WindowClient>;
navigate(url: string): Promise<WindowClient>;
}
declare class Client {
id: string;
reserved: boolean;
url: string;
fra... | d;
+notification: Notification;
+action: string;
}
type ForeignFetchOptions = {
scopes: Iterator<string>,
origins: Iterator<string>,
...
};
declare class InstallEvent extends ExtendableEvent {
registerForeignFetch(options: ForeignFetchOptions | ficationEvent$Init = {
...Event$Init,
notification: Notification,
action?: string,
...
};
declare class NotificationEvent extends ExtendableEvent {
constructor(type: string, eventInitDict?: NotificationEvent$Init): voi | {
"filepath": "flow-typed/environments/serviceworkers.js",
"language": "javascript",
"file_size": 6502,
"cut_index": 716,
"middle_length": 229
} |
ow_>=v0.261.x
type TextEncodeOptions = {options?: boolean, ...};
declare class ReadableStreamController {
constructor(
stream: ReadableStream,
underlyingSource: UnderlyingSource,
size: number,
highWaterMark: number
): void;
desiredSize: number;
close(): void;
enqueue(chunk: any): void;
e... |
highWaterMark: number
): void;
byobRequest: ReadableStreamBYOBRequest;
}
declare class ReadableStreamReader {
constructor(stream: ReadableStream): void;
closed: boolean;
cancel(reason: string): void;
read(): Promise<{
value: ?any,
| en: number): ?any;
respondWithNewView(view: $TypedArray): ?any;
}
declare class ReadableByteStreamController extends ReadableStreamController {
constructor(
stream: ReadableStream,
underlyingSource: UnderlyingSource, | {
"filepath": "flow-typed/environments/streams.js",
"language": "javascript",
"file_size": 3131,
"cut_index": 614,
"middle_length": 229
} |
ions/flow_>=v0.261.x
// https://www.w3.org/TR/web-animations-1/
type AnimationPlayState = 'idle' | 'running' | 'paused' | 'finished';
type AnimationReplaceState = 'active' | 'removed' | 'persisted';
type CompositeOperation = 'replace' | 'add' | 'accumulate';
type CompositeOperationOrAuto = 'replace' | 'add' | 'acc... | edKeyframe = {|
composite: CompositeOperationOrAuto,
computedOffset: number,
easing: string,
offset: number | null,
|};
type BaseKeyframe = {|
composite: CompositeOperationOrAuto,
easing: string,
offset: number | null,
|};
type BaseProperty | e PlaybackDirection =
| 'normal'
| 'reverse'
| 'alternate'
| 'alternate-reverse';
type AnimationPlaybackEvent$Init = Event$Init & {
currentTime?: number | null,
timelineTime?: number | null,
...
};
type BaseComput | {
"filepath": "flow-typed/environments/web-animations.js",
"language": "javascript",
"file_size": 4790,
"cut_index": 614,
"middle_length": 229
} |
d signature: 132e48034ef4756600e1d98681a166b5
// flow-typed version: c6154227d1/error-stack-parser_v2.x.x/flow_>=v0.104.x
declare module 'error-stack-parser' {
declare interface StackFrame {
constructor(object: StackFrame): StackFrame;
isConstructor?: boolean;
getIsConstructor(): boolean;
setIsConst... | fileName?: string;
getFileName(): string;
setFileName(): void;
functionName?: string;
getFunctionName(): string;
setFunctionName(): void;
source?: string;
getSource(): string;
setSource(): void;
args?: any[];
|
getIsTopLevel(): boolean;
setIsTopLevel(): void;
columnNumber?: number;
getColumnNumber(): number;
setColumnNumber(): void;
lineNumber?: number;
getLineNumber(): number;
setLineNumber(): void;
| {
"filepath": "flow-typed/npm/error-stack-parser_v2.x.x.js",
"language": "javascript",
"file_size": 1298,
"cut_index": 524,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Our philosophy for linting is that lints should be very high-signal:
* - Error, don't warn. If it's worth mentioning it's worth fixing.
* - Enable rules that consistently identify real problems. If we frequently would hav... | ue
*/
"prefer-const": "off",
// Not valuable enough to enable
"no-useless-escape": "off",
/*
* There are valid use cases for loops with constant conditions where the body contains the
* break
*/
"no-constant-condit |
module.exports = {
extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
rules: {
/*
* We prefer using const where variables are not reassigned, but occassional mistakes
* aren't a major iss | {
"filepath": "compiler/.eslintrc.js",
"language": "javascript",
"file_size": 3568,
"cut_index": 614,
"middle_length": 229
} |
;
const fs = require('fs');
const HermesParser = require('hermes-parser');
const BabelParser = require('@babel/parser');
const BabelCore = require('@babel/core');
const invariant = require('invariant');
const {argv, stdin} = require('process');
const prettier = require('prettier');
const {JSXText} = require('hermes-pa... | ],
sourceType: 'module',
});
}
const result = BabelCore.transformFromAstSync(ast, text, {
ast: false,
filename: file,
highlightCode: false,
retainLines: true,
plugins: [[AnonymizePlugin]],
sourceType: 'module',
con | 'all',
sourceFilename: file,
sourceType: 'module',
enableExperimentalComponentSyntax: true,
});
} else {
ast = BabelParser.parse(text, {
sourceFilename: file,
plugins: ['typescript', 'jsx' | {
"filepath": "compiler/scripts/anonymize.js",
"language": "javascript",
"file_size": 5949,
"cut_index": 716,
"middle_length": 229
} |
const ReactCompiler = require('../packages/babel-plugin-react-compiler/dist');
const combinedRules = [
{
name: 'rules-of-hooks',
recommended: true,
description:
'Validates that components and hooks follow the [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks)',
},
{
name: 'e... | ilter(
ruleConfig => ruleConfig.rule.recommended && ruleConfig.severity !== 'Off'
)
.map(ruleConfig => {
return `
## \`react-hooks/${ruleConfig.rule.name}\`
${ruleConfig.rule.description}
`.trim();
})
.join('\n\n');
console.log(printe | enced variables in their dependency array. Referencing a value without including it in the ' +
'dependency array can lead to stale UI or callbacks.',
},
...ReactCompiler.LintRules,
];
const printed = combinedRules
.f | {
"filepath": "compiler/scripts/build-eslint-docs.js",
"language": "javascript",
"file_size": 1001,
"cut_index": 512,
"middle_length": 229
} |
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 fs = require('fs');
const glob = require('glob');
const META_COPYRIGHT_COMMENT_BLOCK =
`/**
* Copyright (c) Meta Platforms, Inc.... | => {
try {
const result = processFile(file);
if (result != null) {
updatedFiles.set(file, result);
}
} catch (e) {
console.error(e);
hasErrors = true;
}
});
if (hasErrors) {
console.error('Update failed');
process.exit( | ('**/*.{js,ts,tsx,jsx,rs}', {
ignore: [
'**/dist/**',
'**/node_modules/**',
'**/tests/fixtures/**',
'**/__tests__/fixtures/**',
],
});
const updatedFiles = new Map();
let hasErrors = false;
files.forEach(file | {
"filepath": "compiler/scripts/copyright.js",
"language": "javascript",
"file_size": 1585,
"cut_index": 537,
"middle_length": 229
} |
e.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const {execSync} = require('child_process');
const yargs = require('yargs/yargs');
const {hideBin} = require('yargs/helpers');
// Constants
const COMPILER_ROOT = path.resolve(__dirname, '..');
const ENVIRONMENT_TS_PATH = path.join(
COMPIL... | <flag-name>', 'Enable a feature flag by default', yargs => {
yargs.positional('flag-name', {
describe: 'Name of the feature flag to enable',
type: 'string',
});
})
.example(
'$0 validateExhaustiveMemoizationDepend | piler'
);
const FIXTURE_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
/**
* Parse command line arguments
*/
function parseArgs() {
const argv = yargs(hideBin(process.argv))
.usage('Usage: $0 <flag-name>')
.command('$0 | {
"filepath": "compiler/scripts/enable-feature-flag.js",
"language": "javascript",
"file_size": 9182,
"cut_index": 716,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* INSTALLATION:
* - `$ npm install octokit
* - Get a token from https://github.com/settings/tokens for use in the command below,
* set the token value as the GITHUB_AUTH_TOKEN environment variable
*
* USAGE:
* - $ ... | st(
'GET /repos/{owner}/{repo}/pulls/{pull_number}',
{
owner: OWNER,
repo: REPO,
pull_number: pullNumber,
headers: {
'X-GitHub-Api-Version': '2022-11-28',
},
}
);
return {body: response.data.body, title | s = require('fs');
const OWNER = 'facebook';
const REPO = 'react-forget';
const octokit = new Octokit({auth: process.env.GITHUB_AUTH_TOKEN});
const fetchPullRequest = async pullNumber => {
const response = await octokit.reque | {
"filepath": "compiler/scripts/update-commit-message.js",
"language": "javascript",
"file_size": 3592,
"cut_index": 614,
"middle_length": 229
} |
e.
*/
'use strict';
const ora = require('ora');
const path = require('path');
const yargs = require('yargs');
const {hashElement} = require('folder-hash');
const promptForOTP = require('./prompt-for-otp');
const {PUBLISHABLE_PACKAGES} = require('./shared/packages');
const {
execHelper,
getDateStringForCommit,
... | d double check the contents of the files that
* will be pushed to npm.
*
* If it looks good, you can run `yarn npm:publish --for-real` to really publish to npm. You must
* have 2FA enabled first and the script will prompt you to enter a 2FA code before | ABLE_PACKAGES to npm. By default, this runs in tarball mode, meaning
* the script will only print out what the contents of the files included in the npm tarball would
* be.
*
* Please run this first (ie `yarn npm:publish`) an | {
"filepath": "compiler/scripts/release/publish.js",
"language": "javascript",
"file_size": 7547,
"cut_index": 716,
"middle_length": 229
} |
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 cp = require('child_process');
const util = require('util');
function execHelper(command, options, streamStdout = false) {
re... | nst spawnHelper = util.promisify(_spawn);
async function getDateStringForCommit(commit) {
let dateString = await execHelper(
`git show -s --no-show-signature --format=%cd --date=format:%Y%m%d ${commit}`
);
// On CI environment, this string is w | proc.stdout.pipe(process.stdout);
}
});
}
function _spawn(command, args, options, cb) {
const child = cp.spawn(command, args, options);
child.on('close', exitCode => {
cb(null, exitCode);
});
return child;
}
co | {
"filepath": "compiler/scripts/release/shared/utils.js",
"language": "javascript",
"file_size": 1212,
"cut_index": 518,
"middle_length": 229
} |
iates.
*
* 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 {tests} = require('./eslint-plugin-react-hooks-test-cases');
const {
runBabelPluginReactCompiler,
} = require('../dist/Babel/RunReactCompilerBabelPlugin');
... | ttier.resolveConfig.sync(FIXTURES_DIR, {
config: prettierConfigPath,
});
const fixtures = [];
for (const test of tests.valid) {
fixtures.push({code: test.code, valid: true});
}
for (const test of tests.invalid) {
fixtures.push({code: test.code, vali | const {createHash} = require('crypto');
const {create} = require('domain');
const FIXTURES_DIR = path.join(
process.cwd(),
'src',
'__tests__',
'fixtures',
'compiler',
'rules-of-hooks'
);
const PRETTIER_OPTIONS = pre | {
"filepath": "compiler/packages/babel-plugin-react-compiler/scripts/build-react-hooks-fixures.js",
"language": "javascript",
"file_size": 2685,
"cut_index": 563,
"middle_length": 229
} |
useHook();
}
`,
},
{
code: normalizeIndent`
// Valid because components can use hooks.
function createComponentWithHook() {
return function ComponentWithHook() {
useHook();
};
}
`,
},
{
code: normalizeIndent`
... | n call functions.
function ComponentWithNormalFunction() {
doSomething();
}
`,
},
{
code: normalizeIndent`
// Valid because functions can call functions.
function normalFunctionWithNormalFunctio | s can use hooks.
function createHook() {
return function useHookWithHook() {
useHook();
}
}
`,
},
{
code: normalizeIndent`
// Valid because components ca | {
"filepath": "compiler/packages/babel-plugin-react-compiler/scripts/eslint-plugin-react-hooks-test-cases.js",
"language": "javascript",
"file_size": 26931,
"cut_index": 1331,
"middle_length": 229
} |
* 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.
*/
module.exports = function makeE2EConfig(displayName, useForget) {
return {
displayName,
testEnvironment: 'jsdom',
roo... | est/snapshot-resolver-with-forget.js'
: '<rootDir>/../scripts/jest/snapshot-resolver-no-forget.js',
transform: {
'\\.[tj]sx?$': useForget
? '<rootDir>/../scripts/jest/transform-with-forget'
: '<rootDir>/../scripts/jest/tran | ap$' : '.*\\.with-forget\\.snap$',
// ignore snapshots from the main project
'.*\\.ts\\.snap$',
],
globals: {
__FORGET__: useForget,
},
snapshotResolver: useForget
? '<rootDir>/../scripts/j | {
"filepath": "compiler/packages/babel-plugin-react-compiler/scripts/jest/makeE2EConfig.js",
"language": "javascript",
"file_size": 1082,
"cut_index": 515,
"middle_length": 229
} |
ezeFunctionExpressions:false
import {
Stringify,
mutate,
identity,
setPropertyByKey,
shallowCopy,
} from 'shared-runtime';
/**
* Function expression version of `aliased-nested-scope-truncated-dep`.
*
* In this fixture, the output would be invalid if propagateScopeDeps did not
* avoid adding MemberExpressi... | ction expression creation until its
* earliest potential invocation
* (2) it's invalid to eagerly evaluate function expression dependencies during
* their respective mutable ranges.
*/
function Component({prop}) {
let obj = shallowCopy(prop) | tput regardless of MemberExpression dependency truncation.
*
* Note while other expressions evaluate inline, function expressions *always*
* represent deferred evaluation. This means that
* (1) it's always safe to reorder fun | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/aliased-nested-scope-fn-expr.tsx",
"language": "tsx",
"file_size": 1607,
"cut_index": 537,
"middle_length": 229
} |
;
/**
* This fixture is similar to `bug-aliased-capture-aliased-mutate` and
* `nonmutating-capture-in-unsplittable-memo-block`, but with a focus on
* dependency extraction.
*
* NOTE: this fixture is currently valid, but will break with optimizations:
* - Scope and mutable-range based reordering may move the arra... | scope block creation, HIR looks like this:
* //
* // $1 is unscoped as obj's mutable range will be
* // extended in a later pass
* //
* $1 = LoadLocal obj@0[0:12]
* $2 = PropertyLoad $1.id
* //
* // $3 gets assigned a scope as Array | d
* output -- it may compare the array's contents / dependencies too early.
* - Runtime validation for immutable values will break if `mutate` does
* interior mutation of the value captured into the array.
*
* Before | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/aliased-nested-scope-truncated-dep.tsx",
"language": "tsx",
"file_size": 3399,
"cut_index": 614,
"middle_length": 229
} |
tity, makeArray, mutate} from 'shared-runtime';
/**
* Here, identity('foo') is an immutable allocating instruction.
* `arr` is a mutable value whose mutable range ends at `arr.map`.
*
* The previous (reactive function) version of alignScopesToBlocks set the range of
* both scopes to end at value blocks within the... | ay<any>({a: 2}, 2, []);
return cond1 ? (
<>
<div>{identity('foo')}</div>
<Stringify value={cond2 ? arr.map(mutate) : null} />
</>
) : null;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{cond1: true, cond2: true}],
} | function Foo({cond1, cond2}) {
const arr = makeArr | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-within-nested-valueblock-in-array.tsx",
"language": "tsx",
"file_size": 845,
"cut_index": 535,
"middle_length": 52
} |
import {useEffect, useState} from 'react';
let someGlobal = {value: null};
function Component() {
const [state, setState] = useState(someGlobal);
// NOTE: if we initialize to eg null or a local, then it won't be a definitively global
// mutation below when we modify `y`. The point of this is example is that if... | a rule of react violation.
*/
useEffect(() => {
y.value = 'hello';
});
useEffect(() => {
setState(someGlobal.value);
}, [someGlobal]);
return <div>{String(state)}</div>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
param | t is not a context variable.
const y = x;
/**
* Note that this fixture currently produces a stale effect closure if `y = x
* = someGlobal` changes between renders. Under current compiler assumptions,
* that would be | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutate-global-in-effect-fixpoint.js",
"language": "javascript",
"file_size": 1009,
"cut_index": 512,
"middle_length": 229
} |
alidateRefAccessDuringRender @validateNoSetStateInRender:false
import {useCallback, useEffect, useRef, useState} from 'react';
function Component() {
const ref = useRef(null);
const [state, setState] = useState(false);
const setRef = useCallback(() => {
ref.current = 'Ok';
}, []);
useEffect(() => {
... | String(state)} ref={ref} />;
}
function Child({ref}) {
'use no memo';
// This violates the rules of React, so we access the ref in a child
// component
return ref.current;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
};
| ally ran
// and wasn't DCE'd
return <Child key={ | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-ref-access-in-effect-indirect.js",
"language": "javascript",
"file_size": 825,
"cut_index": 517,
"middle_length": 52
} |
ote that this `Array.from` is inferred to be mutating its first
* argument. This is because React Compiler's typing system does not yet support
* annotating a function with a set of argument match cases + distinct
* definitions (polymorphism).
*
* In this case, we should be able to infer that the `Array.from` call... | = [{value: 'foo'}, {value: 'bar'}, {value}];
useIdentity();
const derived = Array.from(arr, (x, idx) => ({...x, id: idx}));
return <Stringify>{derived.at(-1)}</Stringify>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{value: 5} | callee
*/
function Component({value}) {
const arr | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-from-arg1-captures-arg0.js",
"language": "javascript",
"file_size": 955,
"cut_index": 582,
"middle_length": 52
} |
m` is inferred to be mutating its first
* argument. This is because React Compiler's typing system does not yet support
* annotating a function with a set of argument match cases + distinct
* definitions (polymorphism)
*
* In this case, we should be able to infer that the `Array.from` call is
* not mutating its 0... | e: 'bar'}, {value}];
useIdentity();
const derived = Array.from(arr);
return <Stringify>{derived.at(-1)}</Stringify>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{value: 5}],
sequentialRenders: [{value: 5}, {value: 6}, {value: | nent({value}) {
const arr = [{value: 'foo'}, {valu | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-from-captures-arg0.js",
"language": "javascript",
"file_size": 923,
"cut_index": 606,
"middle_length": 52
} |
* TODO: object spreads should have conditionally mutate semantics
* Found differences in evaluator results
* Non-forget (expected):
* (kind: ok) [3,1,5,4]
* [3,1,5,4]
* [4,1,5,4]
* Forget:
* (kind: ok) [3,1,5,4]
* [3,1,5,4]
* [4]
*/
function useBar({arg}) {
'use memo';
/**
* Note th... | e same reactive scope.
*/
const s = new Set([1, 5, 4]);
const mutableIterator = s.values();
return [arg, ...mutableIterator];
}
export const FIXTURE_ENTRYPOINT = {
fn: useBar,
params: [{arg: 3}],
sequentialRenders: [{arg: 3}, {arg: 3}, {ar | should have th | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-spread-mutable-iterator.js",
"language": "javascript",
"file_size": 798,
"cut_index": 517,
"middle_length": 14
} |
ef, useEffect} from 'react';
/**
* The postfix increment operator should return the value before incrementing.
* ```js
* const id = count.current; // 0
* count.current = count.current + 1; // 1
* return id;
* ```
* The bug is that we currently increment the value before the expression is evaluated.
* This bug ... | nction params=0 ]]"}
* logs: ['id = 1','count = 1']
*/
function useFoo() {
const count = useRef(0);
const updateCountPostfix = () => {
const id = count.current++;
return id;
};
const updateCountPrefix = () => {
const id = ++count.curr | x":"[[ function params=0 ]]","updateCountPrefix":"[[ function params=0 ]]"}
* logs: ['id = 0','count = 1']
* Forget:
* (kind: ok) {"count":{"current":0},"updateCountPostfix":"[[ function params=0 ]]","updateCountPrefix":"[[ fu | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-ref-prefix-postfix-operator.js",
"language": "javascript",
"file_size": 1304,
"cut_index": 524,
"middle_length": 229
} |
false
import {ValidateMemoization} from 'shared-runtime';
const Codes = {
en: {name: 'English'},
ja: {name: 'Japanese'},
ko: {name: 'Korean'},
zh: {name: 'Chinese'},
};
function Component(a) {
let keys;
if (a) {
keys = Object.keys(Codes);
} else {
return null;
}
const options = keys.map(code... | {[]}
output={options}
onlyCheckCompiled={true}
/>
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: false}],
sequentialRenders: [
{a: false},
{a: true},
{a: true},
{a: false},
{a | {true} />
<ValidateMemoization
inputs= | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-separate-memoization-due-to-callback-capturing.js",
"language": "javascript",
"file_size": 888,
"cut_index": 547,
"middle_length": 52
} |
ength === 1 && typeof arguments[0] === 'string') {
str = arguments[0];
} else {
str = Array.prototype.map
.call(arguments, function (arg) {
return inspect(arg, {
depth: 10,
});
})
.join(', ');
}
const firstArg = arguments[0];
let logLev... | rLog(
INSPECTOR_LEVELS[logLevel],
str,
[].slice.call(arguments),
INSPECTOR_FRAMES_TO_SKIP
);
}
if (groupStack.length) {
str = groupFormat('', str);
}
global.nativeLoggingHook(str, logLevel);
};
| if (global.__inspectorLog) {
global.__inspecto | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-param-mutate.js",
"language": "javascript",
"file_size": 916,
"cut_index": 606,
"middle_length": 52
} |
`a`
*/
function ComponentA(props) {
const a_DEBUG = [];
a_DEBUG.push(props.a);
if (props.b) {
return null;
}
a_DEBUG.push(props.d);
return a_DEBUG;
}
/**
* props.b *does* influence `a`
*/
function ComponentB(props) {
const a = [];
a.push(props.a);
if (props.b) {
a.push(props.c);
}
a.p... | (props.d);
return a;
}
/**
* props.b *does* influence `a`
*/
function ComponentD(props) {
const a = [];
a.push(props.a);
if (props.b) {
a.push(props.c);
return a;
}
a.push(props.d);
return a;
}
export const FIXTURE_ENTRYPOINT = {
| {
a.push(props.c);
return null;
}
a.push | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conditional-early-return.js",
"language": "javascript",
"file_size": 912,
"cut_index": 547,
"middle_length": 52
} |
TestCase from '../../TestCase';
import Iframe from '../../Iframe';
const React = window.React;
export default class ReorderedInputsTestCase extends React.Component {
state = {count: 0};
componentDidMount() {
this.interval = setInterval(() => {
this.setState({count: this.state.count + 1});
}, 2000);... | eps>
<li>The two inputs below swap positions every two seconds</li>
<li>Select the text in either of them</li>
<li>Wait for the swap to occur</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The selec | ar" />,
];
if (this.state.count % 2 === 0) {
inputs.reverse();
}
return inputs;
}
render() {
return (
<TestCase title="Reordered input elements in iframes" description="">
<TestCase.St | {
"filepath": "fixtures/dom/src/components/fixtures/selection-events/ReorderedInputsTestCase.js",
"language": "javascript",
"file_size": 1163,
"cut_index": 518,
"middle_length": 229
} |
uttonText: 'Trigger error',
badChildType: BadRender,
};
state = {
shouldThrow: false,
didThrow: false,
error: null,
};
componentDidCatch(error) {
this.setState({error, didThrow: true});
}
triggerError = () => {
this.setState({
shouldThrow: true,
});
};
render() {
if... | ops.buttonText}</button>;
}
}
class Example extends React.Component {
state = {key: 0};
restart = () => {
this.setState(state => ({key: state.key + 1}));
};
render() {
return (
<div>
<button onClick={this.restart}>Reset</but | te.error)}</p>;
}
}
if (this.state.shouldThrow) {
const BadChild = this.props.badChildType;
return <BadChild doThrow={this.props.doThrow} />;
}
return <button onClick={this.triggerError}>{this.pr | {
"filepath": "fixtures/dom/src/components/fixtures/error-handling/index.js",
"language": "javascript",
"file_size": 12187,
"cut_index": 921,
"middle_length": 229
} |
= window.React;
const startDate = new Date();
/**
* This test case was originally provided by @richsoni,
* https://github.com/facebook/react/issues/8116
*/
class SwitchDateTestCase extends React.Component {
state = {
fullDate: false,
date: startDate,
};
render() {
const attrs = this.inputAttrs();... | />{' '}
Switch type
</label>
</p>
</div>
);
}
inputAttrs() {
if (this.state.fullDate) {
return {
type: 'datetime-local',
value: this.state.date.toISOString().replace(/\..*Z/, ''),
| .value}
onChange={this.onInputChange}
/>
<label>
<input
type="checkbox"
checked={this.state.fullDate}
onChange={this.updateFullDate}
| {
"filepath": "fixtures/dom/src/components/fixtures/date-inputs/switch-date-test-case.js",
"language": "javascript",
"file_size": 1428,
"cut_index": 524,
"middle_length": 229
} |
ixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import PasswordTestCase from './PasswordTestCase';
const React = window.React;
function NumberInputs() {
return (
<FixtureSet title="Password inputs">
<TestCase
title="The show password icon"
description={`
... | </TestCase.Steps>
<TestCase.ExpectedResult>
The field should include the "unmasking password" icon.
</TestCase.ExpectedResult>
<PasswordTestCase />
</TestCase>
</FixtureSet>
);
}
export default NumberI | <li>Type any string (not an actual password)</li>
| {
"filepath": "fixtures/dom/src/components/fixtures/password-inputs/index.js",
"language": "javascript",
"file_size": 835,
"cut_index": 520,
"middle_length": 52
} |
st React = window.React;
class RangeInputs extends React.Component {
state = {value: 0.5};
onChange = event => {
this.setState({value: event.target.value});
};
render() {
return (
<FixtureSet
title="Range Inputs"
description="Note: Range inputs are not supported in IE9.">
... | lue: {this.state.value}</span>
</fieldset>
<fieldset>
<legend>Uncontrolled</legend>
<input type="range" defaultValue={0.5} />
</fieldset>
</form>
</FixtureSet>
);
}
}
export defaul | />
<span className="hint">Va | {
"filepath": "fixtures/dom/src/components/fixtures/range-inputs/index.js",
"language": "javascript",
"file_size": 882,
"cut_index": 559,
"middle_length": 52
} |
../TestCase';
const React = window.React;
const ReactDOM = window.ReactDOM;
const MouseEnter = () => {
const containerRef = React.useRef();
React.useEffect(function () {
const hostEl = containerRef.current;
ReactDOM.render(<MouseEnterDetect />, hostEl, () => {
ReactDOM.render(<MouseEnterDetect />, ... | r noreferrer"
target="_blank"
href="https://github.com/facebook/react/issues/16763">
#16763
</a>{' '}
should not happen.
<br />
</TestCase.ExpectedResult>
<div ref={containerRef} />
</Te | <li>Mouse enter the boxes below, from different borders</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
Mouse enter call count should equal to 1; <br />
Issue{' '}
<a
rel="noopene | {
"filepath": "fixtures/dom/src/components/fixtures/mouse-events/mouse-enter.js",
"language": "javascript",
"file_size": 1783,
"cut_index": 537,
"middle_length": 229
} |
ment.getElementById('status');
var hydrate = document.getElementById('hydrate');
var reload = document.getElementById('reload');
var renders = 0;
var failed = false;
var needsReactDOM = getBooleanQueryParam('needsReactDOM');
var needsCreateElement = getBooleanQueryParam('needsCreateElement');
function u... | eplaced function invocation in 0.12
if (needsCreateElement) {
return React.createElement(value);
} else {
return value();
}
}
function getQueryParam(key) {
var pattern = new RegExp(key + '=([^&]+)(&|$)');
var matches = | ode) {
React.unmountComponentAtNode(node);
} else {
// Unmounting for React 0.4 and lower
React.unmountAndReleaseReactRootNode(node);
}
}
function createElement(value) {
// React.createElement r | {
"filepath": "fixtures/dom/public/renderer.js",
"language": "javascript",
"file_size": 5233,
"cut_index": 716,
"middle_length": 229
} |
: boolean,
linearAcceleration: null | Float32Array,
linearVelocity: null | Float32Array,
orientation: null | Float32Array,
position: null | Float32Array,
...
};
type Gamepad = {
axes: number[],
buttons: GamepadButton[],
connected: boolean,
displayId?: number,
hapticActuators?: GamepadHapticActuator[... | onlevelchange: ?(event: any) => mixed,
...
};
// https://wicg.github.io/web-share
type ShareData = {
title?: string,
text?: string,
url?: string,
...
};
type PermissionName =
| 'geolocation'
| 'notifications'
| 'push'
| 'midi'
| 'came | ng: boolean,
+chargingTime: number,
+dischargingTime: number,
+level: number,
onchargingchange: ?(event: any) => mixed,
onchargingtimechange: ?(event: any) => mixed,
ondischargingtimechange: ?(event: any) => mixed,
| {
"filepath": "flow-typed/environments/bom.js",
"language": "javascript",
"file_size": 66072,
"cut_index": 2151,
"middle_length": 229
} |
ss NumberTestCase extends React.Component {
state = {value: ''};
onChange = event => {
const parsed = parseFloat(event.target.value, 10);
const value = isNaN(parsed) ? '' : parsed;
this.setState({value});
};
render() {
return (
<Fixture>
<div>{this.props.children}</div>
<... | pan className="hint">
{' '}
Value: {JSON.stringify(this.state.value)}
</span>
</fieldset>
<fieldset>
<legend>Uncontrolled</legend>
<input type="number" defaultValue={0.5} | Change={this.onChange}
/>
<s | {
"filepath": "fixtures/dom/src/components/fixtures/number-inputs/NumberTestCase.js",
"language": "javascript",
"file_size": 992,
"cut_index": 582,
"middle_length": 52
} |
./data';
import {CodeEditor, CodeError} from './Code';
import {compile} from './code-transformer';
import {reactPaths} from '../../../react-loader';
import qs from 'query-string';
const React = window.React;
// The Hydration fixture can render at a different version than the parent
// app. This allows rendering for ve... | {
window.removeEventListener('message', this.handleMessage);
}
handleMessage = event => {
var data = JSON.parse(event.data);
switch (data.type) {
case 'ready':
this.ready = true;
this.injectCode();
break;
| = {
error: null,
code: SAMPLE_CODE,
hydrate: true,
version: initialVersion,
};
ready = false;
componentDidMount() {
window.addEventListener('message', this.handleMessage);
}
componentWillUnmount() | {
"filepath": "fixtures/dom/src/components/fixtures/hydration/index.js",
"language": "javascript",
"file_size": 3046,
"cut_index": 614,
"middle_length": 229
} |
ase from '../../TestCase';
import HitBox from './hit-box';
const React = window.React;
class Persistence extends React.Component {
state = {
persisted: 0,
pooled: [],
};
addPersisted = event => {
let {persisted, pooled} = this.state;
event.persist();
if (event.type === 'mousemove') {
... | description="">
<TestCase.Steps>
<li>Mouse over the pooled event box</li>
<li>Mouse over the persisted event box</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The pool size should not increase abov | t.type === 'mousemove' && pooled.indexOf(event) === -1) {
this.setState({pooled: pooled.concat(event)});
}
};
render() {
const {pooled, persisted} = this.state;
return (
<TestCase title="Persistence" | {
"filepath": "fixtures/dom/src/components/fixtures/event-pooling/persistence.js",
"language": "javascript",
"file_size": 1437,
"cut_index": 524,
"middle_length": 229
} |
re from '../../Fixture';
const React = window.React;
class InputTestCase extends React.Component {
static defaultProps = {
type: 'text',
defaultValue: '',
parseAs: 'text',
};
constructor() {
super(...arguments);
this.state = {
value: this.props.defaultValue,
};
}
onChange = e... | Fixture>
<div>{children}</div>
<div className="control-box">
<fieldset>
<legend>Controlled {type}</legend>
<input type={type} value={value} onChange={this.onChange} />
<p className="hint">Value | aN(parsed) ? '' : parsed});
break;
default:
this.setState({value: raw});
}
};
render() {
const {children, type, defaultValue} = this.props;
const {value} = this.state;
return (
< | {
"filepath": "fixtures/dom/src/components/fixtures/text-inputs/InputTestCase.js",
"language": "javascript",
"file_size": 1303,
"cut_index": 524,
"middle_length": 229
} |
EmailInput';
const React = window.React;
class TextInputFixtures extends React.Component {
render() {
return (
<FixtureSet
title="Inputs"
description="Common behavior across controlled and uncontrolled inputs">
<TestCase title="Numbers in a controlled text field with no handler">
... | number</legend>
<input value={2} onChange={() => {}} />
</fieldset>
<fieldset>
<legend>Value as string</legend>
<input value={'2'} onChange={() => {}} />
</fieldset | e.ExpectedResult>
The text field's value should not update.
</TestCase.ExpectedResult>
<Fixture>
<div className="control-box">
<fieldset>
<legend>Value as | {
"filepath": "fixtures/dom/src/components/fixtures/text-inputs/index.js",
"language": "javascript",
"file_size": 5894,
"cut_index": 716,
"middle_length": 229
} |
ase from '../../TestCase';
import HoverBox from './hover-box';
const React = window.React;
class Hover extends React.Component {
state = {
overs: 0,
outs: 0,
enters: 0,
leaves: 0,
};
onOver = () => this.setState({overs: this.state.overs + 1});
onOut = () => this.setState({outs: this.state.out... | Overs and outs should increase when moving over the obstacles but
enters and leaves should not.
</TestCase.ExpectedResult>
<HoverBox
onOver={this.onOver}
onOut={this.onOut}
onEnter={this.onEnte | s} = this.state;
return (
<TestCase title="Hover" description="">
<TestCase.Steps>
<li>Hover over the above box and the obstacles</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
| {
"filepath": "fixtures/dom/src/components/fixtures/pointer-events/hover.js",
"language": "javascript",
"file_size": 1326,
"cut_index": 524,
"middle_length": 229
} |
estCase 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"
... | href="https://support.google.com/chrome/answer/142893?co=GENIE.Platform%3DDesktop&hl=en"
text="Google Chrome"
/>
</li>
<li>
<SafeLink
| r.">
<TestCase.Steps>
<li>
Set up autofill/autocomplete for your browser.
<br />
Instructions:
<ul>
<li>
<SafeLink
| {
"filepath": "fixtures/dom/src/components/fixtures/form-state/index.js",
"language": "javascript",
"file_size": 2083,
"cut_index": 563,
"middle_length": 229
} |
reSet from '../../FixtureSet';
import TestCase from '../../TestCase';
const React = window.React;
function onButtonClick() {
window.alert(`This shouldn't have happened!`);
}
export default class ButtonTestCases extends React.Component {
render() {
return (
<FixtureSet title="Buttons">
<TestCase... | Click Me
</button>
</TestCase>
<TestCase
title="onClick with disabled buttons containing other elements"
description="The onClick event handler should not be invoked when clicking on a disabled butt | <li>Click on the disabled button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
Nothing should happen
</TestCase.ExpectedResult>
<button disabled onClick={onButtonClick}>
| {
"filepath": "fixtures/dom/src/components/fixtures/buttons/index.js",
"language": "javascript",
"file_size": 1437,
"cut_index": 524,
"middle_length": 229
} |
ase from '../../TestCase';
import Iframe from '../../Iframe';
const React = window.React;
class OnSelectIframe extends React.Component {
state = {count: 0, value: 'Select Me!'};
_onSelect = event => {
this.setState(({count}) => ({count: count + 1}));
};
_onChange = event => {
this.setState({value: ev... | rn (
<TestCase
title="onSelect events within iframes"
description="onSelect events should fire for elements rendered inside iframes">
<TestCase.Steps>
<li>Highlight some of the text in the input below</li>
| "
onSelect={this._onSelect}
value={value}
onChange={this._onChange}
/>
</Iframe>
);
}
}
export default class OnSelectEventTestCase extends React.Component {
render() {
retu | {
"filepath": "fixtures/dom/src/components/fixtures/selection-events/OnSelectEventTestCase.js",
"language": "javascript",
"file_size": 1307,
"cut_index": 524,
"middle_length": 229
} |
;
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import SwitchDateTestCase from './switch-date-test-case';
const React = window.React;
class DateInputFixtures extends React.Component {
render() {
return (
<FixtureSet title="Dates">
<TestCase title="Switching betw... | , and year values should correctly transfer. The
hours/minutes/seconds should not be discarded.
</TestCase.ExpectedResult>
<Fixture>
<SwitchDateTestCase />
</Fixture>
</TestCase>
</Fixtur | <TestCase.ExpectedResult>
The month, day | {
"filepath": "fixtures/dom/src/components/fixtures/date-inputs/index.js",
"language": "javascript",
"file_size": 909,
"cut_index": 547,
"middle_length": 52
} |
ort TestCase from '../../TestCase';
const React = window.React;
class MouseMovement extends React.Component {
state = {
movement: {x: 0, y: 0},
};
onMove = event => {
this.setState({x: event.movementX, y: event.movementY});
};
render() {
const {x, y} = this.state;
const boxStyle = {
... | es should equal the pixel (integer) difference
between mouse movements positions.
</TestCase.ExpectedResult>
<div style={boxStyle} onMouseMove={this.onMove}>
<p>Trace your mouse over this box.</p>
<p>
| movementX and movementY fields."
affectedBrowsers="IE, Safari">
<TestCase.Steps>
<li>Mouse over the box below</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The reported valu | {
"filepath": "fixtures/dom/src/components/fixtures/mouse-events/mouse-movement.js",
"language": "javascript",
"file_size": 1119,
"cut_index": 515,
"middle_length": 229
} |
Promise(resolve => {
setTimeout(resolve, timeoutMS);
});
}
export default function FormActions() {
const [textValue, setTextValue] = useState('0');
const [radioValue, setRadioValue] = useState('two');
const [checkboxValue, setCheckboxValue] = useState([false, true, true]);
const [selectValue, setSelectV... | type="text"
name="text"
value={textValue}
onChange={event => setTextValue(event.currentTarget.value)}
/>
</fieldset>
<fieldset style={{flexBasis: 0}}>
<legend>type="radio"</le | setCheckboxValue([false, true, true]);
setSelectValue('three');
}}>
<div style={{display: 'flex'}}>
<fieldset style={{flexBasis: 0}}>
<legend>type="text"</legend>
<input
| {
"filepath": "fixtures/dom/src/components/fixtures/form-actions/index.js",
"language": "javascript",
"file_size": 3357,
"cut_index": 614,
"middle_length": 229
} |
traZeroes from './NumberInputExtraZeroes';
const React = window.React;
function NumberInputs() {
return (
<FixtureSet
title="Number inputs"
description="Number inputs inconsistently assign and report the value
property depending on the browser.">
<TestCase
title="B... | Notes:</b> Modern Chrome and Safari {'<='} 6 clear trailing
decimals on blur. React makes this concession so that the value
attribute remains in sync with the value property.
</p>
</TestCase>
<TestCase
title | /TestCase.Steps>
<TestCase.ExpectedResult>
The field should read "3.", preserving the decimal place
</TestCase.ExpectedResult>
<NumberTestCase />
<p className="footnote">
<b> | {
"filepath": "fixtures/dom/src/components/fixtures/number-inputs/index.js",
"language": "javascript",
"file_size": 5897,
"cut_index": 716,
"middle_length": 229
} |
alue: ''};
_nestedDOMNode = null;
_singleFormDOMNode = null;
_multipleFormDOMNode = null;
onChange = event => {
this.setState({value: event.target.value});
};
resetSingleOptionForm = event => {
event.preventDefault();
this._singleFormDOMNode.reset();
};
resetMultipleOptionForm = event => ... | ="blue">Blue</option>
<option value="green">Green</option>
</select>,
this._nestedDOMNode
);
}
render() {
return (
<FixtureSet title="Selects">
<form className="field-group">
<fieldset>
< |
}
_renderNestedSelect() {
ReactDOM.render(
<select value={this.state.value} onChange={this.onChange}>
<option value="">Select a color</option>
<option value="red">Red</option>
<option value | {
"filepath": "fixtures/dom/src/components/fixtures/selects/index.js",
"language": "javascript",
"file_size": 8043,
"cut_index": 716,
"middle_length": 229
} |
/../Fixture';
const React = window.React;
class ReplaceEmailInput extends React.Component {
state = {
formSubmitted: false,
};
onReset = () => {
this.setState({formSubmitted: false});
};
onSubmit = event => {
event.preventDefault();
this.setState({formSubmitted: true});
};
render() {
... | (
<input type="text" disabled={true} />
)}
</fieldset>
</form>
<button type="button" onClick={this.onReset}>
Reset
</button>
</Fixture>
);
}
}
export default ReplaceEmailIn | <input type="email" />
) : | {
"filepath": "fixtures/dom/src/components/fixtures/text-inputs/ReplaceEmailInput.js",
"language": "javascript",
"file_size": 848,
"cut_index": 535,
"middle_length": 52
} |
Set from '../../FixtureSet';
import TestCase from '../../TestCase';
const React = window.React;
class ProgressFixture extends React.Component {
state = {value: 0, max: 1, enabled: false, backwards: false};
startTest = () => {
this.setState({enabled: true}, () => {
this.progressIntervalId = setInterval(... | lue < this.state.max) {
this.setState({value: this.state.value + this.state.max / 100});
} else {
this.setState({backwards: true});
}
}
}, 10);
});
};
resetTest = () => {
clearInterval( | (this.state.max === 10000) {
this.resetTest();
} else {
this.setState({max: this.state.max * 100, backwards: false});
}
}
} else {
if (this.state.va | {
"filepath": "fixtures/dom/src/components/fixtures/progress/index.js",
"language": "javascript",
"file_size": 2703,
"cut_index": 563,
"middle_length": 229
} |
nds 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>
<in... | </span>
</fieldset>
<fieldset>
<legend>Uncontrolled</legend>
<input type="password" defaultValue="" />
</fieldset>
</div>
</Fixture>
);
}
}
export default PasswordTestCase;
| Value: {JSON.stringify(this.state.value)}
| {
"filepath": "fixtures/dom/src/components/fixtures/password-inputs/PasswordTestCase.js",
"language": "javascript",
"file_size": 914,
"cut_index": 606,
"middle_length": 52
} |
estCase from '../../TestCase';
import JumpingCursorTestCase from './JumpingCursorTestCase';
import EmailEnabledAttributesTestCase from './EmailEnabledAttributesTestCase';
import EmailDisabledAttributesTestCase from './EmailDisabledAttributesTestCase';
const React = window.React;
function EmailInputs() {
return (
... | character</li>
</TestCase.Steps>
<TestCase.ExpectedResult>Cursor not moving.</TestCase.ExpectedResult>
<JumpingCursorTestCase />
</TestCase>
<TestCase
title="Attributes enabled"
description={`
| r
doing this place cursor to the beginning.
`}
affectedBrowsers="Chrome">
<TestCase.Steps>
<li>Type space and character</li>
<li>Type character, space, character, delete last | {
"filepath": "fixtures/dom/src/components/fixtures/email-inputs/index.js",
"language": "javascript",
"file_size": 2179,
"cut_index": 563,
"middle_length": 229
} |
const React = window.React;
export class CodeEditor extends React.Component {
shouldComponentUpdate() {
return false;
}
componentDidMount() {
this.textarea = findDOMNode(this);
// Important: CodeMirror incorrectly lays out the editor
// if it executes before CSS has loaded
// https://gith... | r = CodeMirror.fromTextArea(this.textarea, {
mode: 'jsx',
theme: 'paraiso-dark',
lineNumbers: true,
});
this.editor.on('change', function (doc) {
onChange(doc.getValue());
});
}
componentWillUnmount() {
if (thi | import('./codemirror-paraiso-dark.css'),
]).then(([CodeMirror]) => this.install(CodeMirror));
}
install(CodeMirror) {
if (!this.textarea) {
return;
}
const {onChange} = this.props;
this.edito | {
"filepath": "fixtures/dom/src/components/fixtures/hydration/Code.js",
"language": "javascript",
"file_size": 2042,
"cut_index": 563,
"middle_length": 229
} |
re from '../../Fixture';
const React = window.React;
class ControlledFormFixture extends React.Component {
constructor(props) {
super(props);
this.state = {name: '', email: ''};
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
}
... | x-autocompletetype="name"
/>
</label>
<br />
<label>
Email:
<input
type="text"
value={this.state.email}
onChange={this.handleEmailChange}
| <Fixture>
<form>
<label>
Name:
<input
type="text"
value={this.state.name}
onChange={this.handleNameChange}
name="name"
| {
"filepath": "fixtures/dom/src/components/fixtures/form-state/ControlledFormFixture.js",
"language": "javascript",
"file_size": 1395,
"cut_index": 524,
"middle_length": 229
} |
;
class DragBox extends React.Component {
state = {
hasCapture: false,
circleLeft: 80,
circleTop: 80,
};
isDragging = false;
previousLeft = 0;
previousTop = 0;
onDown = event => {
this.isDragging = true;
event.target.setPointerCapture(event.pointerId);
// We store the initial coor... | tCapture = event => this.setState({hasCapture: true});
onLostCapture = event => this.setState({hasCapture: false});
extractPositionDelta = event => {
const left = event.pageX;
const top = event.pageY;
const delta = {
left: left - thi | top} = this.extractPositionDelta(event);
this.setState(({circleLeft, circleTop}) => ({
circleLeft: circleLeft + left,
circleTop: circleTop + top,
}));
};
onUp = event => (this.isDragging = false);
onGo | {
"filepath": "fixtures/dom/src/components/fixtures/pointer-events/drag-box.js",
"language": "javascript",
"file_size": 2104,
"cut_index": 563,
"middle_length": 229
} |
, y) {
'use no forget';
if (x != null) {
x.value = (x.value ?? 0) + 1;
}
if (y != null) {
y.value = (y.value ?? 0) + 1;
}
}
function cond(x) {
'use no forget';
return x.value > 5;
}
function testFunction(props) {
let a = {};
let b = {};
let c = {};
let d = {};
while (true) {
let z =... | , which is later modified, and
// these are therefore mutable references:
if (a) {
}
if (b) {
}
if (c) {
}
if (d) {
}
mutate(d, null);
return {a, b, c, d};
}
export const FIXTURE_ENTRYPOINT = {
fn: testFunction,
params: [{}],
|
// mutated again. but they are all aliased by `d` | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutable-lifetime-loops.js",
"language": "javascript",
"file_size": 860,
"cut_index": 529,
"middle_length": 52
} |
e)) {
x.value = [];
}
x.value.push(y);
if (y != null) {
y.value = x;
}
}
function Component(props) {
const a = {};
const b = [a]; // array elements alias
const c = {};
const d = {c}; // object values alias
// capture all the values into this object
const x = {};
x.b = b;
const y = muta... | re mutable references:
if (a) {
}
if (b) {
}
if (c) {
}
if (d) {
}
if (y) {
}
// could in theory mutate any of a/b/c/x/z, so the above should be inferred as mutable
mutate(x, null);
return x;
}
export const FIXTURE_ENTRYPOINT = | which is later modified, and
// these are therefo | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutable-lifetime-with-aliasing.js",
"language": "javascript",
"file_size": 950,
"cut_index": 582,
"middle_length": 52
} |
This test fixture is similar to mutation-within-jsx. The only difference
* is that there is no `freeze` effect here, which means that `z` may be
* mutated after its memo block through mutating `y`.
*
* While this is technically correct (as `z` is a nested memo block), it
* is an edge case as we believe that values... |
// z captures the result of `mutate(y)`, which may be aliased to `y`.
const z = [mutate(y)];
// the following line may also mutate z
mutate(y);
// and end here
return z;
}
export const FIXTURE_ENTRYPOINT = {
fn: useFoo,
params: [{a: 2, b: | here
const x = {a};
const y = [b];
mutate(x); | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-capture-and-mutablerange.tsx",
"language": "tsx",
"file_size": 876,
"cut_index": 559,
"middle_length": 52
} |
akeObject_Primitives,
mutateAndReturn,
} from 'shared-runtime';
/**
* In this example, the `<Stringify ... />` JSX block mutates then captures obj.
* As JSX expressions freeze their values, we know that `obj` and `myDiv` cannot
* be mutated past this.
* This set of mutable range + scopes is an edge case because ... | $1@0 = mutate(obj@0); |
* myDiv@1 = JSX $1@0 <- scope@1 |
* } ⌟
*
* Coincidentally, the range of `obj` is extended by alignScopesToBlocks to *past*
* the end of the JSX instructi | the lvalue storing the result of `<Stringify .../>`
* this is a immutable value and so gets assigned a different scope
*
* obj@0 = makeObj(); ⌝ scope@0
* if (cond) { |
* | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-jsx.tsx",
"language": "tsx",
"file_size": 1932,
"cut_index": 537,
"middle_length": 229
} |
nctions
import {useCallback, useEffect} from 'react';
import {identity, Stringify, useIdentity} from 'shared-runtime';
import * as SharedRuntime from 'shared-runtime';
function Component(props) {
function named() {
const inner = () => props.named;
const innerIdentity = identity(() => props.named);
retur... | namedElementAttr} />;
const hookArgument = useIdentity(() => props.hookArgument);
useEffect(() => {
console.log(props.useEffect);
JSON.stringify(null, null, () => props.useEffect);
const g = () => props.useEffect;
console.log(g());
}, | SharedRuntime.identity(() => props.methodCall);
const call = identity(() => props.call);
const builtinElementAttr = <div onClick={() => props.builtinElementAttr} />;
const namedElementAttr = <Stringify onClick={() => props. | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/name-anonymous-functions.js",
"language": "javascript",
"file_size": 1624,
"cut_index": 537,
"middle_length": 229
} |
rveExistingMemoizationGuarantees
import {useMemo} from 'react';
import {Stringify} from 'shared-runtime';
// derived from https://github.com/facebook/react/issues/32261
function Component({items}) {
const record = useMemo(
() =>
Object.fromEntries(
items.map(item => [item.id, ref => <Stringify ref=... | ap(id => (
<Stringify key={id} render={record[id]} />
))}
</div>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [
{
items: [
{id: '0', name: 'Hello'},
{id: '1', name: 'World!'},
],
| ed
return (
<div>
{Object.keys(record).m | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-keys.js",
"language": "javascript",
"file_size": 851,
"cut_index": 529,
"middle_length": 52
} |
gify} from 'shared-runtime';
// derived from https://github.com/facebook/react/issues/32261
function Component({items}) {
const record = useMemo(
() =>
Object.fromEntries(
items.map(item => [
item.id,
{id: item.id, render: ref => <Stringify ref={ref} {...item} />},
])
... | (
<Stringify key={id} render={render} />
))}
</div>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [
{
items: [
{id: '0', name: 'Hello'},
{id: '1', name: 'World!'},
],
},
],
}; |
{Object.values(record).map(({id, render}) => | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-values.js",
"language": "javascript",
"file_size": 915,
"cut_index": 606,
"middle_length": 52
} |
;
if (props.cond) {
if (props.cond2) {
y = [props.value];
} else {
y = [props.value2];
}
} else {
y = [];
}
// This should be inferred as `<store> y` s.t. `x` can still
// be independently memoized. *But* this also must properly
// extend the mutable range of the array literals i... | rue, cond2: true, value: 42},
{cond: true, cond2: true, value: 3.14},
{cond: true, cond2: false, value2: 3.14},
{cond: true, cond2: false, value2: 42},
{cond: true, cond2: false, value2: 3.14},
{cond: false},
{cond: false},
],
};
| {cond: true, cond2: true, value: 3.14},
{cond: t | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/phi-type-inference-array-push-consecutive-phis.js",
"language": "javascript",
"file_size": 914,
"cut_index": 606,
"middle_length": 52
} |
/ @enablePreserveExistingMemoizationGuarantees @validatePreserveExistingMemoizationGuarantees @enableOptionalDependencies
import {useMemo} from 'react';
import {identity, ValidateMemoization} from 'shared-runtime';
function Component({x}) {
const object = useMemo(() => {
return identity({
callback: () => ... | nput1 = {x: {y: {z: 42}}};
const input1b = {x: {y: {z: 42}}};
const input2 = {x: {y: {z: 3.14}}};
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [input1],
sequentialRenders: [
input1,
input1,
input1b, // should reset even thou | on-nullable
// we can only take a dep on x.y, not x.y.z
}, [x.y]);
const result = useMemo(() => {
return [object.callback()];
}, [object]);
return <ValidateMemoization inputs={[x.y]} output={result} />;
}
const i | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-deps-conditional-property-chain-less-precise-deps.js",
"language": "javascript",
"file_size": 1050,
"cut_index": 513,
"middle_length": 229
} |
eserveExistingMemoizationGuarantees @validatePreserveExistingMemoizationGuarantees @enableOptionalDependencies
import {useMemo} from 'react';
import {identity, ValidateMemoization} from 'shared-runtime';
function Component({x}) {
const object = useMemo(() => {
return identity({
callback: () => {
r... | export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{x: {y: {z: 42}}}],
sequentialRenders: [
{x: {y: {z: 42}}},
{x: {y: {z: 42}}},
{x: {y: {z: 3.14}}},
{x: {y: {z: 42}}},
{x: {y: {z: 3.14}}},
{x: {y: {z: 42}}},
],
}; | esult} />;
}
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-deps-conditional-property-chain.js",
"language": "javascript",
"file_size": 795,
"cut_index": 524,
"middle_length": 14
} |
@enableOptionalDependencies
import {useMemo} from 'react';
import {identity, ValidateMemoization} from 'shared-runtime';
function Component({x, y, z}) {
const object = useMemo(() => {
return identity({
callback: () => {
return identity(x?.y?.z, y.a?.b, z.a.b?.c);
},
});
}, [x?.y?.z, y... | t={result} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{x: {y: {z: 42}}}],
sequentialRenders: [
{x: {y: {z: 42}}},
{x: {y: {z: 42}}},
{x: {y: {z: 3.14}}},
{x: {y: {z: 42}}},
{x: {y: {z: 3.14}}},
{x: {y: | return <ValidateMemoization inputs={[x.y.z]} outpu | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-deps-optional-property-chain.js",
"language": "javascript",
"file_size": 933,
"cut_index": 606,
"middle_length": 52
} |
tion Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(false);
/... | of `x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: true} | lues assigned to `x` are non-reactive, but the value | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-do-while.js",
"language": "javascript",
"file_size": 830,
"cut_index": 516,
"middle_length": 52
} |
Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push({a: false});
... | e of `x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: true | alues assigned to `x` are non-reactive, but the valu | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-in.js",
"language": "javascript",
"file_size": 835,
"cut_index": 520,
"middle_length": 52
} |
Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(0);
// Downst... | ue of `x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: tru | values assigned to `x` are non-reactive, but the val | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-init.js",
"language": "javascript",
"file_size": 836,
"cut_index": 520,
"middle_length": 52
} |
ion Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(null);
// ... | x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: true}],
}; | assigned to `x` are non-reactive, but the value of ` | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-of.js",
"language": "javascript",
"file_size": 826,
"cut_index": 517,
"middle_length": 52
} |
Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(10);
// Downs... | ue of `x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: tru | values assigned to `x` are non-reactive, but the val | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-test.js",
"language": "javascript",
"file_size": 836,
"cut_index": 520,
"middle_length": 52
} |
Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(10);
// Downs... | value of `x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: | The values assigned to `x` are non-reactive, but the | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-update.js",
"language": "javascript",
"file_size": 840,
"cut_index": 520,
"middle_length": 52
} |
Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(null);
// Dow... | value of `x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: | he values assigned to `x` are non-reactive, but the | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-if.js",
"language": "javascript",
"file_size": 839,
"cut_index": 520,
"middle_length": 52
} |
and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(null);
// Downstream consumer of a, whic... | are non-reactive, but the value of `x`
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Co | x = 2;
}
}
// The values assigned to `x` | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-switch.js",
"language": "javascript",
"file_size": 893,
"cut_index": 547,
"middle_length": 52
} |
function Component(props) {
// a and b are independent but their mutations are interleaved, so
// they get grouped in a reactive scope. this means that a becomes
// reactive since it will effectively re-evaluate based on a reactive
// input
const a = [];
const b = [];
b.push(props.cond);
a.push(null);
... | `
// depends on the "control" value `c[0]` which becomes reactive via
// being interleaved with `b`.
// Therefore x should be treated as reactive too.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: true}],
};
| ssigned to `x` are non-reactive, but the value of `x | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-while.js",
"language": "javascript",
"file_size": 820,
"cut_index": 512,
"middle_length": 52
} |
PreserveExistingMemoizationGuarantees @enablePreserveExistingMemoizationGuarantees:false
import {useMemo} from 'react';
import {ValidateMemoization, useHook} from 'shared-runtime';
function UnmemoizedCallbackCapturedInContextVariable({cond1, cond2}) {
// The return value is captured by `x` which is a context variabl... | le
let x;
if (cond1) {
x = a;
} else if (cond2) {
x = b;
} else {
return null;
}
const f = () => {
return x;
};
const result = f();
return <ValidateMemoization inputs={[cond1, cond2]} output={result} />;
}
export const | range, it can't be memoized either
const b = useMemo(() => ({}), []);
// Conditional assignment without a subsequent mutation normally doesn't create a mutable
// range, but in this case we're reassigning a context variab | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-repro-unmemoized-callback-captured-in-context-variable.tsx",
"language": "tsx",
"file_size": 1335,
"cut_index": 524,
"middle_length": 229
} |
'shared-runtime';
function Component(props) {
let x;
// Reassign `x` based on a reactive value, but inside a function expression
// to make it a context variable
const f = () => {
if (props.cond) {
x = 1;
} else {
x = 2;
}
};
// Pass `f` through a function to prevent IIFE inlining o... | urn [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
sequentialRenders: [
{cond: true},
{cond: true},
{cond: false},
{cond: false},
{cond: true},
{cond: false},
{cond: true},
{cond: false},
],
} | Therefore x should be treated as reactive too.
ret | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-on-context-variable.js",
"language": "javascript",
"file_size": 845,
"cut_index": 535,
"middle_length": 52
} |
nction Component(props) {
const [x, setX] = useState(false);
const [y, setY] = useState(false);
let setState;
if (props.cond) {
setState = setX;
} else {
setState = setY;
}
const setState2 = setState;
const stateObject = {setState: setState2};
return (
<Foo
cond={props.cond}
se... | State === setY, 'Expected the correct setState function');
}
return 'ok';
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
sequentialRenders: [
{cond: true},
{cond: true},
{cond: false},
{cond: false},
{cond: | ct setState function');
} else {
invariant(set | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-phi-setState-type.js",
"language": "javascript",
"file_size": 961,
"cut_index": 582,
"middle_length": 52
} |
value = null;
loop: for (let i = 0; i < 10; i++) {
switch (value) {
case true: {
x = 1;
break loop;
}
case false: {
x = 2;
break loop;
}
}
value = props.cond;
}
// The values assigned to `x` are non-reactive, but the value of `x`
// depends ... | ve.
return [x];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
sequentialRenders: [
{cond: true},
{cond: true},
{cond: false},
{cond: false},
{cond: true},
{cond: false},
{cond: true},
{cond: false | active.
// Therefore x should be treated as reacti | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-reactive-after-fixpoint.js",
"language": "javascript",
"file_size": 878,
"cut_index": 559,
"middle_length": 52
} |
mponent(props) {
const x = [];
const y = x;
// y isn't reactive yet when we first visit this, so z is initially non-reactive
const z = [y];
// then we realize y is reactive. we need a fixpoint to propagate this back to z
y.push(props.input);
// PruneNonReactiveDependencies partially propagates reactivi... | export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
sequentialRenders: [
{input: 42},
{input: 42},
{input: 'sathya'},
{input: 'sathya'},
{input: 42},
{input: 'sathya'},
{input: 42},
{input: 'sathya'},
],
} | 0][0][0] === 42) {
b = 1;
}
return [b];
}
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-readonly-alias-of-mutable-value.js",
"language": "javascript",
"file_size": 833,
"cut_index": 523,
"middle_length": 52
} |
{Stringify} from 'shared-runtime';
function Component({config}) {
/**
* The original memoization is optimal in the sense that it has
* one output (the object) and one dependency (`config`). Both
* the `a` and `b` functions will have to be recreated whenever
* `config` changes, cascading to update the ob... | fig
* / \
* [a] [b]
* \ /
* [object]
*
* All the scopes (shown in []) are transitively dependent on
* `config`, so they can be merged.
*/
const object = useMemo(() => {
c | d later -
* so we don't merge these scopes, and so on.
*
* The more optimal thing would be to build a dependency graph
* of scopes so that we can see the data flow is along the lines
* of:
*
* con | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reordering-across-blocks.js",
"language": "javascript",
"file_size": 1216,
"cut_index": 518,
"middle_length": 229
} |
e';
/**
* Example fixture demonstrating a case where we could hoist dependencies
* and reuse them across scopes. Here we extract a temporary for `item.value`
* and reference it both in the scope for `a`. Then the scope for `c` could
* use `<item-value-temp>.inner` as its dependency, avoiding reloading
* `item.val... | value: item.value, index});
}
const b = [item.value];
// This dependency is more precise (nested property), the outer
// `item.value` portion could use a hoisted dep for `item.value
const c = [item.value.inner];
return <Stringify value={[a, b, | luate it
const a = [];
if (index) {
a.push({ | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repeated-dependencies-more-precise.js",
"language": "javascript",
"file_size": 878,
"cut_index": 559,
"middle_length": 52
} |
ns:false @enableNewMutationAliasingModel
import {arrayPush, setPropertyByKey, Stringify} from 'shared-runtime';
/**
* Repro of a bug fixed in the new aliasing model.
*
* 1. `InferMutableRanges` derives the mutable range of identifiers and their
* aliases from `LoadLocal`, `PropertyLoad`, etc
* - After this ... | infer that
* - `arrayPush(y, x)` might alias `x` and `y` to each other
* - `setPropertyKey(x, ...)` may mutate both `x` and `y`
* - This pass correctly extends the mutable range of `y`
* - Since we didn't run `InferMutableRange` logic agai | esult, `LoadLocal y` and
* `PropertyLoad y` do not get mutable ranges
* 2. `InferReactiveScopeVariables` extends mutable ranges and creates scopes,
* as according to the 'co-mutation' of different values
* - Here, we | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-aliased-capture-aliased-mutate.js",
"language": "javascript",
"file_size": 2253,
"cut_index": 563,
"middle_length": 229
} |
fy} from 'shared-runtime';
// This is a translation of the original merge-consecutive-scopes which uses plain objects
// to describe the UI instead of JSX. The JSXText elements in that fixture happen to
// prevent scome scopes from merging, which concealed a bug with the merging logic.
// By avoiding JSX we eliminate ... | },
{
component: 'button',
props: {
'data-testid': 'button',
onClick: () => setState(state + 1),
children: ['increment'],
},
},
];
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
}; | ,
{component: 'span', props: {children: [state]} | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-objects.js",
"language": "javascript",
"file_size": 868,
"cut_index": 559,
"middle_length": 52
} |
reSet from '../../FixtureSet';
import TestCase from '../../TestCase';
const React = window.React;
const ReactDOM = window.ReactDOM;
const supportsCustomElements = typeof customElements !== 'undefined';
class HelloWorld extends React.Component {
render() {
return <h1>Hello, world!</h1>;
}
}
if (supportsCusto... | nt(HelloWorld), shadowRoot);
}
}`
)(React, ReactDOM, HelloWorld);
customElements.define('my-element', MyElement);
}
export default class ButtonTestCases extends React.Component {
render() {
return (
<FixtureSet
title="Cus | 'ReactDOM',
'HelloWorld',
`
return class MyElement extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode:'open' });
ReactDOM.render(React.createEleme | {
"filepath": "fixtures/dom/src/components/fixtures/custom-elements/index.js",
"language": "javascript",
"file_size": 1494,
"cut_index": 524,
"middle_length": 229
} |
{Stringify, graphql} from 'shared-runtime';
function useFragment(_arg1, _arg2) {
'use no forget';
return {
urls: ['url1', 'url2', 'url3'],
comments: ['comment1'],
};
}
function Component(props) {
const post = useFragment(
graphql`
fragment F on T {
id
}
`,
props.post
... | his means we try to
// reassign `comments` when there's no declaration for it.
const {media = null, comments = [], urls = []} = post;
const onClick = e => {
if (!comments.length) {
return;
}
console.log(comments.length);
};
allU | ecks `comments.length`)
// because of the scope, the let declaration for media and urls are lifted
// out of the scope, and the destructure statement ends up turning into
// a reassignment, instead of a const declaration. t | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-mixed-scope-and-local-variables-with-default.js",
"language": "javascript",
"file_size": 1200,
"cut_index": 518,
"middle_length": 229
} |
shared-runtime';
// Achieving Forget's level of memoization precision in this example isn't possible with useMemo
// without significantly altering the code, so disable the non-Forget evaluation of this fixture.
// @disableNonForgetInSprout
function Component({a, b, c}) {
const x = [];
let y;
if (a) {
y = [b... | <ValidateMemoization inputs={[a, b]} output={z} />
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: false, b: null, c: 0}],
sequentialRenders: [
{a: false, b: null, c: 0},
{a: false, b: null, c: 1},
{a | alidateMemoization inputs={[a, b, c]} output={x} />
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dont-merge-if-dep-is-inner-declaration-of-previous-scope.js",
"language": "javascript",
"file_size": 911,
"cut_index": 547,
"middle_length": 52
} |
react';
import {Stringify} from 'shared-runtime';
function Foo() {
/**
* Previously, this lowered to
* $1 = LoadContext capture setState
* $2 = FunctionExpression deps=$1 context=setState
* [[ at this point, we freeze the `LoadContext setState` instruction, but it will never be referenced again ]]
*
... | ect
* for everything *other* than hoisted context declarations.
*
* $2 = Function context=setState
*/
useEffect(() => setState(2), []);
const [state, setState] = useState(0);
return <Stringify state={state} />;
}
export const FIXTURE_EN | vel removed `LoadContext`) is more semantically corr | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-hoisting-setstate.js",
"language": "javascript",
"file_size": 964,
"cut_index": 582,
"middle_length": 52
} |
asingModel
import {Stringify, useIdentity} from 'shared-runtime';
function Component({prop1, prop2}) {
'use memo';
const data = useIdentity(
new Map([
[0, 'value0'],
[1, 'value1'],
])
);
let i = 0;
const items = [];
items.push(
<Stringify
key={i}
onClick={() => data.get... | tems}</>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{prop1: 'prop1', prop2: 'prop2'}],
sequentialRenders: [
{prop1: 'prop1', prop2: 'prop2'},
{prop1: 'prop1', prop2: 'prop2'},
{prop1: 'changed', prop2: 'prop2'},
],
|
return <>{i | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-jsx-captures-context-variable.js",
"language": "javascript",
"file_size": 809,
"cut_index": 536,
"middle_length": 14
} |
{useEffect} from 'react';
function Component() {
let local;
const reassignLocal = newValue => {
local = newValue;
};
const onMount = newValue => {
reassignLocal('hello');
if (local === newValue) {
// Without React Compiler, `reassignLocal` is freshly created
// on each render, captu... | assignLocal` will reassign the wrong
// version of `local`, and not update the binding we are checking
// in the if condition.
//
// To protect against this, we disallow reassigning locals from
// functions that escape
t | anch
console.log('`local` was updated!');
} else {
// With React Compiler enabled, `reassignLocal` is only created
// once, capturing a binding to `local` in that render pass.
// Therefore, calling `re | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-effect.js",
"language": "javascript",
"file_size": 1125,
"cut_index": 518,
"middle_length": 229
} |
ction Component() {
let local;
const reassignLocal = newValue => {
local = newValue;
};
const onClick = newValue => {
reassignLocal('hello');
if (local === newValue) {
// Without React Compiler, `reassignLocal` is freshly created
// on each render, capturing a binding to the latest `l... | wrong
// version of `local`, and not update the binding we are checking
// in the if condition.
//
// To protect against this, we disallow reassigning locals from
// functions that escape
throw new Error('`local` not upd | was updated!');
} else {
// With React Compiler enabled, `reassignLocal` is only created
// once, capturing a binding to `local` in that render pass.
// Therefore, calling `reassignLocal` will reassign the | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-jsx-callback.js",
"language": "javascript",
"file_size": 1075,
"cut_index": 515,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.