From 774cb78bf01a232d6ba6696e3b4f29cc25b2e340 Mon Sep 17 00:00:00 2001 From: KonstantinKai Date: Mon, 20 Nov 2017 18:53:31 +0200 Subject: [PATCH 1/4] [expo] add typings --- types/expo/expo-tests.ts | 86 +++ types/expo/index.d.ts | 1487 ++++++++++++++++++++++++++++++++++++++ types/expo/tsconfig.json | 23 + types/expo/tslint.json | 1 + 4 files changed, 1597 insertions(+) create mode 100644 types/expo/expo-tests.ts create mode 100644 types/expo/index.d.ts create mode 100644 types/expo/tsconfig.json create mode 100644 types/expo/tslint.json diff --git a/types/expo/expo-tests.ts b/types/expo/expo-tests.ts new file mode 100644 index 0000000000..c8b7d5dc64 --- /dev/null +++ b/types/expo/expo-tests.ts @@ -0,0 +1,86 @@ +import { + Accelerometer, + Amplitude, + Asset, + AuthSession, + Audio +} from 'expo'; + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', {key: 'value'}); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true +}); +Audio.setIsEnabledAsync(true); +Audio.Sound.create('uri', { + volume: 0.5, + rate: 0.6 +}, null, true).then(result => { + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + sound.getStatusAsync().then(_status => { + _status.isLoaded; + }); +}); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts new file mode 100644 index 0000000000..5dfff55946 --- /dev/null +++ b/types/expo/index.d.ts @@ -0,0 +1,1487 @@ +// Type definitions for expo 23.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { EventSubscription } from 'fbemitter'; +import { Component, Ref } from 'react'; +import { + ViewStyle, + ViewProperties, + ColorPropType, + ImageURISource, + NativeEventEmitter, + ImageRequireSource +} from 'react-native'; + +export type URISource = ImageURISource; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type Orientation = 'portrait' | 'landscape'; +export type Axis = number; +export interface HashMap { [key: string]: any; } +export type FloatFromZeroToOne = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; +export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; + +/** + * Accelerometer + */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Amplitude + */ +export namespace Amplitude { + function initialize(apiKey: string): void; + function setUserId(userId: string): void; + function setUserProperties(userProperties: HashMap): void; + function clearUserProperties(): void; + function logEvent(eventName: string): void; + function logEventWithProperties(eventName: string, properties: HashMap): void; + function setGroup(groupType: string, groupNames: HashMap): void; +} + +/** + * Asset + */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + name: string; + type: string; + hash: string; + uri: string; + localUri: string; + width?: number; + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + downloadAsync(): Promise; + + static fromModule(module: RequireSource): Asset; + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * AuthSession + */ +export namespace AuthSession { + function startAsync(options: { authUrl: string; returnUrl: string; }): Promise<{ + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }>; + function dismiss(): void; + function getRedirectUrl(): string; +} + +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: FloatFromZeroToOne; + shouldCorrectPitch?: boolean; + volume?: FloatFromZeroToOne; + isMuted?: boolean; + isLooping?: boolean; +} + +export type Source = string | RequireSource | Asset; + +export class PlaybackObject { + loadAsync(source: Source, initialStatus: PlaybackStatusToSet, downloadFirst: boolean): Promise; + unloadAsync(): Promise; + getStatusAsync(): Promise; + setOnPlaybackStatusUpdate(onPlaybackStatusUpdate: (status: PlaybackStatus) => void): void; + setStatusAsync(status: PlaybackStatusToSet): Promise; + playAsync(): Promise; + playFromPositionAsync(positionMillis: number): Promise; + pauseAsync(): Promise; + stopAsync(): Promise; + setPositionAsync(positionMillis: number): Promise; + setRateAsync(rate: number, shouldCorrectPitch: boolean): Promise; + setVolumeAsync(volume: number): Promise; + setIsMutedAsync(isMuted: boolean): Promise; + setIsLoopingAsync(isLooping: boolean): Promise; + setProgressUpdateIntervalAsync(progressUpdateIntervalMillis: number): Promise; +} + +export namespace Audio { + enum InterruptionModeIOS { + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + enum InterruptionModeAndroid { + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + interface AudioMode { + playsInSilentModeIOS: boolean; + allowsRecordingIOS: boolean; + interruptionModeIOS: InterruptionModeIOS; + shouldDuckAndroid: boolean; + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + class Sound extends PlaybackObject { + constructor(); + + static create( + source: Source, + initialStatus?: PlaybackStatusToSet, + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + class Recording { + constructor(); + + getStatusAsync(): Promise; + setOnRecordingStatusUpdate(onRecordingStatusUpdate: (status: RecordingStatus) => void): void; + setProgressUpdateInterval(miliss: number): void; + prepareToRecordAsync(options: Recording): Promise; + isPreparedToRecord(): boolean; + startAsync(): Promise; + pauseAsync(): Promise; + stopAndUnloadAsync(): Promise; + getURI(): string | undefined; + createNewLoadedSound(initialStatus: PlaybackStatusToSet, onPlaybackStatusUpdate: (status: PlaybackStatus) => void): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: Source | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} + +/** + * AppLoading + */ +export type AppLoadingProperties = { + startAsync: () => Promise; + onFinish: () => void; + onError?: (error: Error) => void; +} | { + startAsync: null; + onFinish: null; + onError: null; +}; +export class AppLoading extends Component { } + +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProperties { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeRead?: BarCodeReadCallback; +} + +export class BarCodeScanner extends Component { } + +/** + * BlurView + */ +export interface BlurViewProps extends ViewProperties { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } + +/** + * Brightness + */ +export namespace Brightness { + function setBrightnessAsync(brightnessValue: number): Promise; + function getBrightnessAsync(): Promise; + function getSystemBrightnessAsync(): Promise; + function setSystemBrightnessAsync(brightnessValue: number): Promise; +} + +/** + * Camera + */ +export interface TakePictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; +} +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} +export interface RecordOptions { + quality?: string; + maxDuration?: number; + maxFileSize?: number; + mute?: boolean; +} +export class CameraObject { + takePictureAsync(options: TakePictureOptions): Promise; + recordAsync(options: RecordOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} +export interface CameraProperties extends ViewProperties { + onCameraReady: () => void; + onMountError: () => void; + flashMode: string | number; + type: string | number; + ratio: string; + autoFocus: string | number | boolean; + focusDepth: FloatFromZeroToOne; + zoom: FloatFromZeroToOne; + whiteBalance: string | number; + barCodeTypes: string[]; + onBarCodeRead: BarCodeReadCallback; + ref?: CameraObject; +} +export interface CameraConstants { + Type: string; + FlashMode: string; + AutoFocus: string; + WhiteBalance: string; + VideoQuality: string; + BarCodeType: string; +} +export class Camera extends Component { + static Constants: CameraConstants; +} + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios: { + platform: string; + model: string; + userInterfaceIdiom: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + icon?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBarColor?: string; + androidStatusBar?: { + barStyle?: 'lignt-content' | 'dark-content', + backgroundColor?: string + }; + androidHideExponentNotificationInShellApp?: boolean; + scheme?: string; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme: any; + xde: boolean; + developper?: { + tool?: string, + [propName: string]: any + }; + bundleUrl?: string; + debuggerHost?: string; + mainModuleName?: string; + logUrl?: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; +} + +/** + * Contacts + */ +export namespace Contacts { + type PhoneNumbers = 'phoneNumbers'; + type Emails = 'emails'; + type Addresses = 'addresses'; + type Image = 'image'; + type Thumbnail = 'thumbnail'; + type Note = 'note'; + type Birthday = 'birthday'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type SocialProfiles = 'socialProfiles'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Dates = 'dates'; + type Relationships = 'relationships'; + + const PHONE_NUMBERS: PhoneNumbers; + const EMAILS: Emails; + const ADDRESSES: Addresses; + const IMAGE: Image; + const THUMBNAIL: Thumbnail; + const NOTE: Note; + const BIRTHDAY: Birthday; + const NON_GREGORIAN_BIRTHDAY: NonGregorianBirthday; + const NAME_PREFIX: NamePrefix; + const NAME_SUFFIX: NameSuffix; + const PHONETIC_FIRST_NAME: PhoneticFirstName; + const PHONETIC_MIDDLE_NAME: PhoneticMiddleName; + const PHONETIC_LAST_NAME: PhoneticLastName; + const SOCIAL_PROFILES: SocialProfiles; + const IM_ADDRESSES: InstantMessageAddresses; + const URLS: UrlAddresses; + const DATES: Dates; + const RELATIONSHIPS: Relationships; + + type FieldType = PhoneNumbers | Emails | Addresses | Image | Thumbnail | + Note | Birthday | NonGregorianBirthday | NamePrefix | NameSuffix | + PhoneticFirstName | PhoneticMiddleName | PhoneticLastName | SocialProfiles | + InstantMessageAddresses | UrlAddresses | Dates | Relationships; + + interface Options { + pageSize?: number; + pageOffset?: number; + fields?: FieldType[]; + } + + interface Contact { + id: string; + contactType: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + previousLastName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + emails?: Array<{ + email?: string; + primary?: boolean; + label: string; + id: string; + }>; + phoneNumbers?: Array<{ + number?: string; + primary?: boolean; + digits?: string; + countryCode?: string; + label: string; + id: string; + }>; + addresses?: Array<{ + street?: string; + city?: string; + country?: string; + region?: string; + neighborhood?: string; + postalCode?: string; + poBox?: string; + isoCountryCode?: string; + label: string; + id: string; + }>; + socialProfiles?: Array<{ + service?: string; + localizedProfile?: string; + url?: string; + username?: string; + userId?: string; + label: string; + id: string; + }>; + instantMessageAddresses?: Array<{ + service?: string; + username?: string; + localizedService?: string; + label: string; + id: string; + }>; + urls?: { + label: string; + url?: string; + id: string; + }; + company?: string; + jobTitle?: string; + department?: string; + imageAvailable?: boolean; + image?: { + uri?: string; + }; + thumbnail?: { + uri?: string; + }; + note?: string; + dates?: Array<{ + day?: number; + month?: number; + year?: number; + id: string; + label: string; + }>; + relationships?: Array<{ + label: string; + name?: string; + id: string; + }>; + } + + interface Response { + data: Contact[]; + total: number; + hasNextPage: boolean; + hasPreviousPage: boolean; + } + + function getContactsAsync(options: Options): Promise; + function getContactByIdAsync(options: { id?: string; fields?: FieldType[] }): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type: string; + } + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options: Options): Response; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + type Response = { + type: 'success'; + token: string; + expires: number; + } | { + type: 'cancel'; + }; + function logInWithReadPermissionsAsync(appId: string, options: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + function withNativeAd(component: Component<{ + icon?: string; + coverImage?: string; + title?: string; + subtitle?: string; + description?: string; + callToActionText?: string; + socialContext?: string; + }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FileSystem + */ +export namespace FileSystem { + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: string; + } | { + exists: false; + isDirectory: false; + }; + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: string; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string): Promise; + function writeAsStringAsync(fileUri: string, contents: string): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(fireUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(fileUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + private _uuid: string; + private _url: string; + private _fileUri: string; + private _options: DownloadOptions; + private _emitter: NativeEventEmitter; + private _resumeData?: string; + private _callback?: DownloadProgressCallback; + private _subscription?: () => void; + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** + * Fingerprint + */ +export namespace Fingerprint { + type FingerprintAuthenticationResult = { success: true } | { success: false, error: string }; + + function hasHardwareAsync(): Promise; + function isEnrolledAsync(): Promise; + function authenticateAsync(promptMessageIOS?: string): Promise; + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +/** + * GLView + */ +export interface GLViewProps extends ViewProperties { + onContextCreate(): void; + msaaSamples: number; +} +export class GLView extends Component { } + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** + * Gyroscope + */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: string; + const ACTION_APP_NOTIFICATION_REDACTION: string; + const ACTION_CONDITION_PROVIDER_SETTINGS: string; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: string; + const ACTION_PRINT_SETTINGS: string; + const ACTION_ADD_ACCOUNT_SETTINGS: string; + const ACTION_AIRPLANE_MODE_SETTINGS: string; + const ACTION_APN_SETTINGS: string; + const ACTION_APPLICATION_DETAILS_SETTINGS: string; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: string; + const ACTION_APPLICATION_SETTINGS: string; + const ACTION_APP_NOTIFICATION_SETTINGS: string; + const ACTION_APP_OPS_SETTINGS: string; + const ACTION_BATTERY_SAVER_SETTINGS: string; + const ACTION_BLUETOOTH_SETTINGS: string; + const ACTION_CAPTIONING_SETTINGS: string; + const ACTION_CAST_SETTINGS: string; + const ACTION_DATA_ROAMING_SETTINGS: string; + const ACTION_DATE_SETTINGS: string; + const ACTION_DEVICE_INFO_SETTINGS: string; + const ACTION_DEVICE_NAME: string; + const ACTION_DISPLAY_SETTINGS: string; + const ACTION_DREAM_SETTINGS: string; + const ACTION_HARD_KEYBOARD_SETTINGS: string; + const ACTION_HOME_SETTINGS: string; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: string; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: string; + const ACTION_INPUT_METHOD_SETTINGS: string; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: string; + const ACTION_INTERNAL_STORAGE_SETTINGS: string; + const ACTION_LOCALE_SETTINGS: string; + const ACTION_LOCATION_SOURCE_SETTINGS: string; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: string; + const ACTION_MEMORY_CARD_SETTINGS: string; + const ACTION_MONITORING_CERT_INFO: string; + const ACTION_NETWORK_OPERATOR_SETTINGS: string; + const ACTION_NFCSHARING_SETTINGS: string; + const ACTION_NFC_PAYMENT_SETTINGS: string; + const ACTION_NFC_SETTINGS: string; + const ACTION_NIGHT_DISPLAY_SETTINGS: string; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: string; + const ACTION_NOTIFICATION_SETTINGS: string; + const ACTION_PAIRING_SETTINGS: string; + const ACTION_PRIVACY_SETTINGS: string; + const ACTION_QUICK_LAUNCH_SETTINGS: string; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: string; + const ACTION_SECURITY_SETTINGS: string; + const ACTION_SETTINGS: string; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: string; + const ACTION_SHOW_INPUT_METHOD_PICKER: string; + const ACTION_SHOW_REGULATORY_INFO: string; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: string; + const ACTION_SOUND_SETTINGS: string; + const ACTION_STORAGE_MANAGER_SETTINGS: string; + const ACTION_SYNC_SETTINGS: string; + const ACTION_SYSTEM_UPDATE_SETTINGS: string; + const ACTION_TETHER_PROVISIONING_UI: string; + const ACTION_TRUSTED_CREDENTIALS_USER: string; + const ACTION_USAGE_ACCESS_SETTINGS: string; + const ACTION_USER_DICTIONARY_INSERT: string; + const ACTION_USER_DICTIONARY_SETTINGS: string; + const ACTION_USER_SETTINGS: string; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: string; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: string; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: string; + const ACTION_VOICE_INPUT_SETTINGS: string; + const ACTION_VPN_SETTINGS: string; + const ACTION_VR_LISTENER_SETTINGS: string; + const ACTION_WEBVIEW_SETTINGS: string; + const ACTION_WIFI_IP_SETTINGS: string; + const ACTION_WIFI_SETTINGS: string; + const ACTION_WIRELESS_SETTINGS: string; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: string; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: string; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_SETTINGS: string; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start: [number, number]; + end: [number, number]; + locations: number[]; +} + +export class LinearGradient extends Component { } + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExponentPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'remoteNotifications' | 'location' | + 'camera' | 'contacts' | 'audioRecording'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + function getAsync(type: PermissionType): Promise; + function askAsync(type: PermissionType): Promise; + + const CAMERA: string; + const CAMERA_ROLL: string; + const AUDIO_RECORDING: string; + const LOCATION: string; + const REMOTE_NOTIFICATIONS: string; + const NOTIFICATIONS: string; + const CONTACTS: string; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: Component): Component; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientation { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + const Orientation: Orientation; + function allow(orientation: string): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + keychainAccessible?: number; + } + function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: string) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], // TypeScript Version: 2.4 + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number; + stroke?: string; + strokeWidth?: number; + strokeOpacity?: number; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + x?: Axis; + y?: Axis; + rotate?: number; + scale?: number; + origin?: number | string; + originX?: number; + originY?: number; +} + +export class Svg extends Component<{ width: number, heigth: number }> { } +export class Rect extends Component { } + +export interface CircleProps extends SvgCommonProps { + cx: Axis; + cy: Axis; +} +export class Circle extends Component { } + +export interface EllipseProps extends CircleProps { + rx: Axis; + ry: Axis; +} +export class Ellipse extends Component { } + +export interface LineProps extends SvgCommonProps { + x1: Axis; + y1: Axis; + x2: Axis; + y2: Axis; +} +export class Line extends Component { } + +export interface PolyProps extends SvgCommonProps { + points: string; +} +export class Polygon extends Component { } +export class Polyline extends Component { } + +export interface PathLine extends SvgCommonProps { + d: string; +} +export class Path extends Component { } + +export interface TextProps extends SvgCommonProps { + textAnchor: string; +} +export class Text extends Component { } +export class G extends Component { } +export class Use extends Component<{ href: string, x: number, y: number }> { } +export class Symbol extends Component<{ viewbox: string, widt: number, height: number }> { } +export class Defs extends Component { } +export class RadialGradient extends Component { } + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** + * Util + */ +export namespace Util { + function getCurrentDeviceCountryAsync(): Promise; + function getCurrentLocaleAsync(): Promise; + function getCurrentTimeZoneAsync(): Promise; + function reload(): void; + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; // Android only +} + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} diff --git a/types/expo/tsconfig.json b/types/expo/tsconfig.json new file mode 100644 index 0000000000..f397f7494c --- /dev/null +++ b/types/expo/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.ts" + ] +} diff --git a/types/expo/tslint.json b/types/expo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/expo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 1c8fbc21efee6b784571cef57cd1a92c6ac15860 Mon Sep 17 00:00:00 2001 From: KonstantinKai Date: Tue, 21 Nov 2017 15:54:11 +0200 Subject: [PATCH 2/4] [expo] add tests --- types/expo/expo-tests.ts | 86 ----------------- types/expo/expo-tests.tsx | 191 ++++++++++++++++++++++++++++++++++++++ types/expo/index.d.ts | 75 +++++++-------- types/expo/tsconfig.json | 3 +- 4 files changed, 227 insertions(+), 128 deletions(-) delete mode 100644 types/expo/expo-tests.ts create mode 100644 types/expo/expo-tests.tsx diff --git a/types/expo/expo-tests.ts b/types/expo/expo-tests.ts deleted file mode 100644 index c8b7d5dc64..0000000000 --- a/types/expo/expo-tests.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - Accelerometer, - Amplitude, - Asset, - AuthSession, - Audio -} from 'expo'; - -Accelerometer.addListener((obj) => { - obj.x; - obj.y; - obj.z; -}); -Accelerometer.removeAllListeners(); -Accelerometer.setUpdateInterval(1000); - -Amplitude.initialize('key'); -Amplitude.setUserId('userId'); -Amplitude.setUserProperties({key: 1}); -Amplitude.clearUserProperties(); -Amplitude.logEvent('name'); -Amplitude.logEventWithProperties('event', {key: 'value'}); -Amplitude.setGroup('type', {key: 'value'}); - -const asset = Asset.fromModule(1); -asset.downloadAsync(); -Asset.loadAsync(1); -Asset.loadAsync([1, 2, 3]); -const asset1 = new Asset({ - uri: 'uri', - type: 'type', - name: 'name', - hash: 'hash', - width: 122, - height: 122 -}); - -const url = AuthSession.getRedirectUrl(); -AuthSession.dismiss(); -AuthSession.startAsync({ - authUrl: 'url1', - returnUrl: 'url2' -}).then(result => { - switch (result.type) { - case 'success': - result.event; - result.params; - break; - case 'error': - result.errorCode; - result.params; - result.event; - break; - case 'dismissed': - case 'cancel': - result.type; - break; - } -}); - -Audio.setAudioModeAsync({ - shouldDuckAndroid: false, - playsInSilentModeIOS: true, - interruptionModeIOS: 2, - interruptionModeAndroid: 1, - allowsRecordingIOS: true -}); -Audio.setIsEnabledAsync(true); -Audio.Sound.create('uri', { - volume: 0.5, - rate: 0.6 -}, null, true).then(result => { - const sound = result.sound; - const status = result.status; - - if (!status.isLoaded) { - status.error; - } else { - status.didJustFinish; - // etc. - } - - sound.getStatusAsync().then(_status => { - _status.isLoaded; - }); -}); diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx new file mode 100644 index 0000000000..c2ac532ace --- /dev/null +++ b/types/expo/expo-tests.tsx @@ -0,0 +1,191 @@ +import { + Accelerometer, + Amplitude, + Asset, + AuthSession, + Audio, + AppLoading, + BarCodeScanner, + BlurViewProps, + BlurView, + Brightness, + Camera, + DocumentPicker, + Facebook, + FacebookAds, + FileSystem +} from 'expo'; + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', {key: 'value'}); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true +}); +Audio.setIsEnabledAsync(true); +async () => { + const result = await Audio.Sound.create('uri', { + volume: 0.5, + rate: 0.6 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync('uri'); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(.6); + await Brightness.setSystemBrightnessAsync(.7); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const result = await Facebook.logInWithReadPermissionsAsync('appId'); + + if (result.type === 'success') { + result.expires; + result.token; + } +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); +}; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 5dfff55946..4e808c348a 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -24,6 +24,7 @@ export type Axis = number; export interface HashMap { [key: string]: any; } export type FloatFromZeroToOne = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type Md5 = string; /** * Accelerometer @@ -146,7 +147,7 @@ export interface PlaybackStatusToSet { export type Source = string | RequireSource | Asset; export class PlaybackObject { - loadAsync(source: Source, initialStatus: PlaybackStatusToSet, downloadFirst: boolean): Promise; + loadAsync(source: Source, initialStatus?: PlaybackStatusToSet, downloadFirst?: boolean): Promise; unloadAsync(): Promise; getStatusAsync(): Promise; setOnPlaybackStatusUpdate(onPlaybackStatusUpdate: (status: PlaybackStatus) => void): void; @@ -335,7 +336,7 @@ export type AppLoadingProperties = { } | { startAsync: null; onFinish: null; - onError: null; + onError?: null; }; export class AppLoading extends Component { } @@ -364,10 +365,10 @@ export class BlurView extends Component { } * Brightness */ export namespace Brightness { - function setBrightnessAsync(brightnessValue: number): Promise; - function getBrightnessAsync(): Promise; - function getSystemBrightnessAsync(): Promise; - function setSystemBrightnessAsync(brightnessValue: number): Promise; + function setBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; + function getBrightnessAsync(): Promise; + function getSystemBrightnessAsync(): Promise; + function setSystemBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; } /** @@ -398,29 +399,29 @@ export class CameraObject { getSupportedRatiosAsync(): Promise; // Android only } export interface CameraProperties extends ViewProperties { - onCameraReady: () => void; - onMountError: () => void; - flashMode: string | number; - type: string | number; - ratio: string; - autoFocus: string | number | boolean; - focusDepth: FloatFromZeroToOne; - zoom: FloatFromZeroToOne; - whiteBalance: string | number; - barCodeTypes: string[]; - onBarCodeRead: BarCodeReadCallback; - ref?: CameraObject; + flashMode?: string | number; + type?: string | number; + ratio?: string; + autoFocus?: string | number | boolean; + focusDepth?: FloatFromZeroToOne; + zoom?: FloatFromZeroToOne; + whiteBalance?: string | number; + barCodeTypes?: string[]; + onCameraReady?: () => void; + onMountError?: () => void; + onBarCodeRead?: BarCodeReadCallback; + ref?: Ref; } export interface CameraConstants { - Type: string; - FlashMode: string; - AutoFocus: string; - WhiteBalance: string; - VideoQuality: string; - BarCodeType: string; + readonly Type: string; + readonly FlashMode: string; + readonly AutoFocus: string; + readonly WhiteBalance: string; + readonly VideoQuality: string; + readonly BarCodeType: string; } export class Camera extends Component { - static Constants: CameraConstants; + static readonly Constants: CameraConstants; } /** @@ -694,7 +695,7 @@ export namespace Contacts { */ export namespace DocumentPicker { interface Options { - type: string; + type?: string; } type Response = { type: 'success'; @@ -705,7 +706,7 @@ export namespace DocumentPicker { type: 'cancel'; }; - function getDocumentAsync(options: Options): Response; + function getDocumentAsync(options?: Options): Promise; } /** @@ -730,7 +731,7 @@ export namespace Facebook { } | { type: 'cancel'; }; - function logInWithReadPermissionsAsync(appId: string, options: Options): Promise; + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; } /** @@ -803,7 +804,7 @@ export namespace FileSystem { uri: string; size: number; modificationTime: number; - md5?: string; + md5?: Md5; } | { exists: false; isDirectory: false; @@ -813,7 +814,7 @@ export namespace FileSystem { uri: string; status: number; headers: { [name: string]: string }; - md5?: string; + md5?: Md5; } const documentDirectory: string; @@ -825,9 +826,9 @@ export namespace FileSystem { function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; function moveAsync(options: { from: string, to: string; }): Promise; function copyAsync(options: { from: string, to: string; }): Promise; - function makeDirectoryAsync(fireUri: string, options?: { intermediates: boolean }): Promise; - function readDirectoryAsync(fileUri: string): Promise; - function downloadAsync(uri: string, fileUri: string, options?: { md5: boolean; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; function createDownloadResumable( uri: string, fileUri: string, @@ -863,14 +864,6 @@ export namespace FileSystem { callback?: DownloadProgressCallback, resumeData?: string ); - private _uuid: string; - private _url: string; - private _fileUri: string; - private _options: DownloadOptions; - private _emitter: NativeEventEmitter; - private _resumeData?: string; - private _callback?: DownloadProgressCallback; - private _subscription?: () => void; downloadAsync(): Promise; pauseAsync(): Promise; diff --git a/types/expo/tsconfig.json b/types/expo/tsconfig.json index f397f7494c..04edeb26ab 100644 --- a/types/expo/tsconfig.json +++ b/types/expo/tsconfig.json @@ -4,6 +4,7 @@ "lib": [ "es6" ], + "jsx": "react-native", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -18,6 +19,6 @@ }, "files": [ "index.d.ts", - "expo-tests.ts" + "expo-tests.tsx" ] } From 2f19225621fb21808e7d2c35b80b18519f44b42a Mon Sep 17 00:00:00 2001 From: KonstantinKai Date: Tue, 21 Nov 2017 16:00:14 +0200 Subject: [PATCH 3/4] [expo] add tests 2 --- types/expo/expo-tests.tsx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index c2ac532ace..d170c9fb2d 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -185,7 +185,17 @@ async () => { info.modificationTime; } - const string = await FileSystem.readAsStringAsync('file'); + const string: string = await FileSystem.readAsStringAsync('file'); await FileSystem.writeAsStringAsync('file', 'content'); await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; }; From e39b73235aadde72d1dd22c41e04620023e53dad Mon Sep 17 00:00:00 2001 From: KonstantinKai Date: Tue, 21 Nov 2017 16:18:46 +0200 Subject: [PATCH 4/4] [expo] fixes for tests --- types/expo/expo-tests.tsx | 2 ++ types/expo/index.d.ts | 3 ++- types/expo/tsconfig.json | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index d170c9fb2d..333b9d3e3c 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -1,3 +1,5 @@ +import * as React from 'react'; + import { Accelerometer, Amplitude, diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 4e808c348a..04d500ab6b 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expo/expo-sdk // Definitions by: Konstantin Kai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 import { EventSubscription } from 'fbemitter'; import { Component, Ref } from 'react'; @@ -1346,7 +1347,7 @@ export namespace SQLite { interface Transaction { executeSql( sqlStatement: string, - arguments?: string[] | number[], // TypeScript Version: 2.4 + arguments?: string[] | number[], success?: (transaction: Transaction, resultSet: ResultSet) => any, error?: (transaction: Transaction, error: Error) => any ): void; diff --git a/types/expo/tsconfig.json b/types/expo/tsconfig.json index 04edeb26ab..5d0f560837 100644 --- a/types/expo/tsconfig.json +++ b/types/expo/tsconfig.json @@ -4,7 +4,7 @@ "lib": [ "es6" ], - "jsx": "react-native", + "jsx": "react", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true,