From 1e63996a1096a62fa18884735247fbf2b104bf81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Fri, 27 Mar 2020 18:41:12 +0100 Subject: [PATCH] [react-native] Prepare for 0.62 (#43179) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Feature: unstable_enableLogBox function at 0.62 * [@types/react-native] Add Appearance namespace for new api from v0.62.x * feat: add typing for useColorScheme hook * Add type for fadingEdgeLength prop This adds the types for FlatList and ScrollView on Android * [react-native] Introduce HostComponent * [react-native] Make useNativeDriver parameter required * https://github.com/facebook/react-native/commit/d123bea8c1a4f1c977928fa2cfffe19132f74dab * https://github.com/facebook/react-native/commit/5876052615f4858ed5fc32fa3da9b64695974238 * feat: add typings for A11yValue in RN * [react-native] Import v0.61 typings * [react-native] Run prettier * [react-native] Try fixing v0.61 on CI * [react-native] Defer v0.61 typings to next iteration Co-authored-by: Shinpei Co-authored-by: Jérémy Barbet Co-authored-by: André Krüger Co-authored-by: Kacper Wiszczuk --- .../react-native-sortable-list-tests.tsx | 12 +- types/react-native/globals.d.ts | 10 +- types/react-native/index.d.ts | 519 +++++++++++------- types/react-native/test/ART.tsx | 6 +- types/react-native/test/animated.tsx | 23 +- types/react-native/test/globals.tsx | 20 +- types/react-native/test/index.tsx | 369 +++++++------ types/react-native/test/legacy-properties.tsx | 4 +- .../react-primitives-tests.tsx | 3 +- 9 files changed, 560 insertions(+), 406 deletions(-) diff --git a/types/react-native-sortable-list/react-native-sortable-list-tests.tsx b/types/react-native-sortable-list/react-native-sortable-list-tests.tsx index 3a8732863c..7dd96db6f8 100644 --- a/types/react-native-sortable-list/react-native-sortable-list-tests.tsx +++ b/types/react-native-sortable-list/react-native-sortable-list-tests.tsx @@ -151,12 +151,14 @@ class Row extends React.Component { Animated.timing(style.transform[0].scale, { duration: 100, easing: Easing.out(Easing.quad), - toValue: 1.1 + toValue: 1.1, + useNativeDriver: false, }), Animated.timing(style.shadowRadius, { duration: 100, easing: Easing.out(Easing.quad), - toValue: 10 + toValue: 10, + useNativeDriver: false, }), ]).start(); } @@ -168,12 +170,14 @@ class Row extends React.Component { Animated.timing(style.transform[0].scale, { duration: 100, easing: Easing.out(Easing.quad), - toValue: 1 + toValue: 1, + useNativeDriver: false, }), Animated.timing(style.shadowRadius, { duration: 100, easing: Easing.out(Easing.quad), - toValue: 2 + toValue: 2, + useNativeDriver: false, }), ]).start(); } diff --git a/types/react-native/globals.d.ts b/types/react-native/globals.d.ts index 1367020d41..98c0e761e4 100644 --- a/types/react-native/globals.d.ts +++ b/types/react-native/globals.d.ts @@ -302,14 +302,14 @@ declare var WebSocket: { uri: string, protocols?: string | string[] | null, options?: { - headers: {[headerName: string]: string}; + headers: { [headerName: string]: string }; [optionName: string]: any; } | null, ): WebSocket; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; }; // diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index fdbd0ea648..1392e7129d 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native 0.61 +// Type definitions for react-native 0.62 // Project: https://github.com/facebook/react-native // Definitions by: Eloy Durán // HuHuanming @@ -34,6 +34,8 @@ // Abe Dolinger // Dominique Richard // Mohamed Shaban +// André Krüger +// Jérémy Barbet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -85,7 +87,7 @@ interface EventSubscription { * @param subscriber the subscriber that controls * this subscription. */ - new(subscriber: EventSubscriptionVendor): EventSubscription; + new (subscriber: EventSubscriptionVendor): EventSubscription; /** * Removes this subscription from the subscriber that controls it. @@ -150,7 +152,7 @@ interface EmitterSubscription extends EventSubscription { * @param context - Optional context object to use when invoking the * listener */ - new( + new ( emitter: EventEmitter, subscriber: EventSubscriptionVendor, listener: () => any, @@ -277,7 +279,8 @@ declare class EventEmitter { removeListener(eventType: string, listener: (...args: any[]) => any): void; } -/** NativeMethodsMixin provides methods to access the underlying native component directly. +/** + * NativeMethods provides methods to access the underlying native component directly. * This can be useful in cases when you want to focus a view or measure its on-screen dimensions, * for example. * The methods described here are available on most of the default components provided by React Native. @@ -286,7 +289,7 @@ declare class EventEmitter { * For more information, see [Direct Manipulation](http://facebook.github.io/react-native/docs/direct-manipulation.html). * @see https://github.com/facebook/react-native/blob/master/Libraries/ReactIOS/NativeMethodsMixin.js */ -export interface NativeMethodsMixinStatic { +export interface NativeMethods { /** * Determines the location on screen, width, and height of the given view and * returns the values via an async callback. If successful, the callback will @@ -361,6 +364,27 @@ export interface NativeMethodsMixinStatic { }; } +/** + * @deprecated Use NativeMethods instead. + */ +export type NativeMethodsMixin = NativeMethods; +/** + * @deprecated Use NativeMethods instead. + */ +export type NativeMethodsMixinType = NativeMethods; + +/** + * Represents a native component, such as those returned from `requireNativeComponent`. + * + * @see https://github.com/facebook/react-native/blob/v0.62.0-rc.5/Libraries/Renderer/shims/ReactNativeTypes.js + * + * @todo This should eventually be defined as an AbstractComponent, but that + * should first be introduced in the React typings. + */ +export interface HostComponent

extends Pick, Exclude, 'new'>> { + new (props: P, context?: any): React.Component

& Readonly; +} + // see react-jsx.d.ts export function createElement

( type: React.ReactType, @@ -376,7 +400,7 @@ type TaskProvider = () => Task; type NodeHandle = number; // Similar to React.SyntheticEvent except for nativeEvent -export interface NativeSyntheticEvent extends React.BaseSyntheticEvent { } +export interface NativeSyntheticEvent extends React.BaseSyntheticEvent {} export interface NativeTouchEvent { /** @@ -425,7 +449,7 @@ export interface NativeTouchEvent { touches: NativeTouchEvent[]; } -export interface GestureResponderEvent extends NativeSyntheticEvent { } +export interface GestureResponderEvent extends NativeSyntheticEvent {} // See https://facebook.github.io/react-native/docs/scrollview.html#contentoffset export interface PointPropType { @@ -901,9 +925,9 @@ export interface TextProps extends TextPropsIOS, TextPropsAndroid, Accessibility /** * A React component for displaying text which supports nesting, styling, and touch handling. */ -declare class TextComponent extends React.Component { } -declare const TextBase: Constructor & typeof TextComponent; -export class Text extends TextBase { } +declare class TextComponent extends React.Component {} +declare const TextBase: Constructor & typeof TextComponent; +export class Text extends TextBase {} type DataDetectorTypes = 'phoneNumber' | 'link' | 'address' | 'calendarEvent' | 'none' | 'all'; @@ -917,7 +941,7 @@ type DataDetectorTypes = 'phoneNumber' | 'link' | 'address' | 'calendarEvent' | * components re-render. */ export interface DocumentSelectionState extends EventEmitter { - new(anchor: number, focus: number): DocumentSelectionState; + new (anchor: number, focus: number): DocumentSelectionState; /** * Apply an update to the state. If either offset value has changed, @@ -1062,34 +1086,34 @@ export interface TextInputIOSProps { * */ textContentType?: - | 'none' - | 'URL' - | 'addressCity' - | 'addressCityAndState' - | 'addressState' - | 'countryName' - | 'creditCardNumber' - | 'emailAddress' - | 'familyName' - | 'fullStreetAddress' - | 'givenName' - | 'jobTitle' - | 'location' - | 'middleName' - | 'name' - | 'namePrefix' - | 'nameSuffix' - | 'nickname' - | 'organizationName' - | 'postalCode' - | 'streetAddressLine1' - | 'streetAddressLine2' - | 'sublocality' - | 'telephoneNumber' - | 'username' - | 'password' - | 'newPassword' - | 'oneTimeCode'; + | 'none' + | 'URL' + | 'addressCity' + | 'addressCityAndState' + | 'addressState' + | 'countryName' + | 'creditCardNumber' + | 'emailAddress' + | 'familyName' + | 'fullStreetAddress' + | 'givenName' + | 'jobTitle' + | 'location' + | 'middleName' + | 'name' + | 'namePrefix' + | 'nameSuffix' + | 'nickname' + | 'organizationName' + | 'postalCode' + | 'streetAddressLine1' + | 'streetAddressLine2' + | 'sublocality' + | 'telephoneNumber' + | 'username' + | 'password' + | 'newPassword' + | 'oneTimeCode'; /** * If false, scrolling of the text view will be disabled. The default value is true. Only works with multiline={true} @@ -1125,19 +1149,19 @@ export interface TextInputAndroidProps { * - `off` */ autoCompleteType?: - | 'cc-csc' - | 'cc-exp' - | 'cc-exp-month' - | 'cc-exp-year' - | 'cc-number' - | 'email' - | 'name' - | 'password' - | 'postal-code' - | 'street-address' - | 'tel' - | 'username' - | 'off'; + | 'cc-csc' + | 'cc-exp' + | 'cc-exp-month' + | 'cc-exp-year' + | 'cc-number' + | 'email' + | 'name' + | 'password' + | 'postal-code' + | 'street-address' + | 'tel' + | 'username' + | 'off'; /** * Determines whether the individual fields in your app should be included in a @@ -1154,12 +1178,7 @@ export interface TextInputAndroidProps { * - `yes` - is important for autofill * - `yesExcludeDescendants` - this view is important for autofill but its children aren't */ - importantForAutofill?: - | "auto" - | "no" - | "noExcludeDescendants" - | "yes" - | "yesExcludeDescendants"; + importantForAutofill?: 'auto' | 'no' | 'noExcludeDescendants' | 'yes' | 'yesExcludeDescendants'; /** * When false, if there is a small amount of space available around a text input (e.g. landscape orientation on a phone), @@ -1208,13 +1227,7 @@ export interface TextInputAndroidProps { textAlignVertical?: 'auto' | 'top' | 'bottom' | 'center'; } -export type KeyboardType = - | 'default' - | 'email-address' - | 'numeric' - | 'phone-pad' - | 'number-pad' - | 'decimal-pad'; +export type KeyboardType = 'default' | 'email-address' | 'numeric' | 'phone-pad' | 'number-pad' | 'decimal-pad'; export type KeyboardTypeIOS = | 'ascii-capable' | 'numbers-and-punctuation' @@ -1546,8 +1559,8 @@ interface TextInputState { /** * @see https://facebook.github.io/react-native/docs/textinput.html#methods */ -declare class TextInputComponent extends React.Component { } -declare const TextInputBase: Constructor & Constructor & typeof TextInputComponent; +declare class TextInputComponent extends React.Component {} +declare const TextInputBase: Constructor & Constructor & typeof TextInputComponent; export class TextInput extends TextInputBase { /** * Access the current focus state. @@ -1700,9 +1713,9 @@ export interface ToolbarAndroidProps extends ViewProps { * * [0]: https://developer.android.com/reference/android/support/v7/widget/Toolbar.html */ -declare class ToolbarAndroidComponent extends React.Component { } -declare const ToolbarAndroidBase: Constructor & typeof ToolbarAndroidComponent; -export class ToolbarAndroid extends ToolbarAndroidBase { } +declare class ToolbarAndroidComponent extends React.Component {} +declare const ToolbarAndroidBase: Constructor & typeof ToolbarAndroidComponent; +export class ToolbarAndroid extends ToolbarAndroidBase {} /** * Gesture recognition on mobile devices is much more complicated than web. @@ -2007,7 +2020,7 @@ export interface ViewPropsAndroid { } type Falsy = undefined | null | false; -interface RecursiveArray extends Array | RecursiveArray> { } +interface RecursiveArray extends Array | RecursiveArray> {} /** Keep a brand of 'T' so that calls to `StyleSheet.flatten` can take `RegisteredStyle` and return `T`. */ type RegisteredStyle = number & { __registeredStyleBrand: T }; export type StyleProp = T | RegisteredStyle | RecursiveArray | Falsy> | Falsy; @@ -2050,6 +2063,11 @@ export interface AccessibilityProps extends AccessibilityPropsAndroid, Accessibi * An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not obvious from the accessibility label. */ accessibilityHint?: string; + /** + * Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, + * it contains range information (minimum, current, and maximum). + */ + accessibilityValue?: AccessibilityValue; /** * When `accessible` is true, the system will try to invoke this function when the user performs an accessibility custom action. @@ -2131,6 +2149,28 @@ export interface AccessibilityState { expanded?: boolean; } +export interface AccessibilityValue { + /** + * The minimum value of this component's range. (should be an integer) + */ + min?: number; + + /** + * The maximum value of this component's range. (should be an integer) + */ + max?: number; + + /** + * The current value of this component's range. (should be an integer) + */ + now?: number; + + /** + * A textual description of this component's value. (will override minimum, current, and maximum if set) + */ + text?: string; +} + export type AccessibilityRole = | 'none' | 'button' @@ -2262,10 +2302,10 @@ type AccessibilityTrait = */ export interface ViewProps extends ViewPropsAndroid, - ViewPropsIOS, - GestureResponderHandlers, - Touchable, - AccessibilityProps { + ViewPropsIOS, + GestureResponderHandlers, + Touchable, + AccessibilityProps { /** * This defines how far a touch event can start away from the view. * Typical interface guidelines recommend touch targets that are at least @@ -2337,8 +2377,8 @@ export interface ViewProps * View maps directly to the native view equivalent on whatever platform React is running on, * whether that is a UIView,

, android.view, etc. */ -declare class ViewComponent extends React.Component { } -declare const ViewBase: Constructor & typeof ViewComponent; +declare class ViewComponent extends React.Component {} +declare const ViewBase: Constructor & typeof ViewComponent; export class View extends ViewBase { /** * Is 3D Touch / Force Touch available (i.e. will touch events include `force`) @@ -2416,8 +2456,8 @@ export interface ViewPagerAndroidProps extends ViewProps { pageMargin?: number; } -declare class ViewPagerAndroidComponent extends React.Component { } -declare const ViewPagerAndroidBase: Constructor & typeof ViewPagerAndroidComponent; +declare class ViewPagerAndroidComponent extends React.Component {} +declare const ViewPagerAndroidBase: Constructor & typeof ViewPagerAndroidComponent; export class ViewPagerAndroid extends ViewPagerAndroidBase { /** * A helper function to scroll to a specific page in the ViewPager. @@ -2436,9 +2476,9 @@ export class ViewPagerAndroid extends ViewPagerAndroidBase { * It is a component to solve the common problem of views that need to move out of the way of the virtual keyboard. * It can automatically adjust either its position or bottom padding based on the position of the keyboard. */ -declare class KeyboardAvoidingViewComponent extends React.Component { } +declare class KeyboardAvoidingViewComponent extends React.Component {} declare const KeyboardAvoidingViewBase: Constructor & typeof KeyboardAvoidingViewComponent; -export class KeyboardAvoidingView extends KeyboardAvoidingViewBase { } +export class KeyboardAvoidingView extends KeyboardAvoidingViewBase {} export interface KeyboardAvoidingViewProps extends ViewProps { behavior?: 'height' | 'position' | 'padding'; @@ -2516,9 +2556,9 @@ export interface SegmentedControlIOSProps extends ViewProps { * Moreover, and most importantly, Safe Area's paddings reflect physical limitation of the screen, * such as rounded corners or camera notches (aka sensor housing area on iPhone X). */ -declare class SafeAreaViewComponent extends React.Component { } -declare const SafeAreaViewBase: Constructor & typeof SafeAreaViewComponent; -export class SafeAreaView extends SafeAreaViewBase { } +declare class SafeAreaViewComponent extends React.Component {} +declare const SafeAreaViewBase: Constructor & typeof SafeAreaViewComponent; +export class SafeAreaView extends SafeAreaViewBase {} /** * A component which enables customization of the keyboard input accessory view on iOS. The input accessory view is @@ -2527,7 +2567,7 @@ export class SafeAreaView extends SafeAreaViewBase { } * To use this component wrap your custom toolbar with the InputAccessoryView component, and set a nativeID. Then, pass * that nativeID as the inputAccessoryViewID of whatever TextInput you desire. */ -export class InputAccessoryView extends React.Component { } +export class InputAccessoryView extends React.Component {} export interface InputAccessoryViewProps { backgroundColor?: string; @@ -2560,9 +2600,9 @@ export interface InputAccessoryViewProps { * /> * ```` */ -declare class SegmentedControlIOSComponent extends React.Component { } -declare const SegmentedControlIOSBase: Constructor & typeof SegmentedControlIOSComponent; -export class SegmentedControlIOS extends SegmentedControlIOSBase { } +declare class SegmentedControlIOSComponent extends React.Component {} +declare const SegmentedControlIOSBase: Constructor & typeof SegmentedControlIOSComponent; +export class SegmentedControlIOS extends SegmentedControlIOSBase {} export interface NavigatorIOSProps { /** @@ -2711,9 +2751,9 @@ export interface ActivityIndicatorProps extends ViewProps { style?: StyleProp; } -declare class ActivityIndicatorComponent extends React.Component { } -declare const ActivityIndicatorBase: Constructor & typeof ActivityIndicatorComponent; -export class ActivityIndicator extends ActivityIndicatorBase { } +declare class ActivityIndicatorComponent extends React.Component {} +declare const ActivityIndicatorBase: Constructor & typeof ActivityIndicatorComponent; +export class ActivityIndicator extends ActivityIndicatorBase {} /** * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props @@ -2800,11 +2840,11 @@ export interface DatePickerIOSProps extends ViewProps { timeZoneOffsetInMinutes?: number; } -declare class DatePickerIOSComponent extends React.Component { } -declare const DatePickerIOSBase: Constructor & typeof DatePickerIOSComponent; -export class DatePickerIOS extends DatePickerIOSBase { } +declare class DatePickerIOSComponent extends React.Component {} +declare const DatePickerIOSBase: Constructor & typeof DatePickerIOSComponent; +export class DatePickerIOS extends DatePickerIOSBase {} -export interface DrawerSlideEvent extends NativeSyntheticEvent { } +export interface DrawerSlideEvent extends NativeSyntheticEvent {} /** * @see DrawerLayoutAndroid.android.js @@ -2903,8 +2943,8 @@ interface DrawerPosition { Right: number; } -declare class DrawerLayoutAndroidComponent extends React.Component { } -declare const DrawerLayoutAndroidBase: Constructor & typeof DrawerLayoutAndroidComponent; +declare class DrawerLayoutAndroidComponent extends React.Component {} +declare const DrawerLayoutAndroidBase: Constructor & typeof DrawerLayoutAndroidComponent; export class DrawerLayoutAndroid extends DrawerLayoutAndroidBase { /** * drawer's positions. @@ -2933,7 +2973,7 @@ export interface PickerIOSItemProps { /** * @see PickerIOS.ios.js */ -export class PickerIOSItem extends React.Component { } +export class PickerIOSItem extends React.Component {} /** * @see Picker.js @@ -3037,8 +3077,8 @@ export interface PickerIOSProps extends ViewProps { * @see https://facebook.github.io/react-native/docs/pickerios.html * @see PickerIOS.ios.js */ -declare class PickerIOSComponent extends React.Component { } -declare const PickerIOSBase: Constructor & typeof PickerIOSComponent; +declare class PickerIOSComponent extends React.Component {} +declare const PickerIOSBase: Constructor & typeof PickerIOSComponent; export class PickerIOS extends PickerIOSBase { static Item: typeof PickerIOSItem; } @@ -3090,9 +3130,9 @@ export interface ProgressBarAndroidProps extends ViewProps { * React component that wraps the Android-only `ProgressBar`. This component is used to indicate * that the app is loading or there is some activity in the app. */ -declare class ProgressBarAndroidComponent extends React.Component { } -declare const ProgressBarAndroidBase: Constructor & typeof ProgressBarAndroidComponent; -export class ProgressBarAndroid extends ProgressBarAndroidBase { } +declare class ProgressBarAndroidComponent extends React.Component {} +declare const ProgressBarAndroidBase: Constructor & typeof ProgressBarAndroidComponent; +export class ProgressBarAndroid extends ProgressBarAndroidBase {} /** * @see https://facebook.github.io/react-native/docs/progressviewios.html @@ -3129,9 +3169,9 @@ export interface ProgressViewIOSProps extends ViewProps { */ trackImage?: ImageURISource | ImageURISource[]; } -declare class ProgressViewIOSComponent extends React.Component { } -declare const ProgressViewIOSBase: Constructor & typeof ProgressViewIOSComponent; -export class ProgressViewIOS extends ProgressViewIOSBase { } +declare class ProgressViewIOSComponent extends React.Component {} +declare const ProgressViewIOSBase: Constructor & typeof ProgressViewIOSComponent; +export class ProgressViewIOS extends ProgressViewIOSBase {} export interface RefreshControlPropsIOS extends ViewProps { /** @@ -3198,13 +3238,13 @@ export interface RefreshControlProps extends RefreshControlPropsIOS, RefreshCont * __Note:__ `refreshing` is a controlled prop, this is why it needs to be set to true * in the `onRefresh` function otherwise the refresh indicator will stop immediately. */ -declare class RefreshControlComponent extends React.Component { } -declare const RefreshControlBase: Constructor & typeof RefreshControlComponent; +declare class RefreshControlComponent extends React.Component {} +declare const RefreshControlBase: Constructor & typeof RefreshControlComponent; export class RefreshControl extends RefreshControlBase { static SIZE: Object; // Undocumented } -export interface RecyclerViewBackedScrollViewProps extends ScrollViewProps { } +export interface RecyclerViewBackedScrollViewProps extends ScrollViewProps {} /** * Wrapper around android native recycler view. @@ -3220,7 +3260,7 @@ export interface RecyclerViewBackedScrollViewProps extends ScrollViewProps { } * use it pass this component as `renderScrollComponent` to the list view. For * now only horizontal scrolling is supported. */ -declare class RecyclerViewBackedScrollViewComponent extends React.Component { } +declare class RecyclerViewBackedScrollViewComponent extends React.Component {} declare const RecyclerViewBackedScrollViewBase: Constructor & typeof RecyclerViewBackedScrollViewComponent; export class RecyclerViewBackedScrollView extends RecyclerViewBackedScrollViewBase { @@ -3346,9 +3386,9 @@ export interface SliderProps extends SliderPropsIOS, SliderPropsAndroid { /** * A component used to select a single value from a range of values. */ -declare class SliderComponent extends React.Component { } -declare const SliderBase: Constructor & typeof SliderComponent; -export class Slider extends SliderBase { } +declare class SliderComponent extends React.Component {} +declare const SliderBase: Constructor & typeof SliderComponent; +export class Slider extends SliderBase {} export type SliderIOS = Slider; /** @@ -3395,7 +3435,7 @@ export interface SwitchIOSProps extends ViewProps { * * @see https://facebook.github.io/react-native/docs/switchios.html */ -export class SwitchIOS extends React.Component { } +export class SwitchIOS extends React.Component {} export type ImageResizeMode = 'cover' | 'contain' | 'stretch' | 'repeat' | 'center'; @@ -3765,8 +3805,8 @@ export interface ImageProps extends ImagePropsBase { style?: StyleProp; } -declare class ImageComponent extends React.Component { } -declare const ImageBase: Constructor & typeof ImageComponent; +declare class ImageComponent extends React.Component {} +declare const ImageBase: Constructor & typeof ImageComponent; export class Image extends ImageBase { static getSize(uri: string, success: (width: number, height: number) => void, failure: (error: any) => void): any; static prefetch(url: string): any; @@ -3785,8 +3825,8 @@ export interface ImageBackgroundProps extends ImagePropsBase { imageRef?(image: Image): void; } -declare class ImageBackgroundComponent extends React.Component { } -declare const ImageBackgroundBase: Constructor & typeof ImageBackgroundComponent; +declare class ImageBackgroundComponent extends React.Component {} +declare const ImageBackgroundBase: Constructor & typeof ImageBackgroundComponent; export class ImageBackground extends ImageBackgroundBase { resizeMode: ImageResizeMode; getSize(uri: string, success: (width: number, height: number) => void, failure: (error: any) => void): any; @@ -3928,7 +3968,10 @@ export interface FlatListProps extends VirtualizedListProps { * Remember to include separator length (height or width) in your offset calculation if you specify * `ItemSeparatorComponent`. */ - getItemLayout?: (data: Array | null | undefined, index: number) => { length: number; offset: number; index: number }; + getItemLayout?: ( + data: Array | null | undefined, + index: number, + ) => { length: number; offset: number; index: number }; /** * If true, renders items next to each other horizontally instead of stacked vertically. @@ -4018,6 +4061,18 @@ export interface FlatListProps extends VirtualizedListProps { * This may improve scroll performance for large lists. */ removeClippedSubviews?: boolean; + + /** + * Fades out the edges of the the scroll content. + * + * If the value is greater than 0, the fading edges will be set accordingly + * to the current scroll direction and position, + * indicating if there is more content to show. + * + * The default value is 0. + * @platform android + */ + fadingEdgeLength?: number; } export class FlatList extends React.Component> { @@ -4031,7 +4086,12 @@ export class FlatList extends React.Component> * such that viewPosition 0 places it at the top, 1 at the bottom, and 0.5 centered in the middle. * Cannot scroll to locations outside the render window without specifying the getItemLayout prop. */ - scrollToIndex: (params: { animated?: boolean | null; index: number; viewOffset?: number; viewPosition?: number }) => void; + scrollToIndex: (params: { + animated?: boolean | null; + index: number; + viewOffset?: number; + viewPosition?: number; + }) => void; /** * Requires linear scan through data - use `scrollToIndex` instead if possible. @@ -4069,7 +4129,7 @@ export class FlatList extends React.Component> getScrollableNode: () => any; // TODO: use `unknown` instead of `any` for Typescript >= 3.0 - setNativeProps: (props: {[key: string]: any}) => void; + setNativeProps: (props: { [key: string]: any }) => void; } /** @@ -4635,7 +4695,7 @@ interface TimerMixin { cancelAnimationFrame: typeof cancelAnimationFrame; } -declare class ListViewComponent extends React.Component { } +declare class ListViewComponent extends React.Component {} declare const ListViewBase: Constructor & Constructor & typeof ListViewComponent; export class ListView extends ListViewBase { static DataSource: ListViewDataSource; @@ -4670,9 +4730,9 @@ interface MaskedViewIOSProps extends ViewProps { /** * @see https://facebook.github.io/react-native/docs/maskedviewios.html */ -declare class MaskedViewComponent extends React.Component { } -declare const MaskedViewBase: Constructor & typeof MaskedViewComponent; -export class MaskedViewIOS extends MaskedViewBase { } +declare class MaskedViewComponent extends React.Component {} +declare const MaskedViewBase: Constructor & typeof MaskedViewComponent; +export class MaskedViewIOS extends MaskedViewBase {} export interface ModalBaseProps { /** @@ -4742,7 +4802,7 @@ export interface ModalPropsAndroid { export type ModalProps = ModalBaseProps & ModalPropsIOS & ModalPropsAndroid; -export class Modal extends React.Component { } +export class Modal extends React.Component {} /** * @see https://github.com/facebook/react-native/blob/0.34-stable\Libraries\Components\Touchable\Touchable.js @@ -4920,11 +4980,11 @@ export interface TouchableWithoutFeedbackProps extends TouchableWithoutFeedbackP * * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html */ -declare class TouchableWithoutFeedbackComponent extends React.Component { } +declare class TouchableWithoutFeedbackComponent extends React.Component {} declare const TouchableWithoutFeedbackBase: Constructor & Constructor & typeof TouchableWithoutFeedbackComponent; -export class TouchableWithoutFeedback extends TouchableWithoutFeedbackBase { } +export class TouchableWithoutFeedback extends TouchableWithoutFeedbackBase {} /** * @see https://facebook.github.io/react-native/docs/touchablehighlight.html#props @@ -4970,12 +5030,12 @@ export interface TouchableHighlightProps extends TouchableWithoutFeedbackProps { * * @see https://facebook.github.io/react-native/docs/touchablehighlight.html */ -declare class TouchableHighlightComponent extends React.Component { } -declare const TouchableHighlightBase: Constructor & +declare class TouchableHighlightComponent extends React.Component {} +declare const TouchableHighlightBase: Constructor & Constructor & Constructor & typeof TouchableHighlightComponent; -export class TouchableHighlight extends TouchableHighlightBase { } +export class TouchableHighlight extends TouchableHighlightBase {} /** * @see https://facebook.github.io/react-native/docs/touchableopacity.html#props @@ -4996,10 +5056,10 @@ export interface TouchableOpacityProps extends TouchableWithoutFeedbackProps { * * @see https://facebook.github.io/react-native/docs/touchableopacity.html */ -declare class TouchableOpacityComponent extends React.Component { } +declare class TouchableOpacityComponent extends React.Component {} declare const TouchableOpacityBase: Constructor & Constructor & - Constructor & + Constructor & typeof TouchableOpacityComponent; export class TouchableOpacity extends TouchableOpacityBase { /** @@ -5057,7 +5117,7 @@ export interface TouchableNativeFeedbackProps extends TouchableWithoutFeedbackPr * * @see https://facebook.github.io/react-native/docs/touchablenativefeedback.html#content */ -declare class TouchableNativeFeedbackComponent extends React.Component { } +declare class TouchableNativeFeedbackComponent extends React.Component {} declare const TouchableNativeFeedbackBase: Constructor & typeof TouchableNativeFeedbackComponent; export class TouchableNativeFeedback extends TouchableNativeFeedbackBase { /** @@ -5358,7 +5418,7 @@ export interface ListViewDataSource { * - rowHasChanged(prevRowData, nextRowData); * - sectionHeaderHasChanged(prevSectionData, nextSectionData); */ - new(onAsset: DataSourceAssetCallback): ListViewDataSource; + new (onAsset: DataSourceAssetCallback): ListViewDataSource; /** * Clones this `ListViewDataSource` with the specified `dataBlob` and @@ -5493,18 +5553,18 @@ export interface TabBarIOSItemProps extends ViewProps { * enum('bookmarks', 'contacts', 'downloads', 'favorites', 'featured', 'history', 'more', 'most-recent', 'most-viewed', 'recents', 'search', 'top-rated') */ systemIcon?: - | 'bookmarks' - | 'contacts' - | 'downloads' - | 'favorites' - | 'featured' - | 'history' - | 'more' - | 'most-recent' - | 'most-viewed' - | 'recents' - | 'search' - | 'top-rated'; + | 'bookmarks' + | 'contacts' + | 'downloads' + | 'favorites' + | 'featured' + | 'history' + | 'more' + | 'most-recent' + | 'most-viewed' + | 'recents' + | 'search' + | 'top-rated'; /** * Text that appears under the icon. It is ignored when a system icon is defined. @@ -5512,7 +5572,7 @@ export interface TabBarIOSItemProps extends ViewProps { title?: string; } -export class TabBarIOSItem extends React.Component { } +export class TabBarIOSItem extends React.Component {} /** * @see https://facebook.github.io/react-native/docs/tabbarios.html#props @@ -5659,7 +5719,7 @@ interface PlatformWebStatic extends PlatformStatic { */ interface DeviceEventEmitterStatic extends EventEmitter { sharedSubscriber: EventSubscriptionVendor; - new(): DeviceEventEmitterStatic; + new (): DeviceEventEmitterStatic; addListener(type: string, listener: (data: any) => void, context?: any): EmitterSubscription; } @@ -5795,7 +5855,7 @@ export interface InteractionManagerStatic { setDeadline(deadline: number): void; } -export interface ScrollResponderEvent extends NativeSyntheticEvent { } +export interface ScrollResponderEvent extends NativeSyntheticEvent {} interface ScrollResponderMixin extends SubscribableMixin { /** @@ -6189,7 +6249,7 @@ export interface ScrollViewPropsIOS { * content size. The default value is false. * @platform ios */ - scrollToOverflowEnabled?: boolean, + scrollToOverflowEnabled?: boolean; /** * When true the scroll view scrolls to top when the status bar is tapped. @@ -6201,7 +6261,7 @@ export interface ScrollViewPropsIOS { * Fires when the scroll view scrolls to top after the status bar has been tapped * @platform ios */ - onScrollToTop?: (event: NativeSyntheticEvent) => void, + onScrollToTop?: (event: NativeSyntheticEvent) => void; /** * An array of child indices determining which children get docked to the * top of the screen when scrolling. For example passing @@ -6250,6 +6310,18 @@ export interface ScrollViewPropsAndroid { * Enables nested scrolling for Android API level 21+. Nested scrolling is supported by default on iOS. */ nestedScrollEnabled?: boolean; + + /** + * Fades out the edges of the the scroll content. + * + * If the value is greater than 0, the fading edges will be set accordingly + * to the current scroll direction and position, + * indicating if there is more content to show. + * + * The default value is 0. + * @platform android + */ + fadingEdgeLength?: number; } export interface ScrollViewProps extends ViewProps, ScrollViewPropsIOS, ScrollViewPropsAndroid, Touchable { @@ -6432,7 +6504,7 @@ export interface ScrollViewProps extends ViewProps, ScrollViewPropsIOS, ScrollVi disableScrollViewPanResponder?: boolean; } -declare class ScrollViewComponent extends React.Component { } +declare class ScrollViewComponent extends React.Component {} declare const ScrollViewBase: Constructor & typeof ScrollViewComponent; export class ScrollView extends ScrollViewBase { /** @@ -6515,9 +6587,9 @@ export interface SnapshotViewIOSProps extends ViewProps { testIdentifier: string; } -declare class SnapshotViewIOSComponent extends React.Component { } -declare const SnapshotViewIOSBase: Constructor & typeof SnapshotViewIOSComponent; -export class SnapshotViewIOS extends SnapshotViewIOSBase { } +declare class SnapshotViewIOSComponent extends React.Component {} +declare const SnapshotViewIOSBase: Constructor & typeof SnapshotViewIOSComponent; +export class SnapshotViewIOS extends SnapshotViewIOSBase {} // Deduced from // https://github.com/facebook/react-native/commit/052cd7eb8afa7a805ef13e940251be080499919c @@ -6659,13 +6731,13 @@ export interface ActionSheetIOSStatic { export type ShareContent = | { - title?: string; - message: string; -} + title?: string; + message: string; + } | { - title?: string; - url: string; -}; + title?: string; + url: string; + }; export type ShareOptions = { dialogTitle?: string; @@ -7011,7 +7083,7 @@ export type BackPressEventName = 'hardwareBackPress'; * Detect hardware back button presses, and programmatically invoke the * default back button functionality to exit the app if there are no * listeners or if none of the listeners return true. -* The event subscriptions are called in reverse order + * The event subscriptions are called in reverse order * (i.e. last registered subscription first), and if one subscription * returns true then subscriptions registered earlier * will not be called. @@ -7037,7 +7109,7 @@ export interface ButtonProps { testID?: string; } -export class Button extends React.Component { } +export class Button extends React.Component {} export type CameraRollGroupType = 'Album' | 'All' | 'Event' | 'Faces' | 'Library' | 'PhotoStream' | 'SavedPhotos'; export type CameraRollAssetType = 'All' | 'Videos' | 'Photos'; @@ -7182,7 +7254,7 @@ export interface CheckBoxProps extends ViewProps { value?: boolean; } -export class CheckBox extends React.Component { } +export class CheckBox extends React.Component {} /** Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android */ export interface ClipboardStatic { @@ -7286,10 +7358,7 @@ export interface LinkingStatic extends NativeEventEmitter { * Sends an Android Intent - a broad surface to express Android functions. Useful for deep-linking to settings pages, * opening an SMS app with a message draft in place, and more. See https://developer.android.com/reference/kotlin/android/content/Intent?hl=en */ - sendIntent( - action: string, - extras?: Array<{key: string, value: string | number | boolean}>, - ): Promise; + sendIntent(action: string, extras?: Array<{ key: string; value: string | number | boolean }>): Promise; } export interface PanResponderGestureState { @@ -7460,7 +7529,7 @@ export interface PermissionsAndroidStatic { * A list of specified "dangerous" permissions that require prompting the user */ PERMISSIONS: { [key: string]: Permission }; - new(): PermissionsAndroidStatic; + new (): PermissionsAndroidStatic; /** * @deprecated Use check instead */ @@ -7828,7 +7897,7 @@ export class StatusBar extends React.Component { /** * @deprecated Use StatusBar instead */ -export interface StatusBarIOSStatic extends NativeEventEmitter { } +export interface StatusBarIOSStatic extends NativeEventEmitter {} export interface TimePickerAndroidOpenOptions { hour?: number; @@ -7974,6 +8043,8 @@ export interface UIManagerStatic { * has been completed in native. If you need the measurements as soon as * possible, consider using the [`onLayout` * prop](docs/view.html#onlayout) instead. + * + * @deprecated Use `ref.measure` instead. */ measure(node: number, callback: MeasureOnSuccessCallback): void; @@ -7991,6 +8062,8 @@ export interface UIManagerStatic { * * Note that these measurements are not available until after the rendering * has been completed in native. + * + * @deprecated Use `ref.measureInWindow` instead. */ measureInWindow(node: number, callback: MeasureInWindowOnSuccessCallback): void; @@ -8001,6 +8074,8 @@ export interface UIManagerStatic { * * As always, to obtain a native node handle for a component, you can use * `React.findNodeHandle(component)`. + * + * @deprecated Use `ref.measureLayout` instead. */ measureLayout( node: number, @@ -8131,9 +8206,9 @@ export interface SwitchProps extends SwitchPropsIOS { * If the `value` prop is not updated, the component will continue to render * the supplied `value` prop instead of the expected result of any user actions. */ -declare class SwitchComponent extends React.Component { } -declare const SwitchBase: Constructor & typeof SwitchComponent; -export class Switch extends SwitchBase { } +declare class SwitchComponent extends React.Component {} +declare const SwitchBase: Constructor & typeof SwitchComponent; +export class Switch extends SwitchBase {} /** * The Vibration API is exposed at `Vibration.vibrate()`. @@ -8167,6 +8242,42 @@ export interface VibrationStatic { cancel(): void; } +type ColorSchemeName = 'light' | 'dark' | null | undefined; + +export namespace Appearance { + type AppearancePreferences = { + colorScheme: ColorSchemeName; + }; + + type AppearanceListener = (preferences: AppearancePreferences) => void; + + /** + * Note: Although color scheme is available immediately, it may change at any + * time. Any rendering logic or styles that depend on this should try to call + * this function on every render, rather than caching the value (for example, + * using inline styles rather than setting a value in a `StyleSheet`). + * + * Example: `const colorScheme = Appearance.getColorScheme();` + */ + export function getColorScheme(): ColorSchemeName; + + /** + * Add an event handler that is fired when appearance preferences change. + */ + export function addChangeListener(listener: AppearanceListener): EventSubscription; + + /** + * Remove an event handler. + */ + export function removeChangeListener(listener: AppearanceListener): EventSubscription; +} + +/** + * A new useColorScheme hook is provided as the preferred way of accessing + * the user's preferred color scheme (aka Dark Mode). + */ +export function useColorScheme(): ColorSchemeName; + /** * This class implements common easing functions. The math is pretty obscure, * but this cool website has nice visual illustrations of what they represent: @@ -8341,7 +8452,7 @@ export namespace Animated { interface AnimationConfig { isInteraction?: boolean; - useNativeDriver?: boolean; + useNativeDriver: boolean; } /** @@ -8398,7 +8509,7 @@ export namespace Animated { */ export function add(a: Animated, b: Animated): AnimatedAddition; - class AnimatedAddition extends AnimatedInterpolation { } + class AnimatedAddition extends AnimatedInterpolation {} /** * Creates a new Animated value composed by subtracting the second Animated @@ -8406,7 +8517,7 @@ export namespace Animated { */ export function subtract(a: Animated, b: Animated): AnimatedSubtraction; - class AnimatedSubtraction extends AnimatedInterpolation { } + class AnimatedSubtraction extends AnimatedInterpolation {} /** * Creates a new Animated value composed by dividing the first Animated @@ -8414,7 +8525,7 @@ export namespace Animated { */ export function divide(a: Animated, b: Animated): AnimatedDivision; - class AnimatedDivision extends AnimatedInterpolation { } + class AnimatedDivision extends AnimatedInterpolation {} /** * Creates a new Animated value composed from two Animated values multiplied @@ -8422,7 +8533,7 @@ export namespace Animated { */ export function multiply(a: Animated, b: Animated): AnimatedMultiplication; - class AnimatedMultiplication extends AnimatedInterpolation { } + class AnimatedMultiplication extends AnimatedInterpolation {} /** * Creates a new Animated value that is the (non-negative) modulo of the @@ -8430,7 +8541,7 @@ export namespace Animated { */ export function modulo(a: Animated, modulus: number): AnimatedModulo; - class AnimatedModulo extends AnimatedInterpolation { } + class AnimatedModulo extends AnimatedInterpolation {} /** * Create a new Animated value that is limited between 2 values. It uses the @@ -8443,7 +8554,7 @@ export namespace Animated { */ export function diffClamp(a: Animated, min: number, max: number): AnimatedDiffClamp; - class AnimatedDiffClamp extends AnimatedInterpolation { } + class AnimatedDiffClamp extends AnimatedInterpolation {} /** * Starts an animation after the given delay. @@ -8493,7 +8604,7 @@ export namespace Animated { type Mapping = { [key: string]: Mapping } | AnimatedValue; interface EventConfig { listener?: (event: NativeSyntheticEvent) => void; - useNativeDriver?: boolean; + useNativeDriver: boolean; } /** @@ -8517,24 +8628,28 @@ export namespace Animated { export type ComponentProps = T extends React.ComponentType | React.Component ? P : never; export interface WithAnimatedValue - extends ThisType< - T extends object - ? { [K in keyof T]?: WithAnimatedValue } - : T extends (infer P)[] - ? WithAnimatedValue

[] - : T | Value | AnimatedInterpolation + extends ThisType< + T extends object + ? { [K in keyof T]?: WithAnimatedValue } + : T extends (infer P)[] + ? WithAnimatedValue

[] + : T | Value | AnimatedInterpolation > {} export type AnimatedProps = { [key in keyof T]: WithAnimatedValue }; - export interface AnimatedComponent> | React.Component>> extends React.FC>> { + export interface AnimatedComponent< + T extends React.ComponentType> | React.Component> + > extends React.FC>> { getNode: () => T; } /** * Make any React component Animatable. Used to create `Animated.View`, etc. */ - export function createAnimatedComponent> | React.Component>>(component: T): AnimatedComponent> ? InstanceType : T>; + export function createAnimatedComponent< + T extends React.ComponentType> | React.Component> + >(component: T): AnimatedComponent> ? InstanceType : T>; /** * Animated variants of the basic native views. Accepts Animated.Value for @@ -8749,15 +8864,15 @@ export interface ARTSurfaceProps { height: number; } -export class ClippingRectangle extends React.Component { } +export class ClippingRectangle extends React.Component {} -export class Group extends React.Component { } +export class Group extends React.Component {} -export class Shape extends React.Component { } +export class Shape extends React.Component {} -export class Surface extends React.Component { } +export class Surface extends React.Component {} -export class ARTText extends React.Component { } +export class ARTText extends React.Component {} export interface ARTStatic { ClippingRectangle: typeof ClippingRectangle; @@ -8873,12 +8988,6 @@ export type LayoutAnimation = LayoutAnimationStatic; export const Linking: LinkingStatic; export type Linking = LinkingStatic; -export const NativeMethodsMixin: NativeMethodsMixinStatic; -export type NativeMethodsMixin = NativeMethodsMixinStatic; - -export const NativeComponent: NativeMethodsMixinStatic; -export type NativeComponent = NativeMethodsMixinStatic; - export const PanResponder: PanResponderStatic; export type PanResponder = PanResponderStatic; @@ -8976,10 +9085,10 @@ export const PixelRatio: PixelRatioStatic; * const View = requireNativeComponent('RCTView'); * * The concrete return type of `requireNativeComponent` is a string, but the declared type is - * `any` because TypeScript assumes anonymous JSX intrinsics (`string` instead of `"div", for - * example) not to have any props. + * `HostComponent` because TypeScript assumes anonymous JSX intrinsics (e.g. a `string`) not + * to have any props. */ -export function requireNativeComponent(viewName: string): any; +export function requireNativeComponent(viewName: string): HostComponent; export function findNodeHandle( componentOrHandle: null | number | React.Component | React.ComponentClass, @@ -8989,6 +9098,8 @@ export function processColor(color: any): number; export const YellowBox: React.ComponentClass & { ignoreWarnings: (warnings: string[]) => void }; +export function unstable_enableLogBox(): void; + ////////////////////////////////////////////////////////////////////////// // // Additional ( and controversial) diff --git a/types/react-native/test/ART.tsx b/types/react-native/test/ART.tsx index a3d152d8dd..535cfc60d3 100644 --- a/types/react-native/test/ART.tsx +++ b/types/react-native/test/ART.tsx @@ -1,5 +1,5 @@ -import * as React from "react"; -import * as ReactNative from "react-native"; +import * as React from 'react'; +import * as ReactNative from 'react-native'; // See https://github.com/react-native-china/react-native-ART-doc/blob/6ba9c0f7c7e495a12045f3d7061834d2c74413c5/doc.md @@ -10,7 +10,7 @@ class Test extends React.Component { return ( - + ); diff --git a/types/react-native/test/animated.tsx b/types/react-native/test/animated.tsx index 2337dea81b..1f838e3487 100644 --- a/types/react-native/test/animated.tsx +++ b/types/react-native/test/animated.tsx @@ -1,6 +1,6 @@ -import * as React from "react"; +import * as React from 'react'; -import { Animated, View, NativeSyntheticEvent, NativeScrollEvent } from "react-native"; +import { Animated, View, NativeSyntheticEvent, NativeScrollEvent } from 'react-native'; function TestAnimatedAPI() { // Value @@ -20,6 +20,7 @@ function TestAnimatedAPI() { Animated.timing(v2, { toValue: v1.interpolate({ inputRange: [0, 1], outputRange: [0, 200] }), + useNativeDriver: false, }); // ValueXY @@ -30,6 +31,7 @@ function TestAnimatedAPI() { toValue: 0.5, tension: 10, delay: 100, + useNativeDriver: false, }); const springXY = Animated.spring(position, { @@ -37,17 +39,25 @@ function TestAnimatedAPI() { x: 1, y: 2, }, + useNativeDriver: false, }); spring1.start(); spring1.stop(); - Animated.parallel([Animated.spring(v1, { toValue: 1 }), Animated.spring(v2, { toValue: 1 })], { - stopTogether: true, - }); + Animated.parallel( + [ + Animated.spring(v1, { toValue: 1, useNativeDriver: false }), + Animated.spring(v2, { toValue: 1, useNativeDriver: false }), + ], + { + stopTogether: true, + }, + ); Animated.decay(v1, { velocity: 2, + useNativeDriver: false, }); Animated.timing(v1, { @@ -55,6 +65,7 @@ function TestAnimatedAPI() { duration: 100, delay: 100, easing: v => v, + useNativeDriver: false, }); Animated.add(v1, v2); @@ -88,7 +99,7 @@ function TestAnimatedAPI() { ]} /> - + ); } diff --git a/types/react-native/test/globals.tsx b/types/react-native/test/globals.tsx index 16dd3cf977..2bbc578769 100644 --- a/types/react-native/test/globals.tsx +++ b/types/react-native/test/globals.tsx @@ -1,15 +1,15 @@ -const fetchCopy: WindowOrWorkerGlobalScope["fetch"] = fetch; +const fetchCopy: WindowOrWorkerGlobalScope['fetch'] = fetch; const myHeaders = new Headers(); -myHeaders.append("Content-Type", "image/jpeg"); +myHeaders.append('Content-Type', 'image/jpeg'); const myInit: RequestInit = { - method: "GET", + method: 'GET', headers: myHeaders, - mode: "cors", + mode: 'cors', }; -const myRequest = new Request("flowers.jpg"); +const myRequest = new Request('flowers.jpg'); fetch(myRequest, myInit) .then(response => { @@ -23,16 +23,16 @@ fetch(myRequest, myInit) return response.blob(); }) .then(blob => { - const init = { status: 200, statusText: "SuperSmashingGreat!" }; + const init = { status: 200, statusText: 'SuperSmashingGreat!' }; const myResponse = new Response(blob, init); }); const xmlRequest = new XMLHttpRequest(); -xmlRequest.addEventListener("load", (ev) => { - console.log(ev.lengthComputable) - console.log(ev.loaded) - console.log(ev.total) +xmlRequest.addEventListener('load', ev => { + console.log(ev.lengthComputable); + console.log(ev.loaded); + console.log(ev.total); }); const test = new URLSearchParams(); diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index c870578b79..9cb631d71a 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -11,8 +11,8 @@ The content of index.io.js could be something like For a list of complete Typescript examples: check https://github.com/bgrieder/RNTSExplorer */ -import * as PropTypes from "prop-types"; -import * as React from "react"; +import * as PropTypes from 'prop-types'; +import * as React from 'react'; import { Alert, AppState, @@ -93,9 +93,12 @@ import { AccessibilityInfo, YellowBox, useWindowDimensions, -} from "react-native"; + HostComponent, + Appearance, + useColorScheme, +} from 'react-native'; -declare module "react-native" { +declare module 'react-native' { interface NativeTypedModule { someFunction(): void; someProperty: string; @@ -108,28 +111,28 @@ declare module "react-native" { NativeModules.NativeUntypedModule; NativeModules.NativeTypedModule.someFunction(); -NativeModules.NativeTypedModule.someProperty = ""; +NativeModules.NativeTypedModule.someProperty = ''; function dimensionsListener(dimensions: { window: ScaledSize; screen: ScaledSize }) { - console.log("window dimensions: ", dimensions.window); - console.log("screen dimensions: ", dimensions.screen); + console.log('window dimensions: ', dimensions.window); + console.log('screen dimensions: ', dimensions.screen); } function testDimensions() { - const { width, height, scale, fontScale } = Dimensions.get(1 === 1 ? "window" : "screen"); + const { width, height, scale, fontScale } = Dimensions.get(1 === 1 ? 'window' : 'screen'); - Dimensions.addEventListener("change", dimensionsListener); - Dimensions.removeEventListener("change", dimensionsListener); + Dimensions.addEventListener('change', dimensionsListener); + Dimensions.removeEventListener('change', dimensionsListener); } function TextUseWindowDimensions() { - const {width, height, scale, fontScale} = useWindowDimensions() + const { width, height, scale, fontScale } = useWindowDimensions(); } -BackHandler.addEventListener("hardwareBackPress", () => true).remove(); -BackHandler.addEventListener("hardwareBackPress", () => false).remove(); -BackHandler.addEventListener("hardwareBackPress", () => undefined).remove(); -BackHandler.addEventListener("hardwareBackPress", () => null).remove(); +BackHandler.addEventListener('hardwareBackPress', () => true).remove(); +BackHandler.addEventListener('hardwareBackPress', () => false).remove(); +BackHandler.addEventListener('hardwareBackPress', () => undefined).remove(); +BackHandler.addEventListener('hardwareBackPress', () => null).remove(); interface LocalStyles { container: ViewStyle; @@ -140,18 +143,18 @@ interface LocalStyles { const styles = StyleSheet.create({ container: { flex: 1, - justifyContent: "center", - alignItems: "center", - backgroundColor: "#F5FCFF", + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, - textAlign: "center", + textAlign: 'center', margin: 10, }, instructions: { - textAlign: "center", - color: "#333333", + textAlign: 'center', + color: '#333333', marginBottom: 5, }, }); @@ -160,38 +163,38 @@ const styles = StyleSheet.create({ const stylesAlt = StyleSheet.create({ container: { flex: 1, - justifyContent: "center", - alignItems: "center", - backgroundColor: "#F5FCFF", + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, - textAlign: "center", + textAlign: 'center', margin: 10, }, instructions: { - textAlign: "center", - color: "#333333", + textAlign: 'center', + color: '#333333', marginBottom: 5, }, }); -StyleSheet.setStyleAttributePreprocessor("fontFamily", (family: string) => family); +StyleSheet.setStyleAttributePreprocessor('fontFamily', (family: string) => family); const welcomeFontSize = StyleSheet.flatten(styles.welcome).fontSize; const viewStyle: StyleProp = { - backgroundColor: "#F5FCFF", + backgroundColor: '#F5FCFF', }; const textStyle: StyleProp = { fontSize: 20, }; const imageStyle: StyleProp = { - resizeMode: "contain", + resizeMode: 'contain', }; const fontVariantStyle: StyleProp = { - fontVariant: ['tabular-nums'] -} + fontVariant: ['tabular-nums'], +}; const viewProperty = StyleSheet.flatten(viewStyle).backgroundColor; const textProperty = StyleSheet.flatten(textStyle).fontSize; @@ -205,7 +208,7 @@ const { top } = flattenStyle; const s = StyleSheet.create({ shouldWork: { - fontWeight: "900", // if we comment this line, errors gone + fontWeight: '900', // if we comment this line, errors gone marginTop: 5, // if this line commented, errors also gone }, }); @@ -223,40 +226,22 @@ const composeImageStyle: StyleProp = { }; // The following use of the compose method is valid -const combinedStyle: StyleProp = StyleSheet.compose( - composeTextStyle, - composeTextStyle, -); +const combinedStyle: StyleProp = StyleSheet.compose(composeTextStyle, composeTextStyle); -const combinedStyle1: StyleProp = StyleSheet.compose( - composeImageStyle, - composeImageStyle, -); +const combinedStyle1: StyleProp = StyleSheet.compose(composeImageStyle, composeImageStyle); -const combinedStyle2: StyleProp = StyleSheet.compose( - [composeTextStyle], - [composeTextStyle], -); +const combinedStyle2: StyleProp = StyleSheet.compose([composeTextStyle], [composeTextStyle]); -const combinedStyle3: StyleProp = StyleSheet.compose( - composeTextStyle, - null, -); +const combinedStyle3: StyleProp = StyleSheet.compose(composeTextStyle, null); -const combinedStyle4: StyleProp = StyleSheet.compose( - [composeTextStyle], - null, -); +const combinedStyle4: StyleProp = StyleSheet.compose([composeTextStyle], null); const combinedStyle5: StyleProp = StyleSheet.compose( composeTextStyle, Math.random() < 0.5 ? composeTextStyle : null, ); -const combinedStyle6: StyleProp = StyleSheet.compose( - null, - null, -); +const combinedStyle6: StyleProp = StyleSheet.compose(null, null); // The following use of the compose method is invalid: const combinedStyle7 = StyleSheet.compose(composeImageStyle, composeTextStyle); // $ExpectError @@ -338,7 +323,7 @@ class Welcome extends React.Component & { color: string }> { Welcome to React Native To get started, edit index.ios.js - Press Cmd+R to reload,{"\n"} + Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu @@ -360,7 +345,7 @@ export class TouchableNativeFeedbackTest extends React.Component { render() { return ( - + Button @@ -370,14 +355,14 @@ export class TouchableNativeFeedbackTest extends React.Component { // App State function appStateListener(state: string) { - console.log("New state: " + state); + console.log('New state: ' + state); } function appStateTest() { - console.log("Current state: " + AppState.currentState); - AppState.addEventListener("change", appStateListener); - AppState.addEventListener("blur", appStateListener); - AppState.addEventListener("focus", appStateListener); + console.log('Current state: ' + AppState.currentState); + AppState.addEventListener('change', appStateListener); + AppState.addEventListener('blur', appStateListener); + AppState.addEventListener('focus', appStateListener); } // ViewPagerAndroid @@ -387,7 +372,7 @@ export class ViewPagerAndroidTest { { console.log(`position: ${e.nativeEvent.position}`); console.log(`offset: ${e.nativeEvent.offset}`); @@ -400,12 +385,12 @@ export class ViewPagerAndroidTest { } } -const profiledJSONParse = Systrace.measure("JSON", "parse", JSON.parse); -profiledJSONParse("[]"); +const profiledJSONParse = Systrace.measure('JSON', 'parse', JSON.parse); +profiledJSONParse('[]'); InteractionManager.runAfterInteractions(() => { // ... -}).then(() => "done"); +}).then(() => 'done'); export class FlatListTest extends React.Component, {}> { list: FlatList | null = null; @@ -424,7 +409,7 @@ export class FlatListTest extends React.Component, {}> { ); }; - _renderSeparator = () => ; + _renderSeparator = () => ; render() { return ( @@ -437,6 +422,7 @@ export class FlatListTest extends React.Component, {}> { ListFooterComponentStyle={{ padding: 8 }} ListHeaderComponent={null} ListHeaderComponentStyle={{ padding: 8 }} + fadingEdgeLength={200} /> ); } @@ -457,12 +443,12 @@ export class SectionListTest extends React.Component, { render() { const sections = [ { - title: "Section 1", - data: ["A", "B", "C", "D", "E"], + title: 'Section 1', + data: ['A', 'B', 'C', 'D', 'E'], }, { - title: "Section 2", - data: ["A2", "B2", "C2", "D2", "E2"], + title: 'Section 2', + data: ['A2', 'B2', 'C2', 'D2', 'E2'], renderItem: (info: { item: string }) => ( {info.item} @@ -497,16 +483,17 @@ export class SectionListTest extends React.Component, { export class CapsLockComponent extends React.Component { render() { - const content = (this.props.children || "") as string; + const content = (this.props.children || '') as string; return {content.toUpperCase()}; } } -const getInitialUrlTest = () => Linking.getInitialURL().then(val => { - if (val !== null) { - val.indexOf('val is now a string'); - } -}) +const getInitialUrlTest = () => + Linking.getInitialURL().then(val => { + if (val !== null) { + val.indexOf('val is now a string'); + } + }); class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListViewDataSource }> { eventHandler = (event: NativeSyntheticEvent) => { @@ -516,7 +503,7 @@ class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListVi render() { const scrollViewStyle1 = StyleSheet.create({ scrollView: { - backgroundColor: "red", + backgroundColor: 'red', }, }); const scrollViewStyle2 = { @@ -527,7 +514,7 @@ class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListVi dataSource={this.state.dataSource} renderScrollComponent={props => { if (props.scrollEnabled) { - throw new Error("Expected scroll to be enabled."); + throw new Error('Expected scroll to be enabled.'); } return ( @@ -543,6 +530,7 @@ class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListVi style={[scrollViewStyle1.scrollView, scrollViewStyle2]} onScrollToTop={() => {}} scrollToOverflowEnabled={true} + fadingEdgeLength={200} /> ); }} @@ -589,17 +577,17 @@ class TabBarTest extends React.Component { class AlertTest extends React.Component { showAlert() { Alert.alert( - "Title", - "Message", + 'Title', + 'Message', [ - { text: "First button", onPress: () => {} }, - { text: "Second button", onPress: () => {} }, - { text: "Third button", onPress: () => {} }, + { text: 'First button', onPress: () => {} }, + { text: 'Second button', onPress: () => {} }, + { text: 'Third button', onPress: () => {} }, ], { cancelable: false, onDismiss: () => {}, - } + }, ); } @@ -648,15 +636,19 @@ const CheckboxTest = () => ( { console.log(value); }} - onValueChange={value => { console.log(value); }} + onChange={value => { + console.log(value); + }} + onValueChange={value => { + console.log(value); + }} value={true} /> ); class InputAccessoryViewTest extends React.Component { render() { - const uniqueID = "foobar"; + const uniqueID = 'foobar'; return ( @@ -677,16 +669,16 @@ const dataSourceAssetCallback2: DataSourceAssetCallback = {}; // DeviceEventEmitterStatic const deviceEventEmitterStatic: DeviceEventEmitterStatic = DeviceEventEmitter; -deviceEventEmitterStatic.addListener("keyboardWillShow", data => true); -deviceEventEmitterStatic.addListener("keyboardWillShow", data => true, {}); +deviceEventEmitterStatic.addListener('keyboardWillShow', data => true); +deviceEventEmitterStatic.addListener('keyboardWillShow', data => true, {}); const nativeEventEmitter = new NativeEventEmitter(); -nativeEventEmitter.removeAllListeners("event"); +nativeEventEmitter.removeAllListeners('event'); class CustomEventEmitter extends NativeEventEmitter {} const customEventEmitter = new CustomEventEmitter(); -customEventEmitter.addListener("event", () => {}); +customEventEmitter.addListener('event', () => {}); class TextInputTest extends React.Component<{}, { username: string }> { username: TextInput | null = null; @@ -777,7 +769,7 @@ class TextInputTest extends React.Component<{}, { username: string }> { - + ); } @@ -785,9 +777,9 @@ class TextInputTest extends React.Component<{}, { username: string }> { class StatusBarTest extends React.Component { render() { - StatusBar.setBarStyle("dark-content", true); + StatusBar.setBarStyle('dark-content', true); - console.log("height:", StatusBar.currentHeight); + console.log('height:', StatusBar.currentHeight); return ; } @@ -795,44 +787,45 @@ class StatusBarTest extends React.Component { export class ImageTest extends React.Component { componentDidMount(): void { - const uri = "https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png"; + const uri = 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png'; const image: ImageResolvedAssetSource = Image.resolveAssetSource({ uri }); console.log(image.width, image.height, image.scale, image.uri); - Image.queryCache && Image.queryCache([uri]).then(({ [uri]: status }) => { - if (status === undefined) { - console.log("Image is not in cache"); - } else { - console.log(`Image is in ${status} cache`); - } - }) + Image.queryCache && + Image.queryCache([uri]).then(({ [uri]: status }) => { + if (status === undefined) { + console.log('Image is not in cache'); + } else { + console.log(`Image is in ${status} cache`); + } + }); } handleOnLoad = (e: NativeSyntheticEvent) => { testNativeSyntheticEvent(e); - console.log("height:", e.nativeEvent.source.height); - console.log("width:", e.nativeEvent.source.width); - console.log("url:", e.nativeEvent.source.url); + console.log('height:', e.nativeEvent.source.height); + console.log('width:', e.nativeEvent.source.width); + console.log('url:', e.nativeEvent.source.url); }; handleOnError = (e: NativeSyntheticEvent) => { testNativeSyntheticEvent(e); - console.log("error:", e.nativeEvent.error); + console.log('error:', e.nativeEvent.error); }; render() { - const resizeMode: ImageResizeMode = "contain"; + const resizeMode: ImageResizeMode = 'contain'; return ( @@ -851,7 +844,7 @@ export class ImageBackgroundProps extends React.Component { return ( @@ -866,17 +859,18 @@ class AccessibilityTest extends React.Component { return ( {}} accessibilityRole="header" - accessibilityStates={["selected"]} - accessibilityState={{checked: true}} + accessibilityStates={['selected']} + accessibilityState={{ checked: true }} accessibilityHint="Very importent header" + accessibilityValue={{ min: 60, max: 120, now: 80 }} onMagicTap={() => {}} onAccessibilityEscape={() => {}} > - + Text @@ -885,7 +879,9 @@ class AccessibilityTest extends React.Component { } } -const AccessibilityInfoFetchTest = AccessibilityInfo.fetch().then((isEnabled) => {console.log(isEnabled)}); +const AccessibilityInfoFetchTest = AccessibilityInfo.fetch().then(isEnabled => { + console.log(isEnabled); +}); const KeyboardAvoidingViewTest = () => ; @@ -896,24 +892,24 @@ const TimePickerAndroidTest = () => { hour: 8, minute: 15, is24Hour: true, - mode: "spinner", + mode: 'spinner', }).then(result => { if (result.action === TimePickerAndroid.timeSetAction) { - console.log('Time', result.hour, result.minute) + console.log('Time', result.hour, result.minute); } }); -} +}; const DatePickerAndroidTest = () => { DatePickerAndroid.open({ date: new Date(), - mode: 'calendar' + mode: 'calendar', }).then(result => { if (result.action === DatePickerAndroid.dateSetAction) { - console.log('Date', result.year, result.month, result.day) + console.log('Date', result.year, result.month, result.day); } }); -} +}; const PickerTest = () => ( {}}> @@ -922,27 +918,39 @@ const PickerTest = () => ( ); +const NativeBridgedComponent = requireNativeComponent<{ nativeProp: string }>('NativeBridgedComponent'); // $ExpectType HostComponent<{ nativeProp: string; }> + class BridgedComponentTest extends React.Component { static propTypes = { jsProp: PropTypes.string.isRequired, ...ViewPropTypes, }; + nativeComponentRef: React.ElementRef | null; + + measureNativeComponent() { + if (this.nativeComponentRef) { + this.nativeComponentRef.measure( + (x, y, width, height, pageX, pageY) => x + y + width + height + pageX + pageY, + ); + } + } + render() { - return ; + return ( + (this.nativeComponentRef = ref)} /> + ); } } -const NativeBridgedComponent = requireNativeComponent("NativeBridgedComponent"); +const SwitchColorTest = () => ; -const SwitchColorTest = () => ; - -const SwitchThumbColorTest = () => ; +const SwitchThumbColorTest = () => ; const NativeIDTest = () => ( - - - Text + + + Text ); @@ -950,11 +958,11 @@ const MaxFontSizeMultiplierTest = () => Text { Share.share( - { title: "title", message: "message" }, - { dialogTitle: "dialogTitle", excludedActivityTypes: ["activity"], tintColor: "red", subject: "Email subject" } + { title: 'title', message: 'message' }, + { dialogTitle: 'dialogTitle', excludedActivityTypes: ['activity'], tintColor: 'red', subject: 'Email subject' }, ); - Share.share({ title: "title", url: "url" }); - Share.share({ message: "message" }).then(result => { + Share.share({ title: 'title', url: 'url' }); + Share.share({ message: 'message' }).then(result => { if (result.action === Share.sharedAction) { const activity = result.activityType; } else if (result.action === Share.dismissedAction) { @@ -963,9 +971,11 @@ const ShareTest = () => { }; const KeyboardTest = () => { - const subscriber = Keyboard.addListener("keyboardDidHide", (event) => {event}); + const subscriber = Keyboard.addListener('keyboardDidHide', event => { + event; + }); subscriber.remove(); -} +}; const PermissionsAndroidTest = () => { PermissionsAndroid.request('android.permission.CAMERA').then(result => { @@ -977,27 +987,29 @@ const PermissionsAndroidTest = () => { case 'never_ask_again': break; } - }) + }); - PermissionsAndroid.requestMultiple(['android.permission.CAMERA', 'android.permission.ACCESS_FINE_LOCATION']).then(results => { - switch (results['android.permission.CAMERA']) { - case 'granted': - break; - case 'denied': - break; - case 'never_ask_again': - break; - } - switch (results['android.permission.ACCESS_FINE_LOCATION']) { - case 'granted': - break; - case 'denied': - break; - case 'never_ask_again': - break; - } - }) -} + PermissionsAndroid.requestMultiple(['android.permission.CAMERA', 'android.permission.ACCESS_FINE_LOCATION']).then( + results => { + switch (results['android.permission.CAMERA']) { + case 'granted': + break; + case 'denied': + break; + case 'never_ask_again': + break; + } + switch (results['android.permission.ACCESS_FINE_LOCATION']) { + case 'granted': + break; + case 'denied': + break; + case 'never_ask_again': + break; + } + }, + ); +}; // Platform const PlatformTest = () => { @@ -1024,21 +1036,16 @@ Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5, default: 0 } // ProgressBarAndroid const ProgressBarAndroidTest = () => { - + ; }; // Push notification const PushNotificationTest = () => { PushNotificationIOS.presentLocalNotification({ - alertBody: "notificatus", - userInfo: "informius", - alertTitle: "Titulus", - alertAction: "view", + alertBody: 'notificatus', + userInfo: 'informius', + alertTitle: 'Titulus', + alertAction: 'view', }); PushNotificationIOS.scheduleLocalNotification({ @@ -1047,14 +1054,34 @@ const PushNotificationTest = () => { alertTitle: 'Hello!', applicationIconBadgeNumber: 999, category: 'engagement', - fireDate: (new Date()).toISOString(), + fireDate: new Date().toISOString(), isSilent: false, repeatInterval: 'minute', userInfo: { abc: 123, }, }); -} +}; // YellowBox const YellowBoxTest = () => ; + +// Appearance +const DarkMode = () => { + const color = useColorScheme(); + const isDarkMode = Appearance.getColorScheme() === 'dark'; + + Appearance.addChangeListener(({ colorScheme }) => { + console.log(colorScheme); + }); + + Appearance.removeChangeListener(({ colorScheme }) => { + console.log(colorScheme); + }); + + React.useEffect(() => { + console.log('-color', color); + }, [color]); + + return Is dark mode enabled? {isDarkMode}; +}; diff --git a/types/react-native/test/legacy-properties.tsx b/types/react-native/test/legacy-properties.tsx index 1c4068a78b..8be6515ba4 100644 --- a/types/react-native/test/legacy-properties.tsx +++ b/types/react-native/test/legacy-properties.tsx @@ -1,4 +1,4 @@ -import * as React from "react"; -import { TextInputProperties } from "react-native"; +import * as React from 'react'; +import { TextInputProperties } from 'react-native'; class Test extends React.Component {} diff --git a/types/react-primitives/react-primitives-tests.tsx b/types/react-primitives/react-primitives-tests.tsx index 7fd45e132e..f9d0fe307a 100644 --- a/types/react-primitives/react-primitives-tests.tsx +++ b/types/react-primitives/react-primitives-tests.tsx @@ -47,7 +47,8 @@ export default class Component extends React.Component<{}, State> { Animated.timing(this.state.opacity, { toValue: 1, duration: 10000, - easing: Easing.cubic + easing: Easing.cubic, + useNativeDriver: false, }).start(); if (Platform.OS === 'sketch') { console.log('The Platform is sketch');