prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {clamp} from './clamp';
/**
* Single-axis offset and length state.
*
* ```
* contentStart containerStart containerEnd contentEnd
* |<----------offset| | |
* |<-------... | ScrollState,
minContentLength: number,
maxContentLength: number,
containerLength: number,
}): ScrollState {
return {
offset: state.offset,
length: clamp(
Math.max(minContentLength, containerLength),
Math.max(containerLength, max | State {
return {
offset: clamp(-(state.length - containerLength), 0, state.offset),
length: state.length,
};
}
function clampLength({
state,
minContentLength,
maxContentLength,
containerLength,
}: {
state: | {
"filepath": "packages/react-devtools-timeline/src/view-base/utils/scrollState.js",
"language": "javascript",
"file_size": 4763,
"cut_index": 614,
"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.
*
* @flow
*/
// This file uses workerize to load ./importFile.worker as a webworker and instanciates it,
// exposing flow typed fu... | ssedData: TimelineData}
| {status: 'INVALID_PROFILE_ERROR', error: Error}
| {status: 'UNEXPECTED_ERROR', error: Error};
export type importFileFunction = (file: File) => ImportWorkerOutputData;
export const importFile = (file: File): Promise<ImportWor |
type ImportFileModule = typeof importFileModule;
const workerizedImportFile: ImportFileModule = window.Worker
? WorkerizedImportFile()
: importFileModule;
export type ImportWorkerOutputData =
| {status: 'SUCCESS', proce | {
"filepath": "packages/react-devtools-timeline/src/import-worker/index.js",
"language": "javascript",
"file_size": 1057,
"cut_index": 513,
"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.
*
* @flow
*/
import {useLayoutEffect, useRef} from 'react';
const TOOLTIP_OFFSET_BOTTOM = 10;
const TOOLTIP_OFFSET_TOP = 5;
export default function useSmartTooltip({
canvasRef,... | if (target !== null) {
const rect = target.getBoundingClientRect();
height = rect.top + rect.height;
width = rect.left + rect.width;
}
useLayoutEffect(() => {
const element = ref.current;
if (element !== null) {
// Let's che | l);
// HACK: Browser extension reports window.innerHeight of 0,
// so we fallback to using the tooltip target element.
let height = window.innerHeight;
let width = window.innerWidth;
const target = canvasRef.current;
| {
"filepath": "packages/react-devtools-timeline/src/utils/useSmartTooltip.js",
"language": "javascript",
"file_size": 2777,
"cut_index": 563,
"middle_length": 229
} |
Each event type defines the exact object that it accepts. This ensures
* that no arbitrary properties can be assigned to events, and the properties
* that don't exist on specific event types (e.g., 'pointerType') are not added
* to the respective native event.
*
* 2. Properties that cannot be relied on due to inc... | ');
event.initCustomEvent(type, true, true);
if (data != null) {
Object.keys(data).forEach(key => {
const value = data[key];
if (key === 'timeStamp' && !value) {
return;
}
Object.defineProperty(event, key, {value});
| ted values.
*
* 3. PointerEvent and TouchEvent fields are normalized (e.g., 'rotationAngle' -> 'twist')
*/
function emptyFunction() {}
function createEvent(type, data = {}) {
const event = document.createEvent('CustomEvent | {
"filepath": "packages/dom-event-testing-library/domEvents.js",
"language": "javascript",
"file_size": 9256,
"cut_index": 921,
"middle_length": 229
} |
onst fs = require('fs');
const ReactVersionSrc = fs.readFileSync(require.resolve('shared/ReactVersion'));
const reactVersion = /export default '([^']+)';/.exec(ReactVersionSrc)[1];
const config = {
use: {
headless: true,
browserName: 'chromium',
launchOptions: {
// This bit of delay gives async Rea... | t_version: process.env.REACT_VERSION
? semver.coerce(process.env.REACT_VERSION).version
: reactVersion,
trace: 'retain-on-failure',
},
// Some of our e2e tests can be flaky. Retry tests to make sure the error isn't transient
retries: | '
: 'http://localhost:8080/e2e.html',
reac | {
"filepath": "packages/react-devtools-inline/playwright.config.js",
"language": "javascript",
"file_size": 887,
"cut_index": 547,
"middle_length": 52
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Rect} from '../../view-base';
import {rectEqualToRect} from '../../view-base';
import {COLORS, FONT_SIZE, TEXT_PADDING} from '../constants';
const cachedTextWidths = new Map<string, number>();
export fu... | | null {
const maxIndex = text.length - 1;
let startIndex = 0;
let stopIndex = maxIndex;
let longestValidIndex = 0;
let longestValidText = null;
// Trimming long text could be really slow if we decrease only 1 character at a time.
// Trim | xt.measureText(text).width;
cachedTextWidths.set(text, measuredWidth);
}
return ((measuredWidth: any): number);
}
export function trimText(
context: CanvasRenderingContext2D,
text: string,
width: number,
): string | {
"filepath": "packages/react-devtools-timeline/src/content-views/utils/text.js",
"language": "javascript",
"file_size": 3375,
"cut_index": 614,
"middle_length": 229
} |
ource code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import nullthrows from 'nullthrows';
import InvalidProfileError from './InvalidProfileError';
export const readInputData = (file: File): Promise<string> => {
if (!file.name.endsWith('... | {
const result = nullthrows(fileReader.result);
if (typeof result === 'string') {
resolve(result);
}
reject(new InvalidProfileError('Input file was not read as a string'));
};
fileReader.onerror = () => reject(file | (resolve, reject) => {
fileReader.onload = () => | {
"filepath": "packages/react-devtools-timeline/src/import-worker/readInputData.js",
"language": "javascript",
"file_size": 948,
"cut_index": 582,
"middle_length": 52
} |
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';
/**
* Change environment support for PointerEvent.
*/
function emptyFunction() {}
export function hasPointerE... | ptureFn('setPointerCapture')
: undefined;
global.HTMLElement.prototype.releasePointerCapture = bool
? pointerCaptureFn('releasePointerCapture')
: undefined;
}
/**
* Change environment host platform.
*/
const platformGetter = jest.spyOn(gl | f (__DEV__) {
console.error('A pointerId must be passed to "%s"', name);
}
}
};
global.PointerEvent = bool ? emptyFunction : undefined;
global.HTMLElement.prototype.setPointerCapture = bool
? pointerCa | {
"filepath": "packages/dom-event-testing-library/domEnvironment.js",
"language": "javascript",
"file_size": 1520,
"cut_index": 537,
"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.
*
* @flow
*/
import 'regenerator-runtime/runtime';
import type {TimelineEvent} from '@elg/speedscope';
import type {ImportWorkerOutput... | idProfileError('No profiling data found in file.');
}
const processedData = await preprocessData(events);
return {
status: 'SUCCESS',
processedData,
};
} catch (error) {
if (error instanceof InvalidProfileError) {
| tion importFile(file: File): Promise<ImportWorkerOutputData> {
try {
const readFile = await readInputData(file);
const events: TimelineEvent[] = JSON.parse(readFile);
if (events.length === 0) {
throw new Inval | {
"filepath": "packages/react-devtools-timeline/src/import-worker/importFile.js",
"language": "javascript",
"file_size": 1177,
"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.
*
* @emails react-core
*/
'use strict';
/**
* Touch events state machine.
*
* Keeps track of the active pointers and allows them to be reflected in touch events.
*/
const act... | dentifier,
);
} else {
activeTouches.get(target).set(identifier, touch);
}
}
export function updateTouch(touch) {
const identifier = touch.identifier;
const target = touch.target;
if (activeTouches.get(target) != null) {
activeTouche | t, new Map());
}
if (activeTouches.get(target).get(identifier)) {
// Do not allow existing touches to be overwritten
console.error(
'Touch with identifier %s already exists. Did not record touch start.',
i | {
"filepath": "packages/dom-event-testing-library/touchStore.js",
"language": "javascript",
"file_size": 2062,
"cut_index": 563,
"middle_length": 229
} |
;
// Mock of the Native Hooks
const roots = new Map();
const allocatedTags = new Set();
function dumpSubtree(info, indent) {
let out = '';
out += ' '.repeat(indent) + info.viewName + ' ' + JSON.stringify(info.props);
// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (const child of info.childre... | onst result = [];
// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (const [rootTag, childSet] of roots) {
result.push(rootTag);
// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (const child of childSe | slint-disable-next-line no-for-of-loops/no-for-of-loops
for (const child of childSet) {
result.push(dumpSubtree(child, 0));
}
return result.join('\n');
},
__dumpHierarchyForJestTestsOnly: function () {
c | {
"filepath": "packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager.js",
"language": "javascript",
"file_size": 5703,
"cut_index": 716,
"middle_length": 229
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
*/
module.exports = {
get ReactFiberErrorDialog() {
return require('./ReactFiberErrorDialog');
},
get ReactN... |
return require('./getNodeFromPublicInstance').default;
},
get createPublicInstance() {
return require('./createPublicInstance').default;
},
get createPublicTextInstance() {
return require('./createPublicTextInstance').default;
},
g | },
get RawEventEmitter() {
return require('./RawEventEmitter').default;
},
get getNativeTagFromPublicInstance() {
return require('./getNativeTagFromPublicInstance').default;
},
get getNodeFromPublicInstance() { | {
"filepath": "packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/ReactNativePrivateInterface.js",
"language": "javascript",
"file_size": 1321,
"cut_index": 524,
"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';
type Options = {+unsafelyIgnoreFunctions?: boolean};
/*
* @returns {bool} true if different, false if equal
*/
function deepDiffer(
one: any,
two: any,
... | false;
}
if (typeof one === 'function' && typeof two === 'function') {
// We consider all functions equal unless explicitly configured otherwise
let unsafelyIgnoreFunctions =
options == null ? null : options.unsafelyIgnoreFunctions;
i | h =
typeof maxDepthOrOptions === 'number' ? maxDepthOrOptions : -1;
if (maxDepth === 0) {
return true;
}
if (one === two) {
// Short circuit on identical object references instead of traversing them.
return | {
"filepath": "packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/deepDiffer.js",
"language": "javascript",
"file_size": 2306,
"cut_index": 563,
"middle_length": 229
} |
import type {DispatchConfig} from './ReactSyntheticEventType';
import type {
AnyNativeEvent,
PluginName,
LegacyPluginModule,
} from './PluginModuleType';
import type {TopLevelType} from './TopLevelEventTypes';
type NamesToPlugins = {
[key: PluginName]: LegacyPluginModule<AnyNativeEvent>,
};
type EventPluginOrd... | until an `eventPluginOrder` is injected.
return;
}
for (const pluginName in namesToPlugins) {
const pluginModule = namesToPlugins[pluginName];
// $FlowFixMe[incompatible-use] found when upgrading Flow
const pluginIndex = eventPluginOrd | */
const namesToPlugins: NamesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering(): void {
if (!eventPluginOrder) {
// Wait | {
"filepath": "packages/react-native-renderer/src/legacy-events/EventPluginRegistry.js",
"language": "javascript",
"file_size": 7595,
"cut_index": 716,
"middle_length": 229
} |
import type {Node} from './ReactNativeTypes';
import type {ElementRef, ElementType} from 'react';
import type {PublicInstance} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
// Modules provided by RN:
import {
getNodeFromPublicInstance,
getNativeTagFromPublicInstance,
getInternalInstance... | m 'react-reconciler/src/ReactCurrentFiber';
export function findHostInstance_DEPRECATED<TElementType: ElementType>(
componentOrHandle: ?(ElementRef<TElementType> | number),
): ?PublicInstance {
if (__DEV__) {
const owner = currentOwner;
if (ow | actFiberReconciler';
import {doesFiberContain} from 'react-reconciler/src/ReactFiberTreeReflection';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import {
current as currentOwner,
isRendering,
} fro | {
"filepath": "packages/react-native-renderer/src/ReactNativePublicCompat.js",
"language": "javascript",
"file_size": 6823,
"cut_index": 716,
"middle_length": 229
} |
ct-core
*/
'use strict';
describe('EventPluginRegistry', () => {
let EventPluginRegistry;
let createPlugin;
beforeEach(() => {
jest.resetModules();
// These tests are intentionally testing the private injection interface.
// The public API surface of this is covered by other tests so
// if `Ev... | const TwoPlugin = createPlugin();
const ThreePlugin = createPlugin();
EventPluginRegistry.injectEventPluginOrder(['one', 'two', 'three']);
EventPluginRegistry.injectEventPluginsByName({
one: OnePlugin,
two: TwoPlugin,
});
E | tePlugin = function (properties) {
return Object.assign({extractEvents: function () {}}, properties);
};
});
it('should be able to inject ordering before plugins', () => {
const OnePlugin = createPlugin();
| {
"filepath": "packages/react-native-renderer/src/__tests__/EventPluginRegistry-test.internal.js",
"language": "javascript",
"file_size": 7315,
"cut_index": 716,
"middle_length": 229
} |
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 ReactFabric;
let createReactNativeComponentClass;
let act;
let View;
let Text;
describe('Fabric FragmentRefs', () => {
beforeEach(() => {
jest... | teReactNativeComponentClass('RCTView', () => ({
validAttributes: {nativeID: true},
uiViewClassName: 'RCTView',
}));
Text = createReactNativeComponentClass('RCTText', () => ({
validAttributes: {nativeID: true},
uiViewClassNam | createReactNativeComponentClass =
require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface')
.ReactNativeViewConfigRegistry.register;
({act} = require('internal-test-utils'));
View = crea | {
"filepath": "packages/react-native-renderer/src/__tests__/ReactFabricFragmentRefs-test.internal.js",
"language": "javascript",
"file_size": 3375,
"cut_index": 614,
"middle_length": 229
} |
ay from 'shared/isArray';
import {runWithFiberInDEV} from 'react-reconciler/src/ReactCurrentFiber';
let hasError = false;
let caughtError = null;
export let getFiberCurrentPropsFromNode = null;
export let getInstanceFromNode = null;
export let getNodeFromInstance = null;
export function setComponentTree(
getFiber... | nstanceFromNode.',
);
}
}
}
function validateEventDispatches(event) {
if (__DEV__) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
const listenersIsArr = isArray(dispatch | deImpl;
getNodeFromInstance = getNodeFromInstanceImpl;
if (__DEV__) {
if (!getNodeFromInstance || !getInstanceFromNode) {
console.error(
'Injected ' +
'module is missing getNodeFromInstance or getI | {
"filepath": "packages/react-native-renderer/src/legacy-events/EventPluginUtils.js",
"language": "javascript",
"file_size": 6152,
"cut_index": 716,
"middle_length": 229
} |
oo: true},
uiViewClassName: 'RCTView',
}));
await act(() => {
ReactFabric.render(<View foo="test" />, 1, null, true);
});
expect(nativeFabricUIManager.createNode).toBeCalled();
expect(nativeFabricUIManager.appendChild).not.toBeCalled();
expect(nativeFabricUIManager.completeRoot).toB... | });
expect(nativeFabricUIManager.createNode).toHaveBeenCalledTimes(1);
await act(() => {
ReactFabric.render(<View foo="bar" />, 11, null, true);
});
expect(nativeFabricUIManager.createNode).toHaveBeenCalledTimes(1);
expect( | true},
uiViewClassName: 'RCTView',
}));
const firstNode = {};
nativeFabricUIManager.createNode.mockReturnValue(firstNode);
await act(() => {
ReactFabric.render(<View foo="foo" />, 11, null, true);
| {
"filepath": "packages/react-native-renderer/src/__tests__/ReactFabric-test.internal.js",
"language": "javascript",
"file_size": 47526,
"cut_index": 2151,
"middle_length": 229
} |
= 0; i < arr.length; i++) {
if (indices.indexOf(i) === -1) {
ret.push(arr[i]);
}
}
return ret;
};
/**
* Helper for creating touch test config data.
* @param allTouchHandles
*/
const _touchConfig = function (
topType,
targetNodeHandle,
allTouchHandles,
changedIndices,
eventTarget,
) {
... | ? antiSubsequence(allTouchObjects, changedIndices)
: null;
return {
nativeEvent: touchEvent(
targetNodeHandle,
activeTouchObjects,
changedTouchObjects,
),
topLevelType: topType,
targetInst: getInstanceFro | ? allTouchObjects
: topType === 'topTouchMove'
? allTouchObjects
: topType === 'topTouchEnd'
? antiSubsequence(allTouchObjects, changedIndices)
: topType === 'topTouchCancel'
| {
"filepath": "packages/react-native-renderer/src/__tests__/ResponderEventPlugin-test.internal.js",
"language": "javascript",
"file_size": 50470,
"cut_index": 2151,
"middle_length": 229
} |
startLoggingProfilingEvents,
} from '../SchedulerProfiling';
type Callback = boolean => ?Callback;
type Task = {
id: number,
callback: Callback | null,
priorityLevel: PriorityLevel,
startTime: number,
expirationTime: number,
sortIndex: number,
isQueued?: boolean,
};
// Max 31 bit integer. The max inte... | min heap
var taskQueue: Array<Task> = [];
var timerQueue: Array<Task> = [];
// Incrementing id counter. Used to maintain insertion order.
var taskIdCounter = 1;
var currentTask = null;
var currentPriorityLevel: PriorityLevel = NormalPriority;
// This is |
// Eventually times out
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000;
// Never times out
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;
// Tasks are stored on a | {
"filepath": "packages/scheduler/src/forks/SchedulerMock.js",
"language": "javascript",
"file_size": 18567,
"cut_index": 1331,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
*/
import * as Scheduler from './Scheduler';
import type {Callback, Task} from './Scheduler';
import type {PriorityLevel} from '../SchedulerPriorities';
import typeof * as PriorityLevels from '../SchedulerPrioritie... | Type = {
unstable_ImmediatePriority: PriorityLevels['ImmediatePriority'],
unstable_UserBlockingPriority: PriorityLevels['UserBlockingPriority'],
unstable_NormalPriority: PriorityLevels['NormalPriority'],
unstable_IdlePriority: PriorityLevels['IdleP | and arguments currently supported by the C++ implementation:
// https://github.com/facebook/react-native/blob/main/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp
type NativeScheduler | {
"filepath": "packages/scheduler/src/forks/SchedulerNative.js",
"language": "javascript",
"file_size": 4632,
"cut_index": 614,
"middle_length": 229
} |
import type {PriorityLevel} from '../SchedulerPriorities';
declare class TaskController {
constructor(options?: {priority?: string}): TaskController;
signal: mixed;
abort(): void;
}
type PostTaskPriorityLevel = 'user-blocking' | 'user-visible' | 'background';
type CallbackNode = {
_controller: TaskController... | ative APIs, in case a polyfill overrides them.
const perf = window.performance;
const setTimeout = window.setTimeout;
// Use experimental Chrome Scheduler postTask API.
const scheduler = global.scheduler;
const getCurrentTime: () => DOMHighResTimeStamp = | ePriority,
UserBlockingPriority as unstable_UserBlockingPriority,
NormalPriority as unstable_NormalPriority,
IdlePriority as unstable_IdlePriority,
LowPriority as unstable_LowPriority,
};
// Capture local references to n | {
"filepath": "packages/scheduler/src/forks/SchedulerPostTask.js",
"language": "javascript",
"file_size": 6740,
"cut_index": 716,
"middle_length": 229
} |
ee.
*/
'use strict';
(function (global, factory) {
// eslint-disable-next-line ft-flow/no-unused-expressions
typeof exports === 'object' && typeof module !== 'undefined'
? (module.exports = factory(require('react')))
: typeof define === 'function' && define.amd // eslint-disable-line no-undef
? def... | SERS_THEY_CANNOT_UPGRADE.Scheduler.unstable_scheduleCallback.apply(
this,
arguments
);
}
function unstable_cancelCallback() {
return global.React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE.Scheduler.unstable_ca | INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE.Scheduler.unstable_now.apply(
this,
arguments
);
}
function unstable_scheduleCallback() {
return global.React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_U | {
"filepath": "packages/scheduler/npm/umd/scheduler.development.js",
"language": "javascript",
"file_size": 5182,
"cut_index": 716,
"middle_length": 229
} |
, Array<any>> {
// This initializes a cache of all primitive hooks so that the top
// most stack frames added by calling the primitive hook can be removed.
if (primitiveStackCache === null) {
const cache = new Map<string, Array<any>>();
let readHookLog;
try {
// Use all hooks here to add them to... | rtionEffect(() => {});
Dispatcher.useEffect(() => {});
Dispatcher.useImperativeHandle(undefined, () => null);
Dispatcher.useDebugValue(null);
Dispatcher.useCallback(() => {});
Dispatcher.useTransition();
Dispatcher.useSy | (null);
if (typeof Dispatcher.useCacheRefresh === 'function') {
// This type check is for Flow only.
Dispatcher.useCacheRefresh();
}
Dispatcher.useLayoutEffect(() => {});
Dispatcher.useInse | {
"filepath": "packages/react-debug-tools/src/ReactDebugHooks.js",
"language": "javascript",
"file_size": 42202,
"cut_index": 2151,
"middle_length": 229
} |
let scheduleUpdate;
let scheduleRetry;
let setSuspenseHandler;
let waitForAll;
global.IS_REACT_ACT_ENVIRONMENT = true;
beforeEach(() => {
global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
inject: injected => {
overrideHookState = injected.overrideHookState;
scheduleUpdate = injected.sched... | Utils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
act = require('internal-test-utils').act;
});
it('should support editing useState hooks', async () => {
let setCountFn;
function MyComponent() {
| onCommitFiberUnmount: () => {},
};
jest.resetModules();
React = require('react');
ReactDebugTools = require('react-debug-tools');
ReactTestRenderer = require('react-test-renderer');
const InternalTest | {
"filepath": "packages/react-debug-tools/src/__tests__/ReactDevToolsHooksIntegration-test.js",
"language": "javascript",
"file_size": 10095,
"cut_index": 921,
"middle_length": 229
} |
{
const [state] = React.useState('hello world');
return <div>{state}</div>;
}
const tree = ReactDebugTools.inspectHooks(Foo, {});
expect(normalizeSourceLoc(tree)).toMatchInlineSnapshot(`
[
{
"debugInfo": null,
"hookSource": {
"columnNumber": 0,
... | DebugValue('custom hook label');
return state;
}
function Foo(props) {
const value = useCustom('hello world');
return <div>{value}</div>;
}
const tree = ReactDebugTools.inspectHooks(Foo, {});
if (__DEV__) {
expec | "subHooks": [],
"value": "hello world",
},
]
`);
});
it('should inspect a simple custom hook', () => {
function useCustom(value) {
const [state] = React.useState(value);
React.use | {
"filepath": "packages/react-debug-tools/src/__tests__/ReactHooksInspection-test.js",
"language": "javascript",
"file_size": 24408,
"cut_index": 1331,
"middle_length": 229
} |
er": 0,
},
"id": 1,
"isStateEditable": true,
"name": "State",
"subHooks": [],
"value": "world",
},
]
`);
await act(() => setStateB('world!'));
childFiber = renderer.root.findByType(Foo)._currentFiber();
tree = ReactDebugTools.in... | "value": "Hi",
},
{
"debugInfo": null,
"hookSource": {
"columnNumber": 0,
"fileName": "**",
"functionName": "Foo",
"lineNumber": 0,
},
"id": 1,
| : 0,
"fileName": "**",
"functionName": "Foo",
"lineNumber": 0,
},
"id": 0,
"isStateEditable": true,
"name": "State",
"subHooks": [],
| {
"filepath": "packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js",
"language": "javascript",
"file_size": 73650,
"cut_index": 3790,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment jsdom
*/
'use strict';
let React;
let ReactDOM;
let ReactDOMClient;
let ReactDebugTools;
let act;
function normalizeSourceLoc(tree) {
tree.forEach(node => {
if (node.hookSource) {... | internal-test-utils').act;
ReactDebugTools = require('react-debug-tools');
});
it('should support useFormStatus hook', async () => {
function FormStatus() {
const status = ReactDOM.useFormStatus();
React.useMemo(() => 'memo', []);
| ibe('ReactHooksInspectionIntegration', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
act = require(' | {
"filepath": "packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegrationDOM-test.js",
"language": "javascript",
"file_size": 3784,
"cut_index": 614,
"middle_length": 229
} |
from 'react';
import {Component} from 'react';
import {findDOMNode} from 'react-dom';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {store} from '../store';
import ThemeContext from './shared/ThemeContext';
import Clock from './shared/Clock';
store.subscribe(() => {
console.log... | <h4 style={{color: theme}}>
This component is rendered by the nested React ({React.version}).
</h4>
<Clock />
<p>
Counter: {this.props.counter}{' '}
<button onClick={() => thi | APIs.
findDOMNode(this);
}
render() {
return (
<ThemeContext.Consumer>
{theme => (
<div style={{border: '1px dashed black', padding: 20}}>
<h3>src/legacy/Greeting.js</h3>
| {
"filepath": "fixtures/nesting/src/legacy/Greeting.js",
"language": "javascript",
"file_size": 1378,
"cut_index": 524,
"middle_length": 229
} |
sable react/jsx-pascal-case */
import React from 'react';
import ReactDOM from 'react-dom';
import ThemeContext from './shared/ThemeContext';
// Note: this is a semi-private API, but it's ok to use it
// if we never inspect the values, and only pass them through.
import {__RouterContext} from 'react-router';
import {... | ort {ReactReduxContext} from 'react-redux'
and render <ReactReduxContext.Provider value={context.reactRedux}>.
*/}
<Provider store={context.reactRedux.store}>{children}</Provider>
</__RouterContext.Provider>
</ThemeConte | turn (
<ThemeContext.Provider value={context.theme}>
<__RouterContext.Provider value={context.router}>
{/*
If we used the newer react-redux@7.x in the legacy/package.json,
we woud instead imp | {
"filepath": "fixtures/nesting/src/legacy/createLegacyRoot.js",
"language": "javascript",
"file_size": 1361,
"cut_index": 524,
"middle_length": 229
} |
from 'react';
import {connect} from 'react-redux';
import ThemeContext from './shared/ThemeContext';
import lazyLegacyRoot from './lazyLegacyRoot';
// Lazy-load a component from the bundle using legacy React.
const Greeting = lazyLegacyRoot(() => import('../legacy/Greeting'));
function AboutPage({counter, dispatch})... | <br />
<p>
Counter: {counter}{' '}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</p>
</>
);
}
function mapStateToProps(state) {
return {counter: state};
}
export default connect(mapStateToProps)(A | React.version}).
</h3>
<Greeting />
| {
"filepath": "fixtures/nesting/src/modern/AboutPage.js",
"language": "javascript",
"file_size": 878,
"cut_index": 559,
"middle_length": 52
} |
from 'react';
import {useState, Suspense} from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';
import ThemeContext from './shared/ThemeContext';
export default function App() {
const [theme, setTheme] = useState('slateg... | minHeight: 300,
}}>
<button onClick={handleToggleClick}>Toggle Theme Context</button>
<br />
<Suspense fallback={<Spinner />}>
<Switch>
<Route path="/about">
< | ThemeContext.Provider value={theme}>
<div style={{fontFamily: 'sans-serif'}}>
<div
style={{
margin: 20,
padding: 20,
border: '1px solid black',
| {
"filepath": "fixtures/nesting/src/modern/App.js",
"language": "javascript",
"file_size": 1314,
"cut_index": 524,
"middle_length": 229
} |
emo, useRef, useState, useLayoutEffect} from 'react';
import {__RouterContext} from 'react-router';
import {ReactReduxContext} from 'react-redux';
import ThemeContext from './shared/ThemeContext';
let rendererModule = {
status: 'pending',
promise: null,
result: null,
};
export default function lazyLegacyRoot(g... | ull);
// Populate every contexts we want the legacy subtree to see.
// Then in src/legacy/createLegacyRoot we will apply them.
const theme = useContext(ThemeContext);
const router = useContext(__RouterContext);
const reactRedux = useCo | rendererModule,
() => import('../legacy/createLegacyRoot')
).default;
const Component = readModule(componentModule, getLegacyComponent).default;
const containerRef = useRef(null);
const rootRef = useRef(n | {
"filepath": "fixtures/nesting/src/modern/lazyLegacyRoot.js",
"language": "javascript",
"file_size": 2588,
"cut_index": 563,
"middle_length": 229
} |
=== void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
c... |
throw new TypeError('@@toPrimitive must return a primitive value.');
}
return ('string' === r ? String : Number)(t);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype | eof i ? i : i + '';
}
function _toPrimitive(t, r) {
if ('object' != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || 'default');
if ('object' != typeof i) return i; | {
"filepath": "fixtures/stacks/BabelClasses-compiled.js",
"language": "javascript",
"file_size": 2570,
"cut_index": 563,
"middle_length": 229
} |
lClass, BabelClassWithFields} from './BabelClasses-compiled.js';
import {
Throw,
Component,
DisplayName,
NativeClass,
FrozenClass,
} from './Components.js';
const x = React.createElement;
class ErrorBoundary extends React.Component {
static getDerivedStateFromError(error) {
return {
error: error... | s.props.children;
}
}
export default function Example() {
let state = React.useState(false);
return x(
ErrorBoundary,
null,
x(
DisplayName,
null,
x(
NativeClass,
null,
x(
FrozenClass,
|
render() {
if (this.state && this.state.error) {
return x(
'div',
null,
x('h3', null, this.state.error.message),
x('pre', null, this.state.componentStack)
);
}
return thi | {
"filepath": "fixtures/stacks/Example.js",
"language": "javascript",
"file_size": 1355,
"cut_index": 524,
"middle_length": 229
} |
ictoryBar,
VictoryTheme,
VictoryScatter,
VictoryStack,
} from 'victory';
const colors = ['#fff489', '#fa57c1', '#b166cc', '#7572ff', '#69a6f9'];
export default class Charts extends PureComponent {
render() {
const streamData = this.props.data;
return (
<div>
<div style={{display: 'flex'}... | ryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
dependentAxis
/>
<VictoryScatter
data={streamData[0]}
siz | or: '#222',
},
}}>
<VictoryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
/>
<Victo | {
"filepath": "fixtures/concurrent/time-slicing/src/Charts.js",
"language": "javascript",
"file_size": 3201,
"cut_index": 614,
"middle_length": 229
} |
t';
const SPEED = 0.003 / Math.PI;
const FRAMES = 10;
export default class Clock extends PureComponent {
faceRef = createRef();
arcGroupRef = createRef();
clockHandRef = createRef();
frame = null;
hitCounter = 0;
rotation = 0;
t0 = Date.now();
arcs = [];
animate = () => {
const now = Date.now()... | ;
const bigArc = SPEED * td < Math.PI ? '0' : '1';
const path = `M${tx} ${ty}A${r} ${r} 0 ${bigArc} 0 ${lx} ${ly}L155 155`;
const hue = 120 - Math.min(120, td / 4);
const colour = `hsl(${hue}, 100%, ${60 - i * (30 / FRAMES)} | ;
if (this.arcs.length > FRAMES) {
this.arcs.forEach(({rotation, td}, i) => {
lx = tx;
ly = ty;
const r = 145;
tx = 155 + r * Math.cos(rotation);
ty = 155 + r * Math.sin(rotation) | {
"filepath": "fixtures/concurrent/time-slicing/src/Clock.js",
"language": "javascript",
"file_size": 2838,
"cut_index": 563,
"middle_length": 229
} |
t';
import _ from 'lodash';
import Charts from './Charts';
import Clock from './Clock';
import './index.css';
let cachedData = new Map();
class App extends PureComponent {
state = {
value: '',
strategy: 'sync',
showDemo: true,
showClock: false,
};
// Random data for the chart
getStreamData(in... | })
);
cachedData.set(input, data);
return data;
}
componentDidMount() {
window.addEventListener('keydown', e => {
if (e.key.toLowerCase() === '?') {
e.preventDefault();
this.setState(state => ({
showClo | cation.search.slice(1), 10) / 100) * 25 || 25;
const data = _.range(5).map(t =>
_.range(complexity * multiplier).map((j, i) => {
return {
x: j,
y: (t + 1) * _.random(0, 255),
};
| {
"filepath": "fixtures/concurrent/time-slicing/src/index.js",
"language": "javascript",
"file_size": 3674,
"cut_index": 614,
"middle_length": 229
} |
t,
useEffect,
useState,
addTransitionType,
} from 'react';
import Chrome from './Chrome.js';
import Page from './Page.js';
const enableNavigationAPI = typeof navigation === 'object';
export default function App({assets, initialURL}) {
const [routerState, setRouterState] = useState({
pendingNav: () => {},... | 'navigate', event => {
if (!event.canIntercept) {
return;
}
const navigationType = event.navigationType;
const previousIndex = window.navigation.currentEntry.index;
const newURL = new URL(event.destination. |
url,
pendingNav() {
window.history.pushState({}, '', url);
},
});
});
}
}
useEffect(() => {
if (enableNavigationAPI) {
window.navigation.addEventListener( | {
"filepath": "fixtures/view-transition/src/components/App.js",
"language": "javascript",
"file_size": 2742,
"cut_index": 563,
"middle_length": 229
} |
, {Component} from 'react';
import './Chrome.css';
export default class Chrome extends Component {
render() {
const assets = this.props.assets;
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
... | wap"
rel="stylesheet"
/>
<title>{this.props.title}</title>
</head>
<body>
<noscript
dangerouslySetInnerHTML={{
__html: `<b>Enable JavaScript to run this app.</b>`,
| <link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin=""
/>
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=s | {
"filepath": "fixtures/view-transition/src/components/Chrome.js",
"language": "javascript",
"file_size": 1257,
"cut_index": 524,
"middle_length": 229
} |
;
import {createPortal} from 'react-dom';
import SwipeRecognizer from './SwipeRecognizer.js';
import './Page.css';
import transitions from './Transitions.module.css';
import NestedReveal from './NestedReveal.js';
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const a = (
... | be properly supported.
useInsertionEffect(() => {
const style = document.createElement('style');
style.textContent = `
.roboto-font {
font-family: "Roboto", serif;
font-optical-sizing: auto;
font-weight: 100;
| function Component() {
// Test inserting fonts with style tags using useInsertionEffect. This is not recommended but
// used to test that gestures etc works with useInsertionEffect so that stylesheet based
// libraries can | {
"filepath": "fixtures/view-transition/src/components/Page.js",
"language": "javascript",
"file_size": 9046,
"cut_index": 716,
"middle_length": 229
} |
ine';
import TouchPanTimeline from 'animation-timelines/touch-pan-timeline';
const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent;
const isSafariMobile =
ua.indexOf('Safari') !== -1 &&
(ua.indexOf('iPhone') !== -1 ||
ua.indexOf('iPad') !== -1 ||
ua.indexOf('iPod') !== -1);
// Example of ... | t scrollRef = useRef(null);
const activeGesture = useRef(null);
const touchTimeline = useRef(null);
function onTouchStart(event) {
if (!isSafariMobile && typeof ScrollTimeline === 'function') {
// If not Safari and native ScrollTimeline is | export default function SwipeRecognizer({
action,
children,
direction,
gesture,
}) {
if (direction == null) {
direction = 'left';
}
const axis = direction === 'left' || direction === 'right' ? 'x' : 'y';
cons | {
"filepath": "fixtures/view-transition/src/components/SwipeRecognizer.js",
"language": "javascript",
"file_size": 7158,
"cut_index": 716,
"middle_length": 229
} |
/core';
const babelOptions = {
babelrc: false,
ignore: [/\/(build|node_modules)\//],
plugins: [
'@babel/plugin-syntax-import-meta',
'@babel/plugin-transform-react-jsx',
],
};
export async function load(url, context, defaultLoad) {
if (url.endsWith('.css')) {
return {source: 'export default {}', ... | source: Buffer.from(result.source).toString('utf8'),
format: 'module',
};
}
return {source: newResult.code, format: 'module'};
}
return defaultLoad(url, context, defaultLoad);
}
async function babelTransformSource(source, con | .assign({filename: url}, babelOptions);
const newResult = await babel.transformAsync(result.source, opt);
if (!newResult) {
if (typeof result.source === 'string') {
return result;
}
return {
| {
"filepath": "fixtures/view-transition/loader/server.js",
"language": "javascript",
"file_size": 1634,
"cut_index": 537,
"middle_length": 229
} |
unstable_ImmediatePriority;
UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
NormalPriority = Scheduler.unstable_NormalPriority;
LowPriority = Scheduler.unstable_LowPriority;
IdlePriority = Scheduler.unstable_IdlePriority;
scheduleCallback = Scheduler.unstable_scheduleCallback;
ca... |
waitForPaint = InternalTestUtils.waitForPaint;
});
it('flushes work incrementally', async () => {
scheduleCallback(NormalPriority, () => Scheduler.log('A'));
scheduleCallback(NormalPriority, () => Scheduler.log('B'));
scheduleCallback | = Scheduler.unstable_shouldYield;
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
assertLog = InternalTestUtils.assertLog;
waitFor = InternalTestUtils.waitFor; | {
"filepath": "packages/scheduler/src/__tests__/SchedulerMock-test.js",
"language": "javascript",
"file_size": 22007,
"cut_index": 1331,
"middle_length": 229
} |
lPriority;
let LowPriority;
let IdlePriority;
let scheduleCallback;
let cancelCallback;
// let wrapCallback;
// let getCurrentPriorityLevel;
// let shouldYield;
let waitForAll;
let waitFor;
let waitForThrow;
function priorityLevelToString(priorityLevel) {
switch (priorityLevel) {
case ImmediatePriority:
re... | pply when profiling is on
it('profiling APIs are not available', () => {
Scheduler = require('scheduler');
expect(Scheduler.unstable_Profiling).toBe(null);
});
return;
}
beforeEach(() => {
jest.resetModules();
jest.mock | return 'Idle';
default:
return null;
}
}
describe('Scheduler', () => {
const {enableProfiling} = require('scheduler/src/SchedulerFeatureFlags');
if (!enableProfiling) {
// The tests in this suite only a | {
"filepath": "packages/scheduler/src/__tests__/SchedulerProfiling-test.js",
"language": "javascript",
"file_size": 16345,
"cut_index": 921,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let Scheduler;
let scheduleCallback;
let ImmediatePriority;
let UserBlockingPriority;
let NormalPriority;
describe('SchedulerNoDOM', () => {
// Scheduler falls b... | Priority = Scheduler.unstable_UserBlockingPriority;
NormalPriority = Scheduler.unstable_NormalPriority;
});
it('runAllTimers flushes all scheduled callbacks', () => {
const log = [];
scheduleCallback(NormalPriority, () => {
log.push( | .useFakeTimers();
delete global.setImmediate;
delete global.MessageChannel;
jest.unmock('scheduler');
Scheduler = require('scheduler');
scheduleCallback = Scheduler.unstable_scheduleCallback;
UserBlocking | {
"filepath": "packages/scheduler/src/__tests__/SchedulerSetTimeout-test.js",
"language": "javascript",
"file_size": 3326,
"cut_index": 614,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
*/
'use strict';
import {type ViewConfig} from './ReactNativeTypes';
// Event configs
export const customBubblingEventTypes = {};
export const customDirectEventTypes = {};
const viewConfigCallbacks = new M... | d bubbling: ${topLevelType}`,
);
}
}
}
}
if (bubblingEventTypes != null) {
for (const topLevelType in bubblingEventTypes) {
if (customBubblingEventTypes[topLevelType] == null) {
customBubblingEventTypes[to | EventTypes != null && directEventTypes != null) {
for (const topLevelType in directEventTypes) {
if (bubblingEventTypes[topLevelType] != null) {
throw new Error(
`Event cannot be both direct an | {
"filepath": "packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/ReactNativeViewConfigRegistry.js",
"language": "javascript",
"file_size": 3253,
"cut_index": 614,
"middle_length": 229
} |
* @nolint
* @flow strict
*/
import type {
// $FlowFixMe[nonstrict-import] TODO(@rubennorte)
HostInstance as PublicInstance,
// $FlowFixMe[nonstrict-import] TODO(@rubennorte)
MeasureOnSuccessCallback,
// $FlowFixMe[nonstrict-import] TODO(@rubennorte)
PublicRootInstance,
// $FlowFixMe[nonstrict-import] T... | , $FlowFixMe>;
export type AttributeConfiguration = $ReadOnly<{
[propName: string]: AnyAttributeType | void,
style?: $ReadOnly<{
[propName: string]: AnyAttributeType,
...
}>,
...
}>;
export type ViewConfig = $ReadOnly<{
Commands?: $Read | olean,
process?: (arg1: V) => T,
}>;
// We either force that `diff` and `process` always use mixed,
// or we allow them to define specific types and use this hack
export type AnyAttributeType = AttributeType<$FlowFixMe | {
"filepath": "packages/react-native-renderer/src/ReactNativeTypes.js",
"language": "javascript",
"file_size": 5986,
"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.
*
* @flow
*/
import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
import type {
DispatchConfig,
ReactSyntheticEve... | Event> = {
eventTypes: EventTypes,
extractEvents: (
topLevelType: TopLevelType,
targetInst: null | Fiber,
nativeTarget: NativeEvent,
nativeEventTarget: null | EventTarget,
eventSystemFlags?: number,
container?: null | EventTarge | objects with arbitrary properties,
// not DOM Event class instances.
export type AnyNativeEvent = {[string]: mixed};
export type PluginName = string;
export type EventSystemFlags = number;
export type LegacyPluginModule<Native | {
"filepath": "packages/react-native-renderer/src/legacy-events/PluginModuleType.js",
"language": "javascript",
"file_size": 1064,
"cut_index": 515,
"middle_length": 229
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* Flow type for SyntheticEvent class that includes private properties
* @flow
*/
import type {Fiber} from 'react-reconciler/src/ReactInter... | n,
},
registrationName?: string,
customEvent: true,
};
export type ReactSyntheticEvent = {
dispatchConfig: DispatchConfig | CustomDispatchConfig,
getPooled: (
dispatchConfig: DispatchConfig | CustomDispatchConfig,
targetInst: Fiber,
| ,
captured: null | string,
skipBubbling?: ?boolean,
},
registrationName?: string,
};
export type CustomDispatchConfig = {
phasedRegistrationNames: {
bubbled: null,
captured: null,
skipBubbling?: ?boolea | {
"filepath": "packages/react-native-renderer/src/legacy-events/ReactSyntheticEventType.js",
"language": "javascript",
"file_size": 1359,
"cut_index": 524,
"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.
*
* @flow
*/
export const TOP_TOUCH_START = 'topTouchStart';
export const TOP_TOUCH_MOVE = 'topTouchMove';
export const TOP_TOUCH... | d): boolean {
return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL;
}
export const startDependencies = [TOP_TOUCH_START];
export const moveDependencies = [TOP_TOUCH_MOVE];
export const endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH | tish(topLevelType: mixed): boolean {
return topLevelType === TOP_TOUCH_START;
}
export function isMoveish(topLevelType: mixed): boolean {
return topLevelType === TOP_TOUCH_MOVE;
}
export function isEndish(topLevelType: mixe | {
"filepath": "packages/react-native-renderer/src/legacy-events/ResponderTopLevelEventTypes.js",
"language": "javascript",
"file_size": 1004,
"cut_index": 512,
"middle_length": 229
} |
import {isStartish, isMoveish, isEndish} from './ResponderTopLevelEventTypes';
/**
* Tracks the position and time of each active touch by `touch.identifier`. We
* should typically only see IDs in the range of 1-20 because IDs get recycled
* when touches end and start again.
*/
type TouchRecord = {
touchActive: b... | ts location. This prevents
// us having to loop through all of the touches all the time in the most
// common case.
indexOfSingleActiveTouch: -1,
mostRecentTimeStamp: 0,
};
type Touch = {
identifier: ?number,
pageX: number,
pageY: number,
| eY: number,
previousTimeStamp: number,
};
const MAX_TOUCH_BANK = 20;
const touchBank: Array<TouchRecord> = [];
const touchHistory = {
touchBank,
numberActiveTouches: 0,
// If there is only one active touch, we remember i | {
"filepath": "packages/react-native-renderer/src/legacy-events/ResponderTouchHistoryStore.js",
"language": "javascript",
"file_size": 7422,
"cut_index": 716,
"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.
*
* @flow
*/
import isArray from 'shared/isArray';
/**
* Accumulates items that must not be null or undefined into the first one. This
* is used to con... | t: ?(Array<T> | T),
next: T | Array<T>,
): T | Array<T> {
if (next == null) {
throw new Error('Accumulated items must not be null or undefined.');
}
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.co | back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto<T>(
curren | {
"filepath": "packages/react-native-renderer/src/legacy-events/accumulateInto.js",
"language": "javascript",
"file_size": 1804,
"cut_index": 537,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as React from 'react';
import ReactVersion from 'shared/ReactVersion';
import {LegacyRoot, ConcurrentRoot} from 'react-reconciler/src/ReactRootTags';
import {
createContainer,
updateContainerSync,
injectIntoDevTools... | ction defaultOnDefaultTransitionIndicator() {
// Noop
}
Mode.setCurrent(
// Change to 'art/modes/dom' for easier debugging via SVG
FastNoSideEffects,
);
/** Declarative fill-type objects; API design not finalized */
const slice = Array.prototype.s | ';
import Mode from 'art/modes/current';
import FastNoSideEffects from 'art/modes/fast-noSideEffects';
import {disableLegacyMode} from 'shared/ReactFeatureFlags';
import {TYPES, childrenAsString} from './ReactARTInternals';
fun | {
"filepath": "packages/react-art/src/ReactART.js",
"language": "javascript",
"file_size": 4854,
"cut_index": 614,
"middle_length": 229
} |
eactARTInternals';
import {
DefaultEventPriority,
NoEventPriority,
} from 'react-reconciler/src/ReactEventPriorities';
import type {ReactContext} from 'shared/ReactTypes';
import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererP... | listeners) {
instance._listeners = {};
instance._subscriptions = {};
}
instance._listeners[type] = listener;
if (listener) {
if (!instance._subscriptions[type]) {
instance._subscriptions[type] = instance.subscribe(
type,
| TransitionStatus = mixed;
/** Helper Methods */
function addEventListeners(instance, type, listener) {
// We need to explicitly unregister before unmount.
// For this reason we need to track subscriptions.
if (!instance._ | {
"filepath": "packages/react-art/src/ReactFiberConfigART.js",
"language": "javascript",
"file_size": 15307,
"cut_index": 921,
"middle_length": 229
} |
mport ARTCurrentMode from 'art/modes/current';
// Since these are default exports, we need to import them using ESM.
// Since they must be on top, we need to import this before ReactDOM.
import Circle from 'react-art/Circle';
import Rectangle from 'react-art/Rectangle';
import Wedge from 'react-art/Wedge';
const {act}... | (domNode.nodeName).toBe(expectedStructure.nodeName);
for (const prop in expectedStructure) {
if (!expectedStructure.hasOwnProperty(prop)) {
continue;
}
if (prop !== 'nodeName' && prop !== 'children') {
if (expectedStructure[prop] | ient = require('react-dom/client');
let Group;
let Shape;
let Surface;
let TestComponent;
let groupRef;
const Missing = {};
function testDOMNodeStructure(domNode, expectedStructure) {
expect(domNode).toBeDefined();
expect | {
"filepath": "packages/react-art/src/__tests__/ReactART-test.js",
"language": "javascript",
"file_size": 13873,
"cut_index": 921,
"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.
* @typechecks
*
* Example usage:
* <Rectangle
* width={50}
* height={50}
* stroke="green"
* fill="blue"
* />
*
* Additional optional properties:
* (Number) radius... | r ReactART
* components, it must be used in a <Surface>.
*/
var Rectangle = createReactClass({
displayName: 'Rectangle',
render: function render() {
var width = this.props.width;
var height = this.props.height;
var radius = this.props.ra | 'react');
var ReactART = require('react-art');
var createReactClass = require('create-react-class');
var Shape = ReactART.Shape;
var Path = ReactART.Path;
/**
* Rectangle is a React component for drawing rectangles. Like othe | {
"filepath": "packages/react-art/npm/Rectangle.js",
"language": "javascript",
"file_size": 2789,
"cut_index": 563,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {PriorityLevel} from './SchedulerPriorities';
import {enableProfiling} from './SchedulerFeatureFlags';
let runIdCounter: number = 0;
let mainThreadIdCounter: number = 0;
// Bytes per element is 4
const IN... | n logEvent(entries: Array<number | PriorityLevel>) {
if (eventLog !== null) {
const offset = eventLogIndex;
eventLogIndex += entries.length;
if (eventLogIndex + 1 > eventLogSize) {
eventLogSize *= 2;
if (eventLogSize > MAX_EVENT_L | nst TaskStartEvent = 1;
const TaskCompleteEvent = 2;
const TaskErrorEvent = 3;
const TaskCancelEvent = 4;
const TaskRunEvent = 5;
const TaskYieldEvent = 6;
const SchedulerSuspendEvent = 7;
const SchedulerResumeEvent = 8;
functio | {
"filepath": "packages/scheduler/src/SchedulerProfiling.js",
"language": "javascript",
"file_size": 4206,
"cut_index": 614,
"middle_length": 229
} |
ulerFeatureFlags;
// The Scheduler implementation uses browser APIs like `MessageChannel` and
// `setTimeout` to schedule work on the main thread. Most of our tests treat
// these as implementation details; however, the sequence and timing of these
// APIs are not precisely specified, and can vary across browsers.
//
... | eduler');
performance = global.performance;
Scheduler = require('scheduler');
cancelCallback = Scheduler.unstable_cancelCallback;
scheduleCallback = Scheduler.unstable_scheduleCallback;
NormalPriority = Scheduler.unstable_NormalPriorit | ntation. It
// assumes as little as possible about the order and timing of events.
describe('SchedulerBrowser', () => {
beforeEach(() => {
jest.resetModules();
runtime = installMockBrowserRuntime();
jest.unmock('sch | {
"filepath": "packages/scheduler/src/__tests__/Scheduler-test.js",
"language": "javascript",
"file_size": 9698,
"cut_index": 921,
"middle_length": 229
} |
eout,
enableRequestPaint,
enableAlwaysYieldScheduler,
} from '../SchedulerFeatureFlags';
import {push, pop, peek} from '../SchedulerMinHeap';
// TODO: Use symbols?
import {
ImmediatePriority,
UserBlockingPriority,
NormalPriority,
LowPriority,
IdlePriority,
} from '../SchedulerPriorities';
import {
mar... |
expirationTime: number,
sortIndex: number,
isQueued?: boolean,
};
let getCurrentTime: () => number | DOMHighResTimeStamp;
const hasPerformanceNow =
// $FlowFixMe[method-unbinding]
typeof performance === 'object' && typeof performance.now === 'f | artLoggingProfilingEvents,
} from '../SchedulerProfiling';
export type Callback = boolean => ?Callback;
export opaque type Task = {
id: number,
callback: Callback | null,
priorityLevel: PriorityLevel,
startTime: number, | {
"filepath": "packages/scheduler/src/forks/Scheduler.js",
"language": "javascript",
"file_size": 17324,
"cut_index": 921,
"middle_length": 229
} |
nder 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 createReactNativeComponentClass;
describe('ReactNativeError', () => {
beforeEach(() => {
jest.resetModules();
createReactNativeComponentClas... | try {
createReactNativeComponentClass('View', null);
} catch (e) {
throw new Error(e.toString());
}
}).toThrow(
'View config getter callback for component `View` must be a function (received `null`)',
);
});
} | tion getter is used', () => {
expect(() => {
| {
"filepath": "packages/react-native-renderer/src/__tests__/ReactNativeError-test.internal.js",
"language": "javascript",
"file_size": 917,
"cut_index": 606,
"middle_length": 52
} |
chAccumulated from './forEachAccumulated';
import {HostComponent} from 'react-reconciler/src/ReactWorkTags';
/**
* Instance of element that should respond to touch/move types of interactions,
* as indicated explicitly by relevant callbacks.
*/
let responderInst = null;
/**
* Count of current touches. A textInput ... | tResponderInst,
blockHostResponder,
);
}
}
const eventTypes = {
/**
* On a `touchStart`/`mouseDown`, is it desired that this element become the
* responder?
*/
startShouldSetResponder: {
phasedRegistrationNames: {
bubble | onst oldResponderInst = responderInst;
responderInst = nextResponderInst;
if (ResponderEventPlugin.GlobalResponderHandler !== null) {
ResponderEventPlugin.GlobalResponderHandler.onChange(
oldResponderInst,
nex | {
"filepath": "packages/react-native-renderer/src/legacy-events/ResponderEventPlugin.js",
"language": "javascript",
"file_size": 29469,
"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.
*
* @flow
*/
import isArray from 'shared/isArray';
/**
* Accumulates items that must not be null or undefined.
*
* This is used to ... | certain that x is an Array (x could be a string with concat method).
if (isArray(current)) {
// $FlowFixMe[incompatible-use] `isArray` does not ensure array is mutable
return current.concat(next);
}
if (isArray(next)) {
/* $FlowFixMe[in | > {
if (next == null) {
throw new Error('Accumulated items must not be null or undefined.');
}
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// | {
"filepath": "packages/react-native-renderer/src/legacy-events/accumulate.js",
"language": "javascript",
"file_size": 1227,
"cut_index": 518,
"middle_length": 229
} |
ource code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allow... | Scope used as `this` in a callback.
*/
function forEachAccumulated<T>(
arr: ?(Array<T> | T),
cb: (elem: T) => void,
scope: ?any,
) {
if (Array.isArray(arr)) {
// $FlowFixMe[incompatible-call] if `T` is an array, `cb` cannot be called
arr.f | each element or a collection.
* @param {?} [scope] | {
"filepath": "packages/react-native-renderer/src/legacy-events/forEachAccumulated.js",
"language": "javascript",
"file_size": 996,
"cut_index": 582,
"middle_length": 52
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
* @typechecks
*
* Example usage:
* <Wedge
* outerRadius={50}
* startAngle={0}
* endAngle={360}
* fill="blue"
* />
*
* Additional optional property:
* (Int) innerRadius
*
*/
'use strict';
var assign = Object.as... | nsPerDegree: Math.PI / 180,
/**
* _degreesToRadians(degrees)
*
* Helper function to convert degrees to radians
*
* @param {number} degrees
* @return {number}
*/
_degreesToRadians: function _degreesToRadians(degrees) {
if (degr | edge is a React component for drawing circles, wedges and arcs. Like other
* ReactART components, it must be used in a <Surface>.
*/
var Wedge = createReactClass({
displayName: 'Wedge',
circleRadians: Math.PI * 2,
radia | {
"filepath": "packages/react-art/npm/Wedge.js",
"language": "javascript",
"file_size": 4713,
"cut_index": 614,
"middle_length": 229
} |
atePriority;
let NormalPriority;
let UserBlockingPriority;
let LowPriority;
let IdlePriority;
let shouldYield;
// The Scheduler postTask implementation uses a new postTask browser API to
// schedule work on the main thread. This test suite mocks all browser methods
// used in our implementation. It assumes as little a... | eCallback = Scheduler.unstable_scheduleCallback;
ImmediatePriority = Scheduler.unstable_ImmediatePriority;
UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
NormalPriority = Scheduler.unstable_NormalPriority;
LowPriority = Sch | l('scheduler/unstable_post_task'),
);
runtime = installMockBrowserRuntime();
performance = window.performance;
Scheduler = require('scheduler');
cancelCallback = Scheduler.unstable_cancelCallback;
schedul | {
"filepath": "packages/scheduler/src/__tests__/SchedulerPostTask-test.js",
"language": "javascript",
"file_size": 11430,
"cut_index": 921,
"middle_length": 229
} |
ct-core
* @jest-environment node
*/
'use strict';
let Scheduler;
let runtime;
let performance;
let cancelCallback;
let scheduleCallback;
let NormalPriority;
let UserBlockingPriority;
// The Scheduler implementation uses browser APIs like `MessageChannel` and
// `setTimeout` to schedule work on the main thread. Mos... | and timing of events.
describe('SchedulerDOMSetImmediate', () => {
beforeEach(() => {
jest.resetModules();
runtime = installMockBrowserRuntime();
jest.unmock('scheduler');
performance = global.performance;
Scheduler = require('sched | ns, we need the ability to simulate specific edge cases
// that we may encounter in various browsers.
//
// This test suite mocks all browser methods used in our implementation. It
// assumes as little as possible about the order | {
"filepath": "packages/scheduler/src/__tests__/SchedulerSetImmediate-test.js",
"language": "javascript",
"file_size": 8839,
"cut_index": 716,
"middle_length": 229
} |
ource code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export type RNTopLevelEventType =
| 'topMouseDown'
| 'topMouseMove'
| 'topMouseUp'
| 'topScroll'
| 'topSelectionChange'
| 'topTouchCancel'
| 'topTouchEnd'
| 'topTouchMove... | ss these methods.)
export function unsafeCastStringToDOMTopLevelType(
topLevelType: string,
): DOMTopLevelEventType {
return topLevelType;
}
export function unsafeCastDOMTopLevelTypeToString(
topLevelType: DOMTopLevelEventType,
): string {
return | M.
// (It is the only module that is allowed to acce | {
"filepath": "packages/react-native-renderer/src/legacy-events/TopLevelEventTypes.js",
"language": "javascript",
"file_size": 979,
"cut_index": 582,
"middle_length": 52
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
*/
type Heap<T: Node> = Array<T>;
type Node = {
id: number,
sortIndex: number,
...
};
export function push<T: Node>(heap: Heap<T>, node: T): void {
const ... | $FlowFixMe[incompatible-call]
siftDown(heap, last, 0);
}
return first;
}
function siftUp<T: Node>(heap: Heap<T>, node: T, i: number): void {
let index = i;
while (index > 0) {
const parentIndex = (index - 1) >>> 1;
const parent = heap[ | pop<T: Node>(heap: Heap<T>): T | null {
if (heap.length === 0) {
return null;
}
const first = heap[0];
const last = heap.pop();
if (last !== first) {
// $FlowFixMe[incompatible-type]
heap[0] = last;
// | {
"filepath": "packages/scheduler/src/SchedulerMinHeap.js",
"language": "javascript",
"file_size": 2418,
"cut_index": 563,
"middle_length": 229
} |
eof performance === 'object' &&
performance !== null &&
typeof performance.now === 'function'
) {
currentTimeStamp = () => performance.now();
} else {
currentTimeStamp = () => Date.now();
}
return currentTimeStamp();
};
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
... | True() {
return true;
}
function functionThatReturnsFalse() {
return false;
}
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling | e: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || event.timestamp || currentTimeStamp();
},
defaultPrevented: null,
isTrusted: null,
};
function functionThatReturns | {
"filepath": "packages/react-native-renderer/src/legacy-events/SyntheticEvent.js",
"language": "javascript",
"file_size": 9652,
"cut_index": 921,
"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.
*/
// Used as a way to call batchedUpdates when we don't have a reference to
// the renderer. Such as when we're dispatching events or if third party
// lib... | export function batchedUpdates(fn, bookkeeping) {
if (isInsideEventHandler) {
// If we are currently inside another batch, we need to wait until it
// fully completes before restoring state.
return fn(bookkeeping);
}
isInsideEventHandler | chronous work.
// Defaults
let batchedUpdatesImpl = function (fn, bookkeeping) {
return fn(bookkeeping);
};
let discreteUpdatesImpl = function (fn, a, b, c, d) {
return fn(a, b, c, d);
};
let isInsideEventHandler = false;
| {
"filepath": "packages/react-native-renderer/src/legacy-events/ReactGenericBatching.js",
"language": "javascript",
"file_size": 1595,
"cut_index": 537,
"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.
* @typechecks
*
* Example usage:
* <Circle
* radius={10}
* stroke="green"
* strokeWidth={3}
* fill="blue"
* />
*
*/... | ction render() {
var radius = this.props.radius;
var path = Path()
.moveTo(0, -radius)
.arc(0, radius * 2, radius)
.arc(0, radius * -2, radius)
.close();
return React.createElement(Shape, assign({}, this.props, {d: path | ;
var Shape = ReactART.Shape;
/**
* Circle is a React component for drawing circles. Like other ReactART
* components, it must be used in a <Surface>.
*/
var Circle = createReactClass({
displayName: 'Circle',
render: fun | {
"filepath": "packages/react-art/npm/Circle.js",
"language": "javascript",
"file_size": 1038,
"cut_index": 513,
"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.
* @flow
*/
import type {ReactSyntheticEvent} from './ReactSyntheticEventType';
import accumulateInto from './accumulateInto';
import forEachAccumulated fro... | ent Synthetic event to be dispatched.
* @private
*/
function executeDispatchesAndRelease(event: ReactSyntheticEvent) {
if (event) {
executeDispatchesInOrder(event);
if (!event.isPersistent()) {
event.constructor.release(event);
}
} | iting to have their dispatches executed.
*/
let eventQueue: ?(Array<ReactSyntheticEvent> | ReactSyntheticEvent) = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} ev | {
"filepath": "packages/react-native-renderer/src/legacy-events/EventBatching.js",
"language": "javascript",
"file_size": 1971,
"cut_index": 537,
"middle_length": 229
} |
ent, commentSource}) {
const currentUserID = comment.viewer.id;
const environment = RelayEnvironment.forUser(currentUserID);
const commentID = nullthrows(comment.id);
useEffect(() => {
const subscription = SubscriptionCounter.subscribeOnce(
`StoreSubscription_${commentID}`,
() =>
StoreSu... | }
function UseEffectWithEmptyDependencies() {
useEffect(() => {
const local = {};
console.log(local);
}, []);
}
// OK because `props` wasn't defined.
function ComponentWithNoPropsDefined() {
useEffect(() => {
console.log(props.foo);
}, | cription.dispose();
}, [commentID, commentSource, currentUserID, environment]);
}
// Valid because no dependencies
function UseEffectWithNoDependencies() {
const local = {};
useEffect(() => {
console.log(local);
});
| {
"filepath": "fixtures/eslint-v8/index.js",
"language": "javascript",
"file_size": 4191,
"cut_index": 614,
"middle_length": 229
} |
t';
import * as React from 'react';
import {useFormStatus} from 'react-dom';
import ErrorBoundary from './ErrorBoundary.js';
const h = React.createElement;
function Status() {
const {pending} = useFormStatus();
return pending ? 'Saving...' : null;
}
export default function Form({action, children}) {
const [is... |
h('input', {
name: 'name',
})
),
h(
'label',
{},
'File: ',
h('input', {
type: 'file',
name: 'file',
})
),
h('button', {}, 'Say Hi'),
h(Stat | 'Name: ', | {
"filepath": "fixtures/flight-esm/src/Form.js",
"language": "javascript",
"file_size": 813,
"cut_index": 522,
"middle_length": 14
} |
* as React from 'react';
import {use, Suspense, useState, startTransition} from 'react';
import ReactDOM from 'react-dom/client';
import {createFromFetch, encodeReply} from 'react-server-dom-esm/client';
const moduleBaseURL = '/src/';
function findSourceMapURL(fileName) {
return (
document.location.origin +
... | // Refresh the tree with the new RSC payload.
startTransition(() => {
updateRoot(root);
});
return returnValue;
}
let data = createFromFetch(
fetch('/', {
headers: {
Accept: 'text/x-component',
},
}),
{
callServer,
m | Accept: 'text/x-component',
'rsc-action': id,
},
body: await encodeReply(args),
});
const {returnValue, root} = await createFromFetch(response, {
callServer,
moduleBaseURL,
findSourceMapURL,
});
| {
"filepath": "fixtures/flight-esm/src/index.js",
"language": "javascript",
"file_size": 1229,
"cut_index": 518,
"middle_length": 229
} |
esolve,
load as reactLoad,
getSource as getSourceImpl,
transformSource as reactTransformSource,
} from 'react-server-dom-esm/node-loader';
export {resolve};
async function textLoad(url, context, defaultLoad) {
const {format} = context;
const result = await defaultLoad(url, context, defaultLoad);
if (resul... | , context, defaultTransformSource) {
const {format} = context;
if (format === 'module') {
if (typeof source === 'string') {
return {source};
}
return {
source: Buffer.from(source).toString('utf8'),
};
}
return defaultTra |
};
}
return result;
}
export async function load(url, context, defaultLoad) {
return await reactLoad(url, context, (u, c) => {
return textLoad(u, c, defaultLoad);
});
}
async function textTransformSource(source | {
"filepath": "fixtures/flight-esm/loader/region.js",
"language": "javascript",
"file_size": 1451,
"cut_index": 524,
"middle_length": 229
} |
ompress = require('compression');
const chalk = require('chalk');
const express = require('express');
const http = require('http');
const React = require('react');
const {renderToPipeableStream} = require('react-dom/server');
const {createFromNodeStream} = require('react-server-dom-esm/client');
const moduleBasePath ... | al server.
const proxiedHeaders = {
'X-Forwarded-Host': req.hostname,
'X-Forwarded-For': req.ips,
'X-Forwarded-Port': 3000,
'X-Forwarded-Proto': req.protocol,
};
// Proxy other headers as desired.
if (req.get('rsc-action')) {
pr | req = http.request(options, res => {
resolve(res);
});
req.on('error', e => {
reject(e);
});
body.pipe(req);
});
}
app.all('/', async function (req, res, next) {
// Proxy the request to the region | {
"filepath": "fixtures/flight-esm/server/global.js",
"language": "javascript",
"file_size": 5179,
"cut_index": 716,
"middle_length": 229
} |
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');
const nodeModule = require('nod... | .createElement(App);
// For client-invoked server actions we refresh the tree and return a return value.
const payload = returnValue ? {returnValue, root} : root;
const {pipe} = renderToPipeableStream(payload, moduleBasePath);
pipe(res);
}
app.get | ename)).href;
async function renderApp(res, returnValue) {
const {renderToPipeableStream} = await import('react-server-dom-esm/server');
const m = await import('../src/App.js');
const App = m.default;
const root = React | {
"filepath": "fixtures/flight-esm/server/region.js",
"language": "javascript",
"file_size": 7540,
"cut_index": 716,
"middle_length": 229
} |
quire('http');
const {Readable} = require('stream');
const webpack = require('webpack');
const {clientManifest, ssrManifest} = require('./webpack-mock');
const {
renderFizzNode,
renderFizzEdge,
renderFlightFizzNode,
renderFlightFizzEdge,
} = require('./render-helpers');
const {printGrid} = require('./print-hel... | rs()) {
reject(new Error(stats.toString({errors: true})));
return;
}
console.log(
stats.toString({colors: true, modules: false, entrypoints: false})
);
resolve();
});
});
}
// ------------------------- | ) {
const config = require('./webpack.config');
return new Promise(function (resolve, reject) {
webpack(config, function (err, stats) {
if (err) {
reject(err);
return;
}
if (stats.hasErro | {
"filepath": "fixtures/flight-ssr-bench/bench-server.js",
"language": "javascript",
"file_size": 9186,
"cut_index": 716,
"middle_length": 229
} |
omise(function (resolve, reject) {
webpack(config, function (err, stats) {
if (err) {
reject(err);
return;
}
if (stats.hasErrors()) {
reject(new Error(stats.toString({errors: true})));
return;
}
console.log(
stats.toString({colors: true, modules:... | ightFizzEdgeStream,
nodeStreamToString,
webStreamToString,
} = require('./render-helpers');
const {printGrid} = require('./print-helpers');
function renderFizzNode(AppComponent, itemCount) {
return nodeStreamToString(renderFizzNodeStream(AppComponen | -------------------------------------------------------
const {
renderFizzNode: renderFizzNodeStream,
renderFizzEdge: renderFizzEdgeStream,
renderFlightFizzNode: renderFlightFizzNodeStream,
renderFlightFizzEdge: renderFl | {
"filepath": "fixtures/flight-ssr-bench/bench.js",
"language": "javascript",
"file_size": 19461,
"cut_index": 1331,
"middle_length": 229
} |
;
function printGrid(colHeaders, rows, getValue, unit, note) {
const labelWidth = Math.max(
...rows.map(function (r) {
return r[0].length;
})
);
const suffix = unit ? ' ' + unit : '';
const fmtVal = function (v) {
return (v.toFixed(1) + suffix).padStart(10 + suffix.length);
};
const fmtPc... | console.log(' ' + header);
console.log(' ' + '-'.repeat(header.length));
for (const [label, a, b] of rows) {
const va = getValue(a);
const vb = getValue(b);
const pct = ((vb - va) / va) * 100;
console.log(
' ' +
label.p | onst colWidth = 10 + suffix.length;
const header =
''.padEnd(labelWidth) +
' ' +
colHeaders
.map(function (h) {
return h.padStart(colWidth);
})
.join(' ') +
' Delta Factor';
| {
"filepath": "fixtures/flight-ssr-bench/print-helpers.js",
"language": "javascript",
"file_size": 1274,
"cut_index": 524,
"middle_length": 229
} |
;
const {renderToPipeableStream} = require('react-dom/server');
const output = new PassThrough();
const {pipe} = renderToPipeableStream(
React.createElement(AppComponent, {itemCount}),
{
onShellReady() {
pipe(output);
},
onError(e) {
console.error('Fizz Node error:', e);... | ire('react');
const {renderToReadableStream} = require('react-dom/server');
return renderToReadableStream(React.createElement(AppComponent, {itemCount}));
}
// ---------------------------------------------------------------------------
// Flight + Fi | streams.
// Returns a promise that resolves to a web ReadableStream of HTML.
// ---------------------------------------------------------------------------
function renderFizzEdge(AppComponent, itemCount) {
const React = requ | {
"filepath": "fixtures/flight-ssr-bench/render-helpers.js",
"language": "javascript",
"file_size": 9452,
"cut_index": 921,
"middle_length": 229
} |
use strict';
const url = require('url');
// Webpack loader that runs in the RSC compilation.
// When a module starts with 'use client', it replaces the entire source
// with a client module proxy. This makes the RSC renderer serialize a
// client reference into the Flight stream instead of rendering the component.
mo... | pathToFileURL(this.resourcePath).href;
return [
`const { createClientModuleProxy } = require('react-server-dom-webpack/server');`,
`module.exports = createClientModuleProxy(${JSON.stringify(href)});`,
].join('\n');
}
return source;
| st href = url. | {
"filepath": "fixtures/flight-ssr-bench/rsc-client-ref-loader.js",
"language": "javascript",
"file_size": 786,
"cut_index": 513,
"middle_length": 14
} |
= require('path');
const url = require('url');
const fs = require('fs');
const clientModules = {};
const clientManifest = {};
const ssrModuleMap = {};
let moduleIdx = 0;
function registerClientModule(modulePath) {
const id = String(moduleIdx++);
const chunkId = 'chunk-' + id;
const absPath = path.resolve(__dir... | (__dirname, 'src/components'),
];
for (const dir of srcDirs) {
if (!fs.existsSync(dir)) continue;
for (const file of fs.readdirSync(dir)) {
if (!file.endsWith('.js')) continue;
const filePath = path.join(dir, file);
const source = fs.readFi | d, absPath], name: '*'};
ssrModuleMap[id] = {'*': {id, chunks: [chunkId, absPath], name: '*'}};
}
// Auto-register all 'use client' components by scanning src/
const srcDirs = [
path.resolve(__dirname, 'src'),
path.resolve | {
"filepath": "fixtures/flight-ssr-bench/webpack-mock.js",
"language": "javascript",
"file_size": 1651,
"cut_index": 537,
"middle_length": 229
} |
;
const path = require('path');
module.exports = {
name: 'rsc',
target: 'node',
entry: './src/entry-rsc.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'rsc-bundle.js',
library: {type: 'commonjs2'},
clean: true,
},
resolve: {
// This is the key: react-server condition ... | ude: /node_modules/,
loader: path.resolve(__dirname, 'rsc-client-ref-loader.js'),
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: require.resolve('babel-loader'),
options: {
presets: [['@ | x'],
},
module: {
rules: [
{
// Custom loader that replaces 'use client' modules with client
// reference proxies. Must run before babel.
enforce: 'pre',
test: /\.jsx?$/,
excl | {
"filepath": "fixtures/flight-ssr-bench/webpack.config.js",
"language": "javascript",
"file_size": 1291,
"cut_index": 524,
"middle_length": 229
} |
ort StatsGrid from './StatsGrid';
import ProductTable from './ProductTable';
import ActivityFeed from './ActivityFeed';
import ChartPanel from './ChartPanel';
import {generateProducts, generateActivities, generateStats} from './data';
export default function Dashboard({itemCount}) {
const products = generateProducts... | className="dashboard-grid">
<div className="dashboard-main">
<ProductTable products={products} />
</div>
<div className="dashboard-aside">
<ChartPanel title="Revenue" data={stats.revenueByMonth} type="bar" />
| der">
<h1>Dashboard Overview</h1>
<p className="dashboard-subtitle">
Welcome back. Here is what is happening with your store today.
</p>
</div>
<StatsGrid stats={stats} />
<div | {
"filepath": "fixtures/flight-ssr-bench/src/components/Dashboard.js",
"language": "javascript",
"file_size": 1095,
"cut_index": 515,
"middle_length": 229
} |
;
import TableHeader from './TableHeader';
import Pagination from './Pagination';
import ActivityItem from './ActivityItem';
import ChartPanel from './ChartPanel';
import Skeleton from './Skeleton';
import {generateProducts, generateActivities, generateStats} from './data';
function fetchData(generator, ...args) {
r... | u', label: 'SKU'},
{key: 'category', label: 'Category'},
{key: 'price', label: 'Price'},
{key: 'stock', label: 'Stock'},
{key: 'status', label: 'Status'},
{key: 'rating', label: 'Rating'},
];
async function AsyncProductRow({product, delay}) {
| olve(value), delayMs);
});
}
async function AsyncStatsSection() {
const stats = await fetchData(generateStats);
return <StatsGrid stats={stats} />;
}
const productColumns = [
{key: 'name', label: 'Product'},
{key: 'sk | {
"filepath": "fixtures/flight-ssr-bench/src/components/DashboardAsync.js",
"language": "javascript",
"file_size": 4209,
"cut_index": 614,
"middle_length": 229
} |
FooterLink from './FooterLink';
const footerSections = [
{
title: 'Product',
links: ['Features', 'Pricing', 'Changelog', 'Docs', 'API Reference'],
},
{
title: 'Company',
links: ['About', 'Blog', 'Careers', 'Press', 'Partners'],
},
{
title: 'Support',
links: ['Help Center', 'Contact',... | {section.links.map(link => (
<li key={link}>
<FooterLink
href={'/' + link.toLowerCase().replace(/\s+/g, '-')}>
{link}
</FooterLink>
</ | <footer className="app-footer">
<div className="footer-grid">
{footerSections.map(section => (
<div key={section.title} className="footer-section">
<h4>{section.title}</h4>
<ul>
| {
"filepath": "fixtures/flight-ssr-bench/src/components/Footer.js",
"language": "javascript",
"file_size": 1215,
"cut_index": 518,
"middle_length": 229
} |
TableRow from './TableRow';
import TableHeader from './TableHeader';
import Badge from './Badge';
import Pagination from './Pagination';
const columns = [
{key: 'name', label: 'Product'},
{key: 'sku', label: 'SKU'},
{key: 'category', label: 'Category'},
{key: 'price', label: 'Price'},
{key: 'stock', label: ... | {columns.map(col => (
<TableHeader key={col.key} column={col} />
))}
</tr>
</thead>
<tbody>
{products.map(product => (
<TableRow key={product.id} product={product} columns={columns | >
<div className="table-toolbar">
<h2>Products</h2>
<span className="table-count">{products.length} items</span>
</div>
<table className="product-table">
<thead>
<tr>
| {
"filepath": "fixtures/flight-ssr-bench/src/components/ProductTable.js",
"language": "javascript",
"file_size": 1131,
"cut_index": 518,
"middle_length": 229
} |
ion from './SidebarSection';
import Badge from './Badge';
const navItems = [
{href: '/', label: 'Dashboard', icon: 'home'},
{href: '/products', label: 'Products', icon: 'box', count: 142},
{href: '/orders', label: 'Orders', icon: 'cart', count: 38},
{href: '/customers', label: 'Customers', icon: 'users'},
{h... | e className="sidebar">
<nav className="sidebar-nav">
<SidebarSection title="Navigation">
{navItems.map(item => (
<NavLink key={item.href} href={item.href} icon={item.icon}>
{item.label}
{item. | id: 2, label: 'Order #1235', status: 'shipped'},
{id: 3, label: 'Order #1236', status: 'delivered'},
{id: 4, label: 'Return #891', status: 'processing'},
];
export default function Sidebar({itemCount}) {
return (
<asid | {
"filepath": "fixtures/flight-ssr-bench/src/components/Sidebar.js",
"language": "javascript",
"file_size": 2086,
"cut_index": 563,
"middle_length": 229
} |
use client';
import Badge from './Badge';
export default function TableRow({product, columns}) {
return (
<tr className="table-row">
{columns.map(col => (
<td key={col.key} className="table-cell" data-column={col.key}>
{col.key === 'status' ? (
<Badge count={product[col.key]}... | lassName="product-name-cell">
<span className="product-name">{product.name}</span>
<span className="product-category">{product.category}</span>
</div>
) : (
product[col.key]
)}
| ting">
<span className="star">★</span> {product[col.key]}
<span className="review-count">({product.reviewCount})</span>
</span>
) : col.key === 'name' ? (
<div c | {
"filepath": "fixtures/flight-ssr-bench/src/components/TableRow.js",
"language": "javascript",
"file_size": 1032,
"cut_index": 513,
"middle_length": 229
} |
const activityTypes = [
'order_placed',
'order_shipped',
'order_delivered',
'refund_requested',
'review_posted',
'product_added',
'stock_alert',
'payment_received',
];
const userNames = [
'Alice Johnson',
'Bob Williams',
'Carol Davis',
'Dan Miller',
'Eve Wilson',
'Frank Moore',
'Grace Tay... | d highly recommend to anyone looking for this type of item.',
'Average product, nothing special. Does what it says but nothing more than that.',
];
export function generateProducts(count) {
const products = [];
for (let i = 0; i < count; i++) {
| Decent value for the price. Some minor issues with packaging but the product itself works well.',
'Not what I expected based on the description. Returning this item for a refund.',
'Outstanding quality and craftsmanship. Woul | {
"filepath": "fixtures/flight-ssr-bench/src/components/data.js",
"language": "javascript",
"file_size": 8932,
"cut_index": 716,
"middle_length": 229
} |
nst React = global.React;
const ReactDOM = global.ReactDOM;
class Counter extends React.unstable_AsyncComponent {
state = {counter: 0};
onCommit() {
setImmediate(() => {
this.setState(state => ({
counter: state.counter + 1,
}));
});
}
componentDidMount() {
this.onCommit();
}
... | e (performance.now() < endTime) {}
}
setInterval(block, interval);
// Should render a counter that increments approximately every second (the
// expiration time of a low priority update).
ReactDOM.render(<Counter />, document.getElementById('root'));
bloc | terval;
whil | {
"filepath": "fixtures/expiration/src/index.js",
"language": "javascript",
"file_size": 789,
"cut_index": 514,
"middle_length": 14
} |
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 path = require('path');
const {ESLint} = require('eslint');
function getESLintInstance(format) {
return... | lts = await eslint.lintFiles([
__dirname + '/' + folder + '/cjs/react-jsx-dev-runtime.development.js',
__dirname + '/' + folder + '/cjs/react-jsx-dev-runtime.production.min.js',
__dirname + '/' + folder + '/cjs/react-jsx-runtime.development.js' | etESLintInstance('cjs'),
};
// Performs sanity checks on bundles *built* by Rollup.
// Helps catch Rollup regressions.
async function lint(folder) {
console.log(`Linting ` + folder);
const eslint = esLints.cjs;
const resu | {
"filepath": "fixtures/legacy-jsx-runtimes/lint-runtimes.js",
"language": "javascript",
"file_size": 1665,
"cut_index": 537,
"middle_length": 229
} |
[') === 0) {
// This looks like an uncaught error from invokeGuardedCallback() wrapper
// in development that is reported by jsdom. Ignore because it's noisy.
return true;
}
if (format.indexOf('The above error occurred') === 0) {
// This looks like an error addendum from Reac... | return false;
}
function normalizeCodeLocInfo(str) {
if (typeof str !== 'string') {
return str;
}
// This special case exists only for the special source location in
// ReactElementValidator. That will go away if we remove source locations.
| k === 'string' &&
args.length === 0
) {
// In production, ReactFiberErrorLogger logs error objects directly.
// They are noisy too so we'll try to ignore them.
return true;
}
}
// Looks legit
| {
"filepath": "fixtures/legacy-jsx-runtimes/setupTests.js",
"language": "javascript",
"file_size": 11406,
"cut_index": 921,
"middle_length": 229
} |
extends React.Component {
render() {
return <div />;
}
};
let RequiredPropComponent = class extends React.Component {
render() {
return <span>{this.props.prop}</span>;
}
};
RequiredPropComponent.displayName = 'RequiredPropComponent';
RequiredPropComponent.propTypes = {prop: PropTypes.string.isRequired}... | tion);
expect(element.props).toEqual(expectation);
});
it('allows a lower-case to be passed as the string type', () => {
const element = <div />;
expect(element.type).toBe('div');
expect(element.key).toBe(null);
expect(element.ref).toBe(null);
| te element according to spec', () => {
const element = <Component />;
expect(element.type).toBe(Component);
expect(element.key).toBe(null);
expect(element.ref).toBe(null);
const expectation = {};
Object.freeze(expecta | {
"filepath": "fixtures/legacy-jsx-runtimes/react-16/react-16.test.js",
"language": "javascript",
"file_size": 21951,
"cut_index": 1331,
"middle_length": 229
} |
0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
var REACT_SUSPENSE_TYPE = 0xead1;
var REACT_SUSPENSE_LIST_TYPE = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_BLOCK_TYPE = 0xead9;
var REACT_SERVER_BLOCK_TYPE = 0xeada;
var RE... | olFor('react.fragment');
REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
REACT_PROFILER_TYPE = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD | _HIDDEN_TYPE = 0xeae3;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symb | {
"filepath": "fixtures/legacy-jsx-runtimes/react-16/cjs/react-jsx-dev-runtime.development.js",
"language": "javascript",
"file_size": 28708,
"cut_index": 1331,
"middle_length": 229
} |
d2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
var REACT_SUSPENSE_TYPE = 0xead1;
var REACT_SUSPENSE_LIST_TYPE = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_BLOCK_TYPE = 0xead9;
var REACT_SERVER_BLOCK_TYPE = 0xeada;
var REACT_... | r('react.fragment');
REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
REACT_PROFILER_TYPE = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD_REF | DEN_TYPE = 0xeae3;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symbolFo | {
"filepath": "fixtures/legacy-jsx-runtimes/react-16/cjs/react-jsx-runtime.development.js",
"language": "javascript",
"file_size": 29319,
"cut_index": 1331,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.