Add LTI annotations to function params in xplat/js [1/2]

Summary: Add annotations to function parameters required for Flow's Local Type Inference project. This codemod prepares the codebase to match Flow's new typechecking algorithm. The new algorithm will make Flow more reliable and predicatable.

Reviewed By: evanyeung

Differential Revision: D37353648

fbshipit-source-id: e5a0c685ced85a8ff353d578b373f836b376bb28
This commit is contained in:
Pieter Vanderwerff
2022-06-22 21:36:52 -07:00
committed by Facebook GitHub Bot
parent a7db8df207
commit e7a4dbcefc
74 changed files with 430 additions and 182 deletions
+19 -3
View File
@@ -33,7 +33,7 @@ const VAL_MERGE_EXPECT = {foo: 1, bar: {hoo: 2, boo: 1}, baz: 2, moo: {a: 3}};
let done = (result: ?boolean) => {};
let updateMessage = (message: string) => {};
function runTestCase(description: string, fn) {
function runTestCase(description: string, fn: () => void) {
updateMessage(description);
fn();
}
@@ -61,7 +61,20 @@ function stringify(
return JSON.stringify(value);
}
function expectEqual(lhs, rhs, testname: string) {
function expectEqual(
lhs: ?(any | string | Array<Array<string>>),
rhs:
| null
| string
| {
bar: {boo: number, hoo: number},
baz: number,
foo: number,
moo: {a: number},
}
| Array<Array<string>>,
testname: string,
) {
expectTrue(
!deepDiffer(lhs, rhs),
'Error in test ' +
@@ -73,7 +86,10 @@ function expectEqual(lhs, rhs, testname: string) {
);
}
function expectAsyncNoError(place, err) {
function expectAsyncNoError(
place: string,
err: ?(Error | string | Array<Error>),
) {
if (err instanceof Error) {
err = err.message;
}
+1 -1
View File
@@ -105,7 +105,7 @@ class Alert {
options && options.onDismiss && options.onDismiss();
}
};
const onError = errorMessage => console.warn(errorMessage);
const onError = (errorMessage: string) => console.warn(errorMessage);
NativeDialogManagerAndroid.showAlert(config, onError, onAction);
}
}
+7 -4
View File
@@ -41,7 +41,7 @@ function attachNativeEvent(
// key path inside the `nativeEvent` object. Ex.: ['contentOffset', 'x'].
const eventMappings = [];
const traverse = (value, path) => {
const traverse = (value: mixed, path: Array<string>) => {
if (value instanceof AnimatedValue) {
value.__makeNative(platformConfig);
@@ -94,8 +94,8 @@ function attachNativeEvent(
};
}
function validateMapping(argMapping, args) {
const validate = (recMapping, recEvt, key) => {
function validateMapping(argMapping: $ReadOnlyArray<?Mapping>, args: any) {
const validate = (recMapping: ?Mapping, recEvt: any, key: string) => {
if (recMapping instanceof AnimatedValue) {
invariant(
typeof recEvt === 'number',
@@ -223,7 +223,10 @@ class AnimatedEvent {
validatedMapping = true;
}
const traverse = (recMapping, recEvt) => {
const traverse = (
recMapping: ?(Mapping | AnimatedValue),
recEvt: any,
) => {
if (recMapping instanceof AnimatedValue) {
if (typeof recEvt === 'number') {
recMapping.setValue(recEvt);
+3 -3
View File
@@ -94,7 +94,7 @@ const _combineCallbacks = function (
config: $ReadOnly<{...AnimationConfig, ...}>,
) {
if (callback && config.onComplete) {
return (...args) => {
return (...args: Array<EndResult>) => {
config.onComplete && config.onComplete(...args);
callback && callback(...args);
};
@@ -308,7 +308,7 @@ const sequence = function (
let current = 0;
return {
start: function (callback?: ?EndCallback) {
const onComplete = function (result) {
const onComplete = function (result: EndResult) {
if (!result.finished) {
callback && callback(result);
return;
@@ -380,7 +380,7 @@ const parallel = function (
}
animations.forEach((animation, idx) => {
const cb = function (endResult) {
const cb = function (endResult: EndResult | {finished: boolean}) {
hasEnded[idx] = true;
doneCount++;
if (doneCount === animations.length) {
+3 -1
View File
@@ -10,6 +10,8 @@
'use strict';
import type {EndResult} from './animations/Animation';
const {AnimatedEvent, attachNativeEvent} = require('./AnimatedEvent');
const AnimatedImplementation = require('./AnimatedImplementation');
const AnimatedInterpolation = require('./nodes/AnimatedInterpolation');
@@ -43,7 +45,7 @@ function mockAnimationStart(
const guardedCallback =
callback == null
? callback
: (...args) => {
: (...args: Array<EndResult>) => {
if (inAnimationCallback) {
console.warn(
'Ignoring recursive animation callback when running mock animations',
+1 -1
View File
@@ -249,7 +249,7 @@ export default class AnimatedColor extends AnimatedWithChildren {
*/
addListener(callback: ColorListenerCallback): string {
const id = String(_uniqueId++);
const jointCallback = ({value: number}) => {
const jointCallback = ({value: number}: any) => {
callback(this.__getValue());
};
this._listeners[id] = {
+1 -1
View File
@@ -177,7 +177,7 @@ class AnimatedValueXY extends AnimatedWithChildren {
*/
addListener(callback: ValueXYListenerCallback): string {
const id = String(_uniqueId++);
const jointCallback = ({value: number}) => {
const jointCallback = ({value: number}: any) => {
callback(this.__getValue());
};
this._listeners[id] = {
+2 -2
View File
@@ -252,7 +252,7 @@ class MessageQueue {
// folly-convertible. As a special case, if a prop value is a
// function it is permitted here, and special-cased in the
// conversion.
const isValidArgument = val => {
const isValidArgument = (val: mixed) => {
switch (typeof val) {
case 'undefined':
case 'boolean':
@@ -286,7 +286,7 @@ class MessageQueue {
// Replacement allows normally non-JSON-convertible values to be
// seen. There is ambiguity with string values, but in context,
// it should at least be a strong hint.
const replacer = (key, val) => {
const replacer = (key: string, val: $FlowFixMe) => {
const t = typeof val;
if (t === 'function') {
return '<<Function ' + val.name + '>>';
@@ -1107,7 +1107,7 @@ class ScrollView extends React.Component<Props, State> {
}
};
_getKeyForIndex(index, childArray) {
_getKeyForIndex(index: $FlowFixMe, childArray: $FlowFixMe) {
const child = childArray[index];
return child && child.key;
}
@@ -1140,7 +1140,7 @@ class ScrollView extends React.Component<Props, State> {
}
}
_onStickyHeaderLayout(index, event, key) {
_onStickyHeaderLayout(index: $FlowFixMe, event: $FlowFixMe, key: $FlowFixMe) {
const {stickyHeaderIndices} = this.props;
if (!stickyHeaderIndices) {
return;
@@ -1822,7 +1822,7 @@ const styles = StyleSheet.create({
},
});
function Wrapper(props, ref) {
function Wrapper(props, ref: (mixed => mixed) | {current: mixed, ...}) {
return <ScrollView {...props} scrollViewRef={ref} />;
}
Wrapper.displayName = 'ScrollView';
@@ -18,7 +18,7 @@ import invariant from 'invariant';
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
const oneArgumentPooler = function (copyFieldsFrom) {
const oneArgumentPooler = function (copyFieldsFrom: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
@@ -29,7 +29,7 @@ const oneArgumentPooler = function (copyFieldsFrom) {
}
};
const twoArgumentPooler = function (a1, a2) {
const twoArgumentPooler = function (a1: any, a2: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
@@ -40,7 +40,7 @@ const twoArgumentPooler = function (a1, a2) {
}
};
const threeArgumentPooler = function (a1, a2, a3) {
const threeArgumentPooler = function (a1: any, a2: any, a3: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
@@ -51,7 +51,7 @@ const threeArgumentPooler = function (a1, a2, a3) {
}
};
const fourArgumentPooler = function (a1, a2, a3, a4) {
const fourArgumentPooler = function (a1: any, a2: any, a3: any, a4: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
+12 -1
View File
@@ -21,7 +21,18 @@ import type {ColorValue} from '../../StyleSheet/StyleSheet';
import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType';
import type {PressEvent} from '../../Types/CoreEventTypes';
const extractSingleTouch = nativeEvent => {
const extractSingleTouch = (nativeEvent: {
+changedTouches: $ReadOnlyArray<PressEvent['nativeEvent']>,
+force?: number,
+identifier: number,
+locationX: number,
+locationY: number,
+pageX: number,
+pageY: number,
+target: ?number,
+timestamp: number,
+touches: $ReadOnlyArray<PressEvent['nativeEvent']>,
}) => {
const touches = nativeEvent.touches;
const changedTouches = nativeEvent.changedTouches;
const hasTouches = touches && touches.length > 0;
@@ -312,11 +312,11 @@ class TouchableNativeFeedback extends React.Component<Props, State> {
const getBackgroundProp =
Platform.OS === 'android'
? (background, useForeground) =>
? (background, useForeground: boolean) =>
useForeground && TouchableNativeFeedback.canUseNativeForeground()
? {nativeForegroundAndroid: background}
: {nativeBackgroundAndroid: background}
: (background, useForeground) => null;
: (background, useForeground: boolean) => null;
TouchableNativeFeedback.displayName = 'TouchableNativeFeedback';
+2 -2
View File
@@ -274,7 +274,7 @@ const JSTimers = {
const timeout = options && options.timeout;
const id = _allocateCallback(
timeout != null
? deadline => {
? (deadline: any) => {
const timeoutId = requestIdleCallbackTimeouts[id];
if (timeoutId) {
JSTimers.clearTimeout(timeoutId);
@@ -364,7 +364,7 @@ const JSTimers = {
// error one at a time
for (let ii = 1; ii < errorCount; ii++) {
JSTimers.setTimeout(
(error => {
((error: Error) => {
throw error;
}).bind(null, errors[ii]),
0,
+7 -2
View File
@@ -10,6 +10,8 @@
'use strict';
import type {RenderItemProps} from '../Lists/VirtualizedList';
const ScrollView = require('../Components/ScrollView/ScrollView');
const TouchableHighlight = require('../Components/Touchable/TouchableHighlight');
const View = require('../Components/View/View');
@@ -326,7 +328,10 @@ class NetworkOverlay extends React.Component<Props, State> {
WebSocketInterceptor.disableInterception();
}
_renderItem = ({item, index}): React.Element<any> => {
_renderItem = ({
item,
index,
}: RenderItemProps<NetworkRequestInfo>): React.Element<any> => {
const tableRowViewStyle = [
styles.tableRow,
index % 2 === 1 ? styles.tableRowOdd : styles.tableRowEven,
@@ -358,7 +363,7 @@ class NetworkOverlay extends React.Component<Props, State> {
);
};
_renderItemDetail(id) {
_renderItemDetail(id: number) {
const requestItem = this.state.requests[id];
const details = Object.keys(requestItem).map(key => {
if (key === 'id') {
+7 -3
View File
@@ -259,9 +259,13 @@ class ViewabilityHelper {
}
_onUpdateSync(
viewableIndicesToCheck,
onViewableItemsChanged,
createViewToken,
viewableIndicesToCheck: Array<number>,
onViewableItemsChanged: ({
changed: Array<ViewToken>,
viewableItems: Array<ViewToken>,
...
}) => void,
createViewToken: (index: number, isViewable: boolean) => ViewToken,
) {
// Filter out indices that have gone out of view since this call was scheduled.
viewableIndicesToCheck = viewableIndicesToCheck.filter(ii =>
+11 -6
View File
@@ -10,7 +10,7 @@
import type {ScrollResponderType} from '../Components/ScrollView/ScrollView';
import type {ViewStyleProp} from '../StyleSheet/StyleSheet';
import type {LayoutEvent} from '../Types/CoreEventTypes';
import type {LayoutEvent, ScrollEvent} from '../Types/CoreEventTypes';
import type {
ViewabilityConfig,
ViewabilityConfigCallbackPair,
@@ -1713,7 +1713,7 @@ class VirtualizedList extends React.PureComponent<Props, State> {
}
}
_onScrollBeginDrag = (e): void => {
_onScrollBeginDrag = (e: ScrollEvent): void => {
this._nestedChildLists.forEach(childList => {
childList.ref && childList.ref._onScrollBeginDrag(e);
});
@@ -1724,7 +1724,7 @@ class VirtualizedList extends React.PureComponent<Props, State> {
this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
};
_onScrollEndDrag = (e): void => {
_onScrollEndDrag = (e: ScrollEvent): void => {
this._nestedChildLists.forEach(childList => {
childList.ref && childList.ref._onScrollEndDrag(e);
});
@@ -1736,14 +1736,14 @@ class VirtualizedList extends React.PureComponent<Props, State> {
this.props.onScrollEndDrag && this.props.onScrollEndDrag(e);
};
_onMomentumScrollBegin = (e): void => {
_onMomentumScrollBegin = (e: ScrollEvent): void => {
this._nestedChildLists.forEach(childList => {
childList.ref && childList.ref._onMomentumScrollBegin(e);
});
this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e);
};
_onMomentumScrollEnd = (e): void => {
_onMomentumScrollEnd = (e: ScrollEvent): void => {
this._nestedChildLists.forEach(childList => {
childList.ref && childList.ref._onMomentumScrollEnd(e);
});
@@ -2033,7 +2033,12 @@ class CellRenderer extends React.Component<
);
};
_renderElement(renderItem, ListItemComponent, item, index) {
_renderElement(
renderItem: any,
ListItemComponent: any,
item: any,
index: any,
) {
if (renderItem && ListItemComponent) {
console.warn(
'VirtualizedList: Both ListItemComponent and renderItem props are present. ListItemComponent will take' +
+8 -5
View File
@@ -392,21 +392,24 @@ class VirtualizedSectionList<
}
};
_updatePropsFor = (cellKey, value) => {
_updatePropsFor = (cellKey: string, value: any) => {
const updateProps = this._updatePropsMap[cellKey];
if (updateProps != null) {
updateProps(value);
}
};
_updateHighlightFor = (cellKey, value) => {
_updateHighlightFor = (cellKey: string, value: boolean) => {
const updateHighlight = this._updateHighlightMap[cellKey];
if (updateHighlight != null) {
updateHighlight(value);
}
};
_setUpdateHighlightFor = (cellKey, updateHighlightFn) => {
_setUpdateHighlightFor = (
cellKey: string,
updateHighlightFn: ?(boolean) => void,
) => {
if (updateHighlightFn != null) {
this._updateHighlightMap[cellKey] = updateHighlightFn;
} else {
@@ -414,7 +417,7 @@ class VirtualizedSectionList<
}
};
_setUpdatePropsFor = (cellKey, updatePropsFn) => {
_setUpdatePropsFor = (cellKey: string, updatePropsFn: ?(boolean) => void) => {
if (updatePropsFn != null) {
this._updatePropsMap[cellKey] = updatePropsFn;
} else {
@@ -449,7 +452,7 @@ class VirtualizedSectionList<
_updateHighlightMap: {[string]: (boolean) => void} = {};
_updatePropsMap: {[string]: void | (boolean => void)} = {};
_listRef: ?React.ElementRef<typeof VirtualizedList>;
_captureRef = ref => {
_captureRef = (ref: null | React$ElementRef<Class<VirtualizedList>>) => {
this._listRef = ref;
};
}
+1 -1
View File
@@ -133,7 +133,7 @@ function handleUpdate(): void {
}
}
function appendNewLog(newLog) {
function appendNewLog(newLog: LogBoxLog) {
// Don't want store these logs because they trigger a
// state update when we add them to the store.
if (isMessageIgnored(newLog.message.content)) {
@@ -49,7 +49,7 @@ function getLogBoxSymbolication(): {|
return (require('../LogBoxSymbolication'): any);
}
const createStack = methodNames =>
const createStack = (methodNames: Array<string>) =>
methodNames.map(methodName => ({
column: null,
file: 'file://path/to/file.js',
@@ -22,7 +22,7 @@ const symbolicateStackTrace: JestMockFn<
Promise<Array<StackFrame>>,
> = (require('../../../Core/Devtools/symbolicateStackTrace'): any);
const createStack = methodNames =>
const createStack = (methodNames: Array<string>) =>
methodNames.map(methodName => ({
column: null,
file: 'file://path/to/file.js',
@@ -8,6 +8,10 @@
* @format
*/
import type {StackFrame} from '../../Core/NativeExceptionsManager';
import type {Stack} from '../Data/LogBoxSymbolication';
import type LogBoxLog from '../Data/LogBoxLog';
import * as React from 'react';
import StyleSheet from '../../StyleSheet/StyleSheet';
import Text from '../../Text/Text';
@@ -18,8 +22,6 @@ import LogBoxInspectorStackFrame from './LogBoxInspectorStackFrame';
import LogBoxInspectorSection from './LogBoxInspectorSection';
import * as LogBoxStyle from './LogBoxStyle';
import openFileInEditor from '../../Core/Devtools/openFileInEditor';
import type {Stack} from '../Data/LogBoxSymbolication';
import type LogBoxLog from '../Data/LogBoxLog';
type Props = $ReadOnly<{|
log: LogBoxLog,
@@ -111,7 +113,10 @@ function LogBoxInspectorStackFrames(props: Props): React.Node {
);
}
function StackFrameList(props) {
function StackFrameList(props: {
list: Stack | Array<StackFrame>,
status: string | 'COMPLETE' | 'FAILED' | 'NONE' | 'PENDING',
}) {
return (
<>
{props.list.map((frame, index) => {
@@ -210,10 +210,10 @@ StaticViewConfigValidator: Invalid static view config for 'RCTView'.
});
function expectSVCToNotMatchNVC(
name,
name: string,
nativeViewConfig,
staticViewConfig,
message,
message: string,
) {
const validationResult = StaticViewConfigValidator.validate(
name,
+17 -6
View File
@@ -255,20 +255,20 @@ const Transitions = Object.freeze({
},
});
const isActiveSignal = signal =>
const isActiveSignal = (signal: TouchState) =>
signal === 'RESPONDER_ACTIVE_PRESS_IN' ||
signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN';
const isActivationSignal = signal =>
const isActivationSignal = (signal: TouchState) =>
signal === 'RESPONDER_ACTIVE_PRESS_OUT' ||
signal === 'RESPONDER_ACTIVE_PRESS_IN';
const isPressInSignal = signal =>
const isPressInSignal = (signal: TouchState) =>
signal === 'RESPONDER_INACTIVE_PRESS_IN' ||
signal === 'RESPONDER_ACTIVE_PRESS_IN' ||
signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN';
const isTerminalSignal = signal =>
const isTerminalSignal = (signal: TouchSignal) =>
signal === 'RESPONDER_TERMINATED' || signal === 'RESPONDER_RELEASE';
const DEFAULT_LONG_PRESS_DELAY_MS = 500;
@@ -808,7 +808,14 @@ export default class Pressability {
}
}
_measureCallback = (left, top, width, height, pageX, pageY) => {
_measureCallback = (
left: number,
top: number,
width: number,
height: number,
pageX: number,
pageY: number,
) => {
if (!left && !top && !width && !height && !pageX && !pageY) {
return;
}
@@ -918,7 +925,11 @@ export default class Pressability {
}
}
function normalizeDelay(delay: ?number, min = 0, fallback = 0): number {
function normalizeDelay(
delay: ?number,
min: number = 0,
fallback: number = 0,
): number {
return Math.max(min, delay ?? fallback);
}
@@ -105,7 +105,7 @@ const mockUIManagerMeasure = (options?: {|delay: number|}) => {
});
};
const createMockTargetEvent = registrationName => {
const createMockTargetEvent = (registrationName: string) => {
const nativeEvent = {
target: 42,
};
@@ -132,7 +132,7 @@ const createMockTargetEvent = registrationName => {
};
};
const createMockMouseEvent = registrationName => {
const createMockMouseEvent = (registrationName: string) => {
const nativeEvent = {
clientX: 0,
clientY: 0,
+1 -1
View File
@@ -114,7 +114,7 @@ const UIManagerJS = {
// $FlowFixMe[prop-missing]
NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig;
function lazifyViewManagerConfig(viewName) {
function lazifyViewManagerConfig(viewName: string) {
const viewConfig = getConstants()[viewName];
viewManagerConfigs[viewName] = viewConfig;
if (viewConfig.Manager) {
+8 -6
View File
@@ -8,6 +8,8 @@
* @format
*/
import type {PressEvent} from '../Types/CoreEventTypes';
import Platform from '../Utilities/Platform';
import * as PressabilityDebug from '../Pressability/PressabilityDebug';
import usePressability from '../Pressability/usePressability';
@@ -73,11 +75,11 @@ const Text: React.AbstractComponent<
pressRectOffset: pressRetentionOffset,
onLongPress,
onPress,
onPressIn(event) {
onPressIn(event: PressEvent) {
setHighlighted(!suppressHighlighting);
onPressIn?.(event);
},
onPressOut(event) {
onPressOut(event: PressEvent) {
setHighlighted(false);
onPressOut?.(event);
},
@@ -106,25 +108,25 @@ const Text: React.AbstractComponent<
eventHandlers == null
? null
: {
onResponderGrant(event) {
onResponderGrant(event: PressEvent) {
eventHandlers.onResponderGrant(event);
if (onResponderGrant != null) {
onResponderGrant(event);
}
},
onResponderMove(event) {
onResponderMove(event: PressEvent) {
eventHandlers.onResponderMove(event);
if (onResponderMove != null) {
onResponderMove(event);
}
},
onResponderRelease(event) {
onResponderRelease(event: PressEvent) {
eventHandlers.onResponderRelease(event);
if (onResponderRelease != null) {
onResponderRelease(event);
}
},
onResponderTerminate(event) {
onResponderTerminate(event: PressEvent) {
eventHandlers.onResponderTerminate(event);
if (onResponderTerminate != null) {
onResponderTerminate(event);
+3 -3
View File
@@ -256,7 +256,7 @@ Error: ${e.message}`;
},
};
function setHMRUnavailableReason(reason) {
function setHMRUnavailableReason(reason: string) {
invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
if (hmrUnavailableReason !== null) {
// Don't show more than one warning.
@@ -273,7 +273,7 @@ function setHMRUnavailableReason(reason) {
}
}
function registerBundleEntryPoints(client) {
function registerBundleEntryPoints(client: MetroHMRClient) {
if (hmrUnavailableReason != null) {
DevSettings.reload('Bundle Splitting – Metro disconnected');
return;
@@ -290,7 +290,7 @@ function registerBundleEntryPoints(client) {
}
}
function flushEarlyLogs(client) {
function flushEarlyLogs(client: MetroHMRClient) {
try {
pendingLogs.forEach(([level, data]) => {
HMRClient.log(level, data);
+3 -1
View File
@@ -180,7 +180,9 @@ function renderAndEnforceStrictMode(element: React.Node): any {
}
function renderWithStrictMode(element: React.Node): ReactTestRendererType {
const WorkAroundBugWithStrictModeInTestRenderer = prps => prps.children;
const WorkAroundBugWithStrictModeInTestRenderer = (prps: {
children: React.Node,
}) => prps.children;
const StrictMode = (React: $FlowFixMe).StrictMode;
return ReactTestRenderer.create(
<WorkAroundBugWithStrictModeInTestRenderer>
+1 -1
View File
@@ -40,7 +40,7 @@ function vibrateByPattern(pattern: Array<number>, repeat: boolean = false) {
}
function vibrateScheduler(
id,
id: number,
pattern: Array<number>,
repeat: boolean,
nextIndex: number,
@@ -10,6 +10,11 @@
'use strict';
import type {
PressEvent,
ScrollEvent,
} from 'react-native/Libraries/Types/CoreEventTypes';
const BatchedBridge = require('react-native/Libraries/BatchedBridge/BatchedBridge');
const React = require('react');
@@ -26,8 +31,6 @@ const {ScrollListener} = NativeModules;
const NUM_ITEMS = 100;
import type {PressEvent} from 'react-native/Libraries/Types/CoreEventTypes';
// Shared by integration tests for ScrollView and HorizontalScrollView
let scrollViewApp: ScrollViewTestApp | HorizontalScrollViewTestApp;
@@ -61,28 +64,28 @@ const getInitialState = function () {
};
};
const onScroll = function (e) {
const onScroll = function (e: ScrollEvent) {
ScrollListener.onScroll(
e.nativeEvent.contentOffset.x,
e.nativeEvent.contentOffset.y,
);
};
const onScrollBeginDrag = function (e) {
const onScrollBeginDrag = function (e: ScrollEvent) {
ScrollListener.onScrollBeginDrag(
e.nativeEvent.contentOffset.x,
e.nativeEvent.contentOffset.y,
);
};
const onScrollEndDrag = function (e) {
const onScrollEndDrag = function (e: ScrollEvent) {
ScrollListener.onScrollEndDrag(
e.nativeEvent.contentOffset.x,
e.nativeEvent.contentOffset.y,
);
};
const onItemPress = function (itemNumber) {
const onItemPress = function (itemNumber: number) {
ScrollListener.onItemPress(itemNumber);
};
@@ -70,7 +70,7 @@ export class HeaderWriter {
this.stream.write('struct UnknownRequest;\n\n');
const namespaceMap: Map<string, Array<Type | Command | Event>> = new Map();
const addToMap = function (type) {
const addToMap = function (type: Type | Command | Event) {
const domain = type.domain;
let types = namespaceMap.get(domain);
if (!types) {
@@ -32,7 +32,7 @@ type Descriptor = {|
events: Array<Event>,
|};
function mergeDomains(original, extra) {
function mergeDomains(original: any, extra: any) {
return {...original, domains: original.domains.concat(extra.domains)};
}
@@ -186,7 +186,7 @@ function filterReachableFromRoots(
// Sort commands and events so the code is easier to read. Types have to be
// topologically sorted as explained above.
const comparator = (a, b) => {
const comparator = (a: Command | Event, b: Command | Event) => {
const id1 = a.getDebuggerName();
const id2 = b.getDebuggerName();
return id1 < id2 ? -1 : id1 > id2 ? 1 : 0;
+1 -1
View File
@@ -198,7 +198,7 @@ module.exports = {
): boolean {
schemaValidator.validate(schema);
function composePath(intermediate) {
function composePath(intermediate: string) {
return path.join(outputDirectory, intermediate, libraryName);
}
@@ -57,7 +57,13 @@ function getImports(
): Set<string> {
const imports: Set<string> = new Set();
function addImportsForNativeName(name) {
function addImportsForNativeName(
name:
| 'ColorPrimitive'
| 'EdgeInsetsPrimitive'
| 'ImageSourcePrimitive'
| 'PointPrimitive',
) {
switch (name) {
case 'ColorPrimitive':
return;
@@ -9,6 +9,7 @@
*/
'use strict';
import type {EventTypeShape} from '../../CodegenSchema';
const {generateEventStructName} = require('./CppHelpers.js');
@@ -90,7 +91,11 @@ void ${className}EventEmitter::${eventName}() const {
}
`.trim();
function generateSetter(variableName, propertyName, propertyParts) {
function generateSetter(
variableName: string,
propertyName: string,
propertyParts: $ReadOnlyArray<string>,
) {
const trailingPeriod = propertyParts.length === 0 ? '' : '.';
const eventChain = `event.${propertyParts.join(
'.',
@@ -99,7 +104,11 @@ function generateSetter(variableName, propertyName, propertyParts) {
return `${variableName}.setProperty(runtime, "${propertyName}", ${eventChain}`;
}
function generateEnumSetter(variableName, propertyName, propertyParts) {
function generateEnumSetter(
variableName: string,
propertyName: string,
propertyParts: $ReadOnlyArray<string>,
) {
const trailingPeriod = propertyParts.length === 0 ? '' : '.';
const eventChain = `event.${propertyParts.join(
'.',
@@ -177,7 +186,7 @@ function generateSetters(
return propSetters;
}
function generateEvent(componentName: string, event): string {
function generateEvent(componentName: string, event: EventTypeShape): string {
// This is a gross hack necessary because native code is sending
// events named things like topChange to JS which is then converted back to
// call the onChange prop. We should be consistent throughout the system.
@@ -135,7 +135,11 @@ function getNativeTypeFromAnnotation(
throw new Error(`Received invalid event property type ${type}`);
}
}
function generateEnum(structs, options, nameParts) {
function generateEnum(
structs: StructsMap,
options: $ReadOnlyArray<string>,
nameParts: Array<string>,
) {
const structName = generateEventStructName(nameParts);
const fields = options
.map((option, index) => `${toSafeCppString(option)}`)
@@ -218,7 +222,10 @@ function generateStruct(
);
}
function generateStructs(componentName: string, component): string {
function generateStructs(
componentName: string,
component: ComponentShape,
): string {
const structs: StructsMap = new Map();
component.events.forEach(event => {
@@ -244,7 +251,10 @@ function generateEvent(componentName: string, event: EventTypeShape): string {
return `void ${event.name}() const;`;
}
function generateEvents(componentName: string, component): string {
function generateEvents(
componentName: string,
component: ComponentShape,
): string {
return component.events
.map(event => generateEvent(componentName, event))
.join('\n\n' + ' ');
@@ -74,7 +74,7 @@ function generatePropsString(componentName: string, component: ComponentShape) {
.join(',\n' + ' ');
}
function getClassExtendString(component): string {
function getClassExtendString(component: ComponentShape): string {
const extendString =
' ' +
component.extendsProps
@@ -9,6 +9,16 @@
*/
'use strict';
import type {
StringTypeAnnotation,
ReservedPropTypeAnnotation,
ObjectTypeAnnotation,
Int32TypeAnnotation,
FloatTypeAnnotation,
DoubleTypeAnnotation,
ComponentShape,
BooleanTypeAnnotation,
} from '../../CodegenSchema';
const {
convertDefaultTypeToString,
@@ -257,7 +267,7 @@ static inline std::string toString(const ${enumMask} &value) {
}
`.trim();
function getClassExtendString(component): string {
function getClassExtendString(component: ComponentShape): string {
if (component.extendsProps.length === 0) {
throw new Error('Invalid: component.extendsProps is empty');
}
@@ -286,7 +296,29 @@ function getClassExtendString(component): string {
function getNativeTypeFromAnnotation(
componentName: string,
prop,
prop:
| NamedShape<PropTypeAnnotation>
| {
name: string,
typeAnnotation:
| $FlowFixMe
| DoubleTypeAnnotation
| FloatTypeAnnotation
| BooleanTypeAnnotation
| Int32TypeAnnotation
| StringTypeAnnotation
| ObjectTypeAnnotation<PropTypeAnnotation>
| ReservedPropTypeAnnotation
| {
+default: string,
+options: $ReadOnlyArray<string>,
+type: 'StringEnumTypeAnnotation',
}
| {
+elementType: ObjectTypeAnnotation<PropTypeAnnotation>,
+type: 'ArrayTypeAnnotation',
},
},
nameParts: $ReadOnlyArray<string>,
): string {
const typeAnnotation = prop.typeAnnotation;
@@ -400,7 +432,10 @@ function generateArrayEnumString(
});
}
function generateStringEnum(componentName, prop) {
function generateStringEnum(
componentName: string,
prop: NamedShape<PropTypeAnnotation>,
) {
const typeAnnotation = prop.typeAnnotation;
if (typeAnnotation.type === 'StringEnumTypeAnnotation') {
const values: $ReadOnlyArray<string> = typeAnnotation.options;
@@ -435,7 +470,10 @@ function generateStringEnum(componentName, prop) {
return '';
}
function generateIntEnum(componentName, prop) {
function generateIntEnum(
componentName: string,
prop: NamedShape<PropTypeAnnotation>,
) {
const typeAnnotation = prop.typeAnnotation;
if (typeAnnotation.type === 'Int32EnumTypeAnnotation') {
const values: $ReadOnlyArray<number> = typeAnnotation.options;
@@ -476,7 +514,10 @@ function generateIntEnum(componentName, prop) {
return '';
}
function generateEnumString(componentName: string, component): string {
function generateEnumString(
componentName: string,
component: ComponentShape,
): string {
return component.props
.map(prop => {
if (
@@ -567,7 +608,13 @@ function getLocalImports(
): Set<string> {
const imports: Set<string> = new Set();
function addImportsForNativeName(name) {
function addImportsForNativeName(
name:
| 'ColorPrimitive'
| 'EdgeInsetsPrimitive'
| 'ImageSourcePrimitive'
| 'PointPrimitive',
) {
switch (name) {
case 'ColorPrimitive':
imports.add('#include <react/renderer/graphics/Color.h>');
@@ -635,7 +682,10 @@ function getLocalImports(
return imports;
}
function generateStructsForComponent(componentName: string, component): string {
function generateStructsForComponent(
componentName: string,
component: ComponentShape,
): string {
const structs = generateStructs(componentName, component.props, []);
const structArray = Array.from(structs.values());
if (structArray.length < 1) {
@@ -646,8 +696,8 @@ function generateStructsForComponent(componentName: string, component): string {
function generateStructs(
componentName: string,
properties,
nameParts,
properties: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
nameParts: Array<string>,
): StructsMap {
const structs: StructsMap = new Map();
properties.forEach(prop => {
@@ -9,6 +9,7 @@
*/
'use strict';
import type {CommandParamTypeAnnotation} from '../../CodegenSchema';
import type {
NamedShape,
@@ -170,7 +171,10 @@ function generatePropCasesString(
}`;
}
function getCommandArgJavaType(param, index) {
function getCommandArgJavaType(
param: NamedShape<CommandParamTypeAnnotation>,
index: number,
) {
const {typeAnnotation} = param;
switch (typeAnnotation.type) {
@@ -229,7 +233,7 @@ function generateCommandCasesString(
return commandMethods;
}
function getClassExtendString(component): string {
function getClassExtendString(component: ComponentShape): string {
const extendString = component.extendsProps
.map(extendProps => {
switch (extendProps.type) {
@@ -251,7 +255,7 @@ function getClassExtendString(component): string {
return extendString;
}
function getDelegateImports(component) {
function getDelegateImports(component: ComponentShape) {
const imports = getImports(component, 'delegate');
// The delegate needs ReadableArray for commands always.
// The interface doesn't always need it
@@ -265,7 +269,10 @@ function getDelegateImports(component) {
return imports;
}
function generateMethods(propsString, commandsString): string {
function generateMethods(
propsString: string,
commandsString: null | string,
): string {
return [
PropSetterTemplate({propCases: propsString}),
commandsString != null
@@ -9,6 +9,7 @@
*/
'use strict';
import type {CommandParamTypeAnnotation} from '../../CodegenSchema';
import type {
NamedShape,
@@ -56,13 +57,13 @@ public interface ${className}<T extends ${extendClasses}> {
}
`;
function addNullable(imports) {
function addNullable(imports: Set<string>) {
imports.add('import androidx.annotation.Nullable;');
}
function getJavaValueForProp(
prop: NamedShape<PropTypeAnnotation>,
imports,
imports: Set<string>,
): string {
const typeAnnotation = prop.typeAnnotation;
@@ -126,7 +127,7 @@ function getJavaValueForProp(
}
}
function generatePropsString(component: ComponentShape, imports) {
function generatePropsString(component: ComponentShape, imports: Set<string>) {
if (component.props.length === 0) {
return '// No props';
}
@@ -140,7 +141,7 @@ function generatePropsString(component: ComponentShape, imports) {
.join('\n' + ' ');
}
function getCommandArgJavaType(param) {
function getCommandArgJavaType(param: NamedShape<CommandParamTypeAnnotation>) {
const {typeAnnotation} = param;
switch (typeAnnotation.type) {
@@ -198,7 +199,7 @@ function generateCommandsString(
.join('\n' + ' ');
}
function getClassExtendString(component): string {
function getClassExtendString(component: ComponentShape): string {
const extendString = component.extendsProps
.map(extendProps => {
switch (extendProps.type) {
@@ -9,6 +9,7 @@
*/
'use strict';
import type {PropTypeAnnotation, ComponentShape} from '../../CodegenSchema';
import type {SchemaType} from '../../CodegenSchema';
const {getImports, toSafeCppString} = require('./CppHelpers');
@@ -76,7 +77,10 @@ TEST(${componentName}_${testName}, etc) {
}
`;
function getTestCasesForProp(propName, typeAnnotation) {
function getTestCasesForProp(
propName: string,
typeAnnotation: PropTypeAnnotation,
) {
const cases = [];
if (typeAnnotation.type === 'StringEnumTypeAnnotation') {
typeAnnotation.options.forEach(option =>
@@ -134,7 +138,7 @@ function getTestCasesForProp(propName, typeAnnotation) {
return cases;
}
function generateTestsString(name, component) {
function generateTestsString(name: string, component: ComponentShape) {
function createTest({testName, propName, propValue, raw = false}: TestCase) {
const value =
!raw && typeof propValue === 'string' ? `"${propValue}"` : propValue;
@@ -127,7 +127,7 @@ function serializeArg(
realTypeAnnotation = resolveAlias(realTypeAnnotation.name);
}
function wrap(callback) {
function wrap(callback: (val: string) => string) {
const val = `args[${index}]`;
const expression = callback(val);
@@ -119,7 +119,7 @@ function translatePrimitiveJSTypeToCpp(
realTypeAnnotation = resolveAlias(realTypeAnnotation.name);
}
function wrap(type) {
function wrap(type: string) {
return nullable ? `std::optional<${type}>` : type;
}
@@ -9,6 +9,7 @@
*/
'use strict';
import type {ASTNode} from '../utils';
const {getValueFromTypes} = require('../utils.js');
@@ -177,7 +178,7 @@ function getTypeAnnotationForArray(
function getTypeAnnotation(
name: string,
annotation,
annotation: $FlowFixMe | ASTNode,
defaultValue: $FlowFixMe | null,
withNullDefault: boolean,
types: TypeDeclarationMap,
@@ -712,7 +712,7 @@ describe('Flow Module Parser', () => {
const RETURN_TYPE_DESCRIPTION = IS_RETURN_TYPE_NULLABLE
? 'a nullable'
: 'a non-nullable';
const annotateRet = retType =>
const annotateRet = (retType: string) =>
IS_RETURN_TYPE_NULLABLE ? `?${retType}` : retType;
function parseReturnType(
@@ -927,7 +927,7 @@ describe('Flow Module Parser', () => {
? 'an optional'
: 'a required';
function annotateProp(propName, propType) {
function annotateProp(propName: string, propType: string) {
if (nullable && optional) {
return `${propName}?: ?${propType}`;
}
@@ -1229,7 +1229,7 @@ describe('Flow Module Parser', () => {
});
});
function parseModule(source) {
function parseModule(source: string) {
const schema = parseString(source, `${MODULE_NAME}.js`);
const module = schema.modules.NativeFoo;
invariant(
@@ -549,7 +549,7 @@ function buildPropertySchema(
};
}
function isModuleInterface(node) {
function isModuleInterface(node: $FlowFixMe) {
return (
node.type === 'InterfaceDeclaration' &&
node.extends.length === 1 &&
@@ -9,6 +9,7 @@
*/
'use strict';
import type {ASTNode} from '../utils';
const {getValueFromTypes} = require('../utils.js');
@@ -221,7 +222,7 @@ function getTypeAnnotationForArray(
function getTypeAnnotation(
name: string,
annotation,
annotation: $FlowFixMe | ASTNode,
defaultValue: $FlowFixMe | null,
withNullDefault: boolean,
types: TypeDeclarationMap,
@@ -714,7 +714,7 @@ describe('TypeScript Module Parser', () => {
const RETURN_TYPE_DESCRIPTION = IS_RETURN_TYPE_NULLABLE
? 'a nullable'
: 'a non-nullable';
const annotateRet = retType =>
const annotateRet = (retType: string) =>
IS_RETURN_TYPE_NULLABLE ? `${retType} | null | void` : retType;
function parseReturnType(
@@ -927,7 +927,7 @@ describe('TypeScript Module Parser', () => {
? 'an optional'
: 'a required';
function annotateProp(propName, propType) {
function annotateProp(propName: string, propType: string) {
if (nullable && optional) {
return `${propName}?: ${propType} | null | void`;
}
@@ -1231,7 +1231,7 @@ describe('TypeScript Module Parser', () => {
});
});
function parseModule(source) {
function parseModule(source: string) {
const schema = parseString(source, `${MODULE_NAME}.ts`);
const module = schema.modules.NativeFoo;
invariant(
@@ -551,7 +551,7 @@ function buildPropertySchema(
};
}
function isModuleInterface(node) {
function isModuleInterface(node: $FlowFixMe) {
return (
node.type === 'TSInterfaceDeclaration' &&
node.extends.length === 1 &&
@@ -189,7 +189,7 @@ class Circle extends React.Component<any, any> {
</Animated.View>
);
}
_toggleIsActive = velocity => {
_toggleIsActive = (velocity: void) => {
const config = {tension: 30, friction: 7};
if (this.state.isActive) {
Animated.spring(this.props.openVal, {
@@ -311,7 +311,7 @@ function distance(p1: Point, p2: Point): number {
return dx * dx + dy * dy;
}
function moveToClosest({activeKey, keys, restLayouts}, position) {
function moveToClosest({activeKey, keys, restLayouts}: any, position: Point) {
const activeIdx = -1;
let closestIdx = activeIdx;
let minDist = Infinity;
@@ -15,7 +15,7 @@ const React = require('react');
const {Alert, Button, View, StyleSheet} = require('react-native');
const {RNTesterThemeContext} = require('../../components/RNTesterTheme');
function onButtonPress(buttonName) {
function onButtonPress(buttonName: string) {
Alert.alert(`Your application has been ${buttonName}!`);
}
@@ -8,6 +8,7 @@
* @flow
*/
import type {RenderItemProps} from 'react-native/Libraries/Lists/VirtualizedList';
import type {
ViewStyleProp,
TextStyle,
@@ -73,7 +74,7 @@ const TableRow = React.memo(
},
);
function renderTableRow({item}) {
function renderTableRow({item}: RenderItemProps<PlatformTestResult>) {
return <TableRow testResult={item} />;
}
@@ -60,19 +60,19 @@ export function check_PointerEvent(
// * if the attribute is "readonly", it cannot be changed
// TA: 1.1, 1.2
const idl_type_check = {
long: function (v) {
long: function (v: any) {
return typeof v === 'number' && Math.round(v) === v;
},
float: function (v) {
float: function (v: any) {
return typeof v === 'number';
},
string: function (v) {
string: function (v: any) {
return typeof v === 'string';
},
boolean: function (v) {
boolean: function (v: any) {
return typeof v === 'boolean';
},
object: function (v) {
object: function (v: any) {
return typeof v === 'object';
},
};
@@ -189,7 +189,8 @@ export function useTestEventHandler(
handler: (event: any, eventName: string) => void,
): ViewProps {
const eventProps: any = useMemo(() => {
const handlerFactory = eventName => event => handler(event, eventName);
const handlerFactory = (eventName: string) => (event: any) =>
handler(event, eventName);
const props = {};
for (const eventName of eventNames) {
const eventPropName =
@@ -8,6 +8,7 @@
* @flow
*/
import type {PointerEvent} from 'react-native/Libraries/Types/CoreEventTypes';
import {Button, StyleSheet, ScrollView, View, Text} from 'react-native';
import * as React from 'react';
import type {ViewProps} from 'react-native/Libraries/Components/View/ViewPropTypes';
@@ -55,7 +56,7 @@ function EventfulView(props: {|
} = props;
const [tag, setTag] = React.useState('');
const eventLog = eventName => event => {
const eventLog = (eventName: string) => (event: PointerEvent) => {
// $FlowFixMe Using private property
log(`${name} - ${eventName} - target: ${event.target._nativeTag}`);
};
@@ -159,7 +160,7 @@ function PointerEventScaffolding({
}) {
const [eventsLog, setEventsLog] = React.useState('');
const clear = () => setEventsLog('');
const log = eventStr => {
const log = (eventStr: string) => {
setEventsLog(currentEventsLog => `${eventStr}\n${currentEventsLog}`);
};
return (
@@ -16,7 +16,8 @@ import * as React from 'react';
export function FlatList_onEndReached(): React.Node {
const [output, setOutput] = React.useState('');
const exampleProps = {
onEndReached: info => setOutput('onEndReached'),
onEndReached: (info: {distanceFromEnd: number, ...}) =>
setOutput('onEndReached'),
onEndReachedThreshold: 0,
};
const ref = React.useRef(null);
@@ -15,8 +15,13 @@ import {StyleSheet, View, Text} from 'react-native';
import * as React from 'react';
const Separator =
(defaultColor, highlightColor) =>
({leadingItem, trailingItem, highlighted, hasBeenHighlighted}) => {
(defaultColor: string, highlightColor: string) =>
({
leadingItem,
trailingItem,
highlighted,
hasBeenHighlighted,
}: $FlowFixMe) => {
const text = `Separator for leading ${leadingItem} and trailing ${trailingItem} has ${
!hasBeenHighlighted ? 'not ' : ''
}been pressed`;
@@ -10,6 +10,8 @@
'use strict';
import type {LayoutEvent} from 'react-native/Libraries/Types/CoreEventTypes';
const React = require('react');
const {
@@ -451,7 +453,7 @@ class OnLayoutExample extends React.Component<
layoutHandlerMessage: 'No Message',
};
onLayoutHandler = event => {
onLayoutHandler = (event: LayoutEvent) => {
this.setState({
width: this.state.width,
height: this.state.height,
@@ -42,7 +42,11 @@ const TextInputForm = () => {
);
};
const CloseButton = props => {
const CloseButton = (
props:
| {behavior: any, setModalOpen: any}
| {behavior: string, setModalOpen: any},
) => {
return (
<View
style={[
@@ -10,6 +10,8 @@
'use strict';
import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue';
const React = require('react');
const {
@@ -313,7 +315,7 @@ class TrackingExample extends React.Component<
this.state.toJS.setValue(nextValue);
};
renderBlock = (anim, dest) => [
renderBlock = (anim: any | AnimatedValue, dest: any | AnimatedValue) => [
<Animated.View
key="line"
style={[styles.line, {transform: [{translateX: dest}]}]}
@@ -268,7 +268,7 @@ const exampleClasses: Array<ExampleClass> = [
},
];
const infoToExample = info => {
const infoToExample = (info: ExampleClass) => {
return {
title: info.title,
description: info.description,
@@ -84,7 +84,7 @@ function TextOnPressBox() {
function PressableFeedbackEvents() {
const [eventLog, setEventLog] = useState([]);
function appendEvent(eventName) {
function appendEvent(eventName: string) {
const limit = 6;
setEventLog(current => {
return [eventName].concat(current.slice(0, limit - 1));
@@ -120,7 +120,7 @@ function PressableFeedbackEvents() {
function PressableDelayEvents() {
const [eventLog, setEventLog] = useState([]);
function appendEvent(eventName) {
function appendEvent(eventName: string) {
const limit = 6;
const newEventLog = eventLog.slice(0, limit - 1);
newEventLog.unshift(eventName);
@@ -43,7 +43,7 @@ const IMAGE_SIZE = [IMAGE_DIMENSION, IMAGE_DIMENSION];
const IS_RTL = I18nManager.isRTL;
function ListItem(props) {
function ListItem(props: {imageSource: number}) {
return (
<View style={styles.row}>
<View style={styles.column1}>
@@ -127,7 +127,10 @@ const IconsExample = withRTLState(({isRTL, setRTL}) => {
);
});
function AnimationBlock(props) {
function AnimationBlock(props: {
imgStyle: {transform: Array<{scaleX: number} | {translateX: any}>},
onPress: (e: any) => void,
}) {
return (
<View style={styles.block}>
<TouchableWithoutFeedback onPress={props.onPress}>
@@ -144,7 +147,13 @@ type RTLSwitcherComponentState = {|
isRTL: boolean,
|};
function withRTLState(Component) {
function withRTLState(
Component: ({
isRTL: boolean,
setRTL: (isRTL: boolean) => void,
style?: any,
}) => React.Node,
) {
return class extends React.Component<
{style?: any},
RTLSwitcherComponentState,
@@ -157,7 +166,7 @@ function withRTLState(Component) {
}
render() {
const setRTL = isRTL => this.setState({isRTL: isRTL});
const setRTL = (isRTL: boolean) => this.setState({isRTL: isRTL});
return (
<Component isRTL={this.state.isRTL} setRTL={setRTL} {...this.props} />
);
@@ -165,7 +174,12 @@ function withRTLState(Component) {
};
}
const RTLToggler = ({isRTL, setRTL}) => {
const RTLToggler = ({
isRTL,
setRTL,
}:
| {isRTL: any, setRTL: any}
| {isRTL: boolean, setRTL: (isRTL: boolean) => void}) => {
if (Platform.OS === 'android') {
return <Text style={styles.rtlToggler}>{isRTL ? 'RTL' : 'LTR'}</Text>;
}
@@ -528,7 +542,7 @@ const BorderExample = withRTLState(({isRTL, setRTL}) => {
);
});
const directionStyle = isRTL =>
const directionStyle = (isRTL: boolean) =>
Platform.OS !== 'android' ? {direction: isRTL ? 'rtl' : 'ltr'} : null;
const styles = StyleSheet.create({
@@ -32,7 +32,7 @@ class SafeAreaViewExample extends React.Component<
modalVisible: false,
};
_setModalVisible = visible => {
_setModalVisible = (visible: boolean) => {
this.setState({modalVisible: visible});
};
@@ -732,7 +732,7 @@ const RefreshControlExample = () => {
wait(2000).then(() => setRefreshing(false));
}, []);
const wait = timeout => {
const wait = (timeout: number) => {
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
@@ -1253,7 +1253,9 @@ class Item extends React.PureComponent<{|
let ITEMS = [...Array(12)].map((_, i) => `Item ${i}`);
const createItemRow = (msg, index) => <Item key={index} msg={msg} />;
const createItemRow = (msg: string, index: number) => (
<Item key={index} msg={msg} />
);
const Button = (props: {
active?: boolean,
@@ -14,7 +14,8 @@ import * as React from 'react';
export function SectionList_onEndReached(): React.Node {
const [output, setOutput] = React.useState('');
const exampleProps = {
onEndReached: info => setOutput('onEndReached'),
onEndReached: (info: {distanceFromEnd: number, ...}) =>
setOutput('onEndReached'),
onEndReachedThreshold: 0,
};
const ref = React.useRef(null);
@@ -8,6 +8,7 @@
* @flow
*/
import type {ViewToken} from 'react-native/Libraries/Lists/ViewabilityHelper';
import SectionListBaseExample from './SectionListBaseExample';
import {View, StyleSheet, SectionList} from 'react-native';
import * as React from 'react';
@@ -30,7 +31,11 @@ export function SectionList_onViewableItemsChanged(props: {
const {viewabilityConfig, offScreen, horizontal, useScrollRefScroll} = props;
const [output, setOutput] = React.useState('');
const exampleProps = {
onViewableItemsChanged: info =>
onViewableItemsChanged: (info: {
changed: Array<ViewToken>,
viewableItems: Array<ViewToken>,
...
}) =>
setOutput(
info.viewableItems
.filter(viewToken => viewToken.index != null && viewToken.isViewable)
@@ -9,6 +9,7 @@
*/
'use strict';
import type {Item} from '../../components/ListExampleShared';
const RNTesterPage = require('../../components/RNTesterPage');
const React = require('react');
@@ -108,7 +109,7 @@ const EmptySectionList = () => (
);
const renderItemComponent =
setItemState =>
(setItemState: (item: Item) => void) =>
({item, separators}) => {
if (isNaN(item.key)) {
return;
@@ -164,7 +165,7 @@ export function SectionList_scrollable(Props: {
const [data, setData] = React.useState(genItemData(1000));
const filterRegex = new RegExp(String(filterText), 'i');
const filter = item =>
const filter = (item: Item) =>
filterRegex.test(item.text) || filterRegex.test(item.title);
const filteredData = data.filter(filter);
const filteredSectionData = [...CONSTANT_SECTION_EXAMPLES];
@@ -181,7 +182,7 @@ export function SectionList_scrollable(Props: {
startIndex = ii;
}
const setItemPress = item => {
const setItemPress = (item: Item) => {
if (isNaN(item.key)) {
return;
}
@@ -190,7 +191,7 @@ export function SectionList_scrollable(Props: {
};
const ref = React.useRef<?React.ElementRef<typeof SectionList>>(null);
const scrollToLocation = (sectionIndex, itemIndex) => {
const scrollToLocation = (sectionIndex: number, itemIndex: number) => {
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
if (ref != null && ref.current?.scrollToLocation != null) {
ref.current.scrollToLocation({sectionIndex, itemIndex});
@@ -13,8 +13,8 @@ import {View, Text, StyleSheet} from 'react-native';
import * as React from 'react';
const Separator =
(defaultColor, highlightColor, isSectionSeparator) =>
({leadingItem, trailingItem, highlighted, hasBeenHighlighted}) => {
(defaultColor: string, highlightColor: string, isSectionSeparator: boolean) =>
({leadingItem, trailingItem, highlighted, hasBeenHighlighted}: any) => {
const text = `${
isSectionSeparator ? 'Section ' : ''
}separator for leading ${leadingItem} and trailing ${trailingItem} has ${
@@ -8,6 +8,8 @@
* @format
*/
import type {RenderItemProps} from 'react-native/Libraries/Lists/VirtualizedList';
import * as React from 'react';
import {
Animated,
@@ -49,7 +51,7 @@ function SwipeableCardExample() {
const incrementCurrent = () => setCurrentIndex(currentIndex + 1);
const getCardColor = index => cardColors[index % cardColors.length];
const getCardColor = (index: number) => cardColors[index % cardColors.length];
/*
* The cards try to reuse the views. Instead of always rebuilding the current card on top
@@ -140,7 +142,7 @@ function SwipeableCard(props: {
const cardData = Array(5);
function Card(props: {color: string}) {
const renderItem = ({item, index}) => (
const renderItem = ({item, index}: RenderItemProps<$FlowFixMe>) => (
<CardSection color={props.color} index={index} />
);
@@ -46,7 +46,7 @@ class TextInputAccessoryViewChangeTextExample extends React.Component<
{...},
{text: string},
> {
constructor(props) {
constructor(props: void | {...}) {
super(props);
this.state = {text: 'Placeholder Text'};
}
@@ -79,7 +79,7 @@ class TextInputAccessoryViewChangeKeyboardExample extends React.Component<
{...},
{keyboardType: string, text: string},
> {
constructor(props) {
constructor(props: void | {...}) {
super(props);
this.state = {text: '', keyboardType: 'default'};
}
@@ -121,7 +121,7 @@ class TextInputAccessoryViewDefaultDoneButtonExample extends React.Component<
|}>,
{text: string},
> {
constructor(props) {
constructor(props: void | $ReadOnly<{keyboardType: KeyboardType}>) {
super(props);
this.state = {text: ''};
}
@@ -140,7 +140,7 @@ class TextInputAccessoryViewDefaultDoneButtonExample extends React.Component<
}
class RewriteExampleKana extends React.Component<$FlowFixMeProps, any> {
constructor(props) {
constructor(props: any | void) {
super(props);
this.state = {text: ''};
}
@@ -161,7 +161,7 @@ class RewriteExampleKana extends React.Component<$FlowFixMeProps, any> {
}
class SecureEntryExample extends React.Component<$FlowFixMeProps, any> {
constructor(props) {
constructor(props: any | void) {
super(props);
this.state = {
text: '',
@@ -209,7 +209,7 @@ class AutogrowingTextInputExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
constructor(props) {
constructor(props: any | void) {
super(props);
this.state = {
@@ -223,7 +223,7 @@ class AutogrowingTextInputExample extends React.Component<
};
}
UNSAFE_componentWillReceiveProps(props) {
UNSAFE_componentWillReceiveProps(props: any) {
this.setState({
multiline: props.multiline,
});
@@ -88,7 +88,7 @@ class WithLabel extends React.Component<$FlowFixMeProps> {
}
class RewriteExample extends React.Component<$FlowFixMeProps, any> {
constructor(props) {
constructor(props: any | void) {
super(props);
this.state = {text: ''};
}
@@ -122,7 +122,7 @@ class RewriteExampleInvalidCharacters extends React.Component<
$FlowFixMeProps,
any,
> {
constructor(props) {
constructor(props: any | void) {
super(props);
this.state = {text: ''};
}
@@ -150,7 +150,7 @@ class RewriteInvalidCharactersAndClearExample extends React.Component<
> {
inputRef: ?React.ElementRef<typeof TextInput> = null;
constructor(props) {
constructor(props: any | void) {
super(props);
this.state = {text: ''};
}
@@ -248,7 +248,7 @@ class TextEventsExample extends React.Component<{...}, $FlowFixMeState> {
prev3Text: '<No Event>',
};
updateText = text => {
updateText = (text: string) => {
this.setState(state => {
return {
curText: text,
@@ -305,7 +305,7 @@ class TokenizedTextExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
constructor(props) {
constructor(props: any | void) {
super(props);
this.state = {text: 'Hello #World'};
}
@@ -396,7 +396,7 @@ class SelectionExample extends React.Component<
return Math.round(Math.random() * length);
}
select(start, end) {
select(start: number, end: number) {
this._textInput?.focus();
this.setState({selection: {start, end}});
if (this.props.imperative) {
@@ -412,7 +412,7 @@ class SelectionExample extends React.Component<
this.select(...positions);
}
placeAt(position) {
placeAt(position: number) {
this.select(position, position);
}
@@ -15,7 +15,7 @@ const React = require('react');
const {Alert, Platform, ToastAndroid, Text, View} = require('react-native');
function burnCPU(milliseconds) {
function burnCPU(milliseconds: number) {
const start = global.performance.now();
while (global.performance.now() < start + milliseconds) {}
}
@@ -117,7 +117,11 @@ class RequestIdleCallbackTester extends React.Component<
this._idleTimer = null;
}
const handler = deadline => {
const handler = (deadline: {
didTimeout: boolean,
timeRemaining: () => number,
...
}) => {
while (deadline.timeRemaining() > 5) {
burnCPU(5);
this.setState({
@@ -181,7 +181,7 @@ class TouchableFeedbackEvents extends React.Component<{...}, $FlowFixMeState> {
);
}
_appendEvent = eventName => {
_appendEvent = (eventName: string) => {
const limit = 6;
const eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
@@ -222,7 +222,7 @@ class TouchableDelayEvents extends React.Component<{...}, $FlowFixMeState> {
);
}
_appendEvent = eventName => {
_appendEvent = (eventName: string) => {
const limit = 6;
const eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
@@ -73,7 +73,33 @@ class SampleTurboModuleExample extends React.Component<{||}, State> {
NativeSampleTurboModule.getValue(5, 'test', {a: 1, b: 'foo'}),
};
_setResult(name, result) {
_setResult(
name:
| string
| 'callback'
| 'getArray'
| 'getBool'
| 'getConstants'
| 'getNumber'
| 'getObject'
| 'getRootTag'
| 'getString'
| 'getUnsafeObject'
| 'getValue'
| 'promise'
| 'rejectPromise'
| 'voidFunc',
result:
| $FlowFixMe
| void
| RootTag
| Promise<mixed>
| number
| string
| boolean
| {const1: boolean, const2: number, const3: string}
| Array<$FlowFixMe>,
) {
this.setState(({testResults}) => ({
/* $FlowFixMe[cannot-spread-indexer] (>=0.122.0 site=react_native_fb)
* This comment suppresses an error found when Flow v0.122.0 was
@@ -88,7 +114,22 @@ class SampleTurboModuleExample extends React.Component<{||}, State> {
}));
}
_renderResult(name) {
_renderResult(
name:
| 'callback'
| 'getArray'
| 'getBool'
| 'getConstants'
| 'getNumber'
| 'getObject'
| 'getRootTag'
| 'getString'
| 'getUnsafeObject'
| 'getValue'
| 'promise'
| 'rejectPromise'
| 'voidFunc',
) {
const result = this.state.testResults[name] || {};
return (
<View style={styles.result}>