feat(typescript): Source code rewrite using typescript (#425)

Rewrote the whole repository into typescript. This will provide way better and up to date documentation. This should also add some safety for people contributing 😄 .
Flow types were not working until now which is why this PR doesn't have them but feel free to PR.

This also fixes #384 #435 #206 #171 #168.
This commit is contained in:
Thibault Malbranche 2019-03-20 12:35:13 +00:00 committed by GitHub
parent e697dff1d0
commit 453b7dd3a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 2794 additions and 2182 deletions

View File

@ -35,7 +35,7 @@ jobs:
- run:
name: Run Tests
command: yarn ci:test
command: yarn ci
publish:
<<: *defaults

1
.eslintignore Normal file
View File

@ -0,0 +1 @@
lib/

75
.eslintrc.js Normal file
View File

@ -0,0 +1,75 @@
module.exports = {
// Airbnb is the base, prettier is here so that eslint doesn't conflict with prettier
extends: ['airbnb', 'prettier', 'prettier/react'],
parser: '@typescript-eslint/parser',
plugins: ['react', 'react-native', 'import', '@typescript-eslint'],
rules: {
'no-console': 'off',
// Lines will be broken before binary operators
'operator-linebreak': ['error', 'before'],
// Allow imports from dev and peer dependencies
'import/no-extraneous-dependencies': [
'error',
{ devDependencies: true, peerDependencies: true },
],
'react/jsx-filename-extension': ['error', { extensions: ['.tsx'] }],
// This rule doesn't play nice with Prettier
'react/jsx-one-expression-per-line': 'off',
// This rule doesn't play nice with Prettier
'react/jsx-wrap-multilines': 'off',
// Remove this rule because we only destructure props, but never state
'react/destructuring-assignment': 'off',
'react/prop-types': 'off',
'@typescript-eslint/adjacent-overload-signatures': 'error',
'@typescript-eslint/array-type': ['error', 'array'],
'@typescript-eslint/generic-type-naming': ['error', '^[a-zA-Z]+$'],
'@typescript-eslint/no-angle-bracket-type-assertion': 'error',
'@typescript-eslint/no-array-constructor': 'error',
'@typescript-eslint/no-empty-interface': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-extraneous-class': 'error',
'@typescript-eslint/no-inferrable-types': 'error',
'@typescript-eslint/no-misused-new': 'error',
'@typescript-eslint/no-namespace': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-object-literal-type-assertion': 'error',
'@typescript-eslint/no-parameter-properties': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-triple-slash-reference': 'error',
'@typescript-eslint/no-type-alias': [
'error',
{
allowAliases: 'always',
allowCallbacks: 'always',
allowMappedTypes: 'always',
},
],
'@typescript-eslint/no-unused-vars': [
'error',
{ ignoreRestSiblings: true },
],
'@typescript-eslint/prefer-interface': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
'@typescript-eslint/type-annotation-spacing': 'error',
},
settings: {
'import/resolver': {
node: {
extensions: [
'.js',
'.android.js',
'.ios.js',
'.jsx',
'.android.jsx',
'.ios.jsx',
'.tsx',
'.ts',
'.android.tsx',
'.android.ts',
'.ios.tsx',
'.ios.ts',
],
},
},
},
};

4
.gitignore vendored
View File

@ -51,4 +51,6 @@ bundles/
android/gradle
android/gradlew
android/gradlew.bat
android/gradlew.bat
lib/

10
.prettierrc.js Normal file
View File

@ -0,0 +1,10 @@
// https://prettier.io/docs/en/options.html
module.exports = {
// Enables semicolons at the end of statements
semi: true,
// Formats strings with single quotes ('') instead of quotes ("")
singleQuote: true,
// Adds a trailing comma at the end of all lists (including function arguments)
trailingComma: 'all',
};

9
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,9 @@
{
"typescript.tsdk": "node_modules/typescript/lib",
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
]
}

View File

@ -96,9 +96,9 @@ _Note that using static HTML requires the WebView property [originWhiteList](Ref
Controls whether to adjust the content inset for web views that are placed behind a navigation bar, tab bar, or toolbar. The default value is `true`.
| Type | Required |
| ---- | -------- |
| bool | No |
| Type | Required | Platform |
| ---- | -------- | -------- |
| bool | No | iOS |
---
@ -154,28 +154,29 @@ Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
onError={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent
console.warn('WebView error: ', nativeEvent)
}}
/>
source={{ uri: 'https://facebook.github.io/react-native' }}
onError={syntheticEvent => {
const { nativeEvent } = syntheticEvent;
console.warn('WebView error: ', nativeEvent);
}}
/>
```
Function passed to `onError` is called with a SyntheticEvent wrapping a nativeEvent with these properties:
```
canGoBack
canGoForward
code
description
didFailProvisionalNavigation
domain
loading
target
title
url
```
canGoBack
canGoForward
code
description
didFailProvisionalNavigation
domain
loading
target
title
url
```
> **_Note_**
> Domain is only used on iOS
@ -193,8 +194,8 @@ Example:
```jsx
<WebView
source={{uri: 'https://facebook.github.io/react-native'}}
onLoad={(syntheticEvent) => {
source={{ uri: 'https://facebook.github.io/react-native' }}
onLoad={syntheticEvent => {
const { nativeEvent } = syntheticEvent;
this.url = nativeEvent.url;
}}
@ -203,13 +204,13 @@ Example:
Function passed to `onLoad` is called with a SyntheticEvent wrapping a nativeEvent with these properties:
```
canGoBack
canGoForward
loading
target
title
url
```
canGoBack
canGoForward
loading
target
title
url
```
---
@ -222,13 +223,12 @@ Function that is invoked when the `WebView` load succeeds or fails.
| -------- | -------- |
| function | No |
Example:
```jsx
<WebView
source={{uri: 'https://facebook.github.io/react-native'}}
onLoadEnd={(syntheticEvent) => {
source={{ uri: 'https://facebook.github.io/react-native' }}
onLoadEnd={syntheticEvent => {
// update component to be aware of loading status
const { nativeEvent } = syntheticEvent;
this.isLoading = nativeEvent.loading;
@ -238,13 +238,13 @@ Example:
Function passed to `onLoadEnd` is called with a SyntheticEvent wrapping a nativeEvent with these properties:
```
canGoBack
canGoForward
loading
target
title
url
```
canGoBack
canGoForward
loading
target
title
url
```
---
@ -257,13 +257,12 @@ Function that is invoked when the `WebView` starts loading.
| -------- | -------- |
| function | No |
Example:
```jsx
<WebView
source={{uri: 'https://facebook.github.io/react-native/='}}
onLoadStart={(syntheticEvent) => {
source={{ uri: 'https://facebook.github.io/react-native/=' }}
onLoadStart={syntheticEvent => {
// update component to be aware of loading status
const { nativeEvent } = syntheticEvent;
this.isLoading = nativeEvent.loading;
@ -273,13 +272,13 @@ Example:
Function passed to `onLoadStart` is called with a SyntheticEvent wrapping a nativeEvent with these properties:
```
canGoBack
canGoForward
loading
target
title
url
```
canGoBack
canGoForward
loading
target
title
url
```
---
@ -301,23 +300,23 @@ Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
onLoadProgress={({ nativeEvent }) => {
this.loadingProgress = nativeEvent.progress
}}
/>
source={{ uri: 'https://facebook.github.io/react-native' }}
onLoadProgress={({ nativeEvent }) => {
this.loadingProgress = nativeEvent.progress;
}}
/>
```
Function passed to `onLoadProgress` is called with a SyntheticEvent wrapping a nativeEvent with these properties:
```
canGoBack
canGoForward
loading
progress
target
title
url
```
canGoBack
canGoForward
loading
progress
target
title
url
```
---
@ -348,23 +347,24 @@ Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
onNavigationStateChange={(navState) => {
source={{ uri: 'https://facebook.github.io/react-native' }}
onNavigationStateChange={navState => {
// Keep track of going back navigation within component
this.canGoBack = navState.canGoBack;
}} />
}}
/>
```
The `navState` object includes these properties:
```
canGoBack
canGoForward
loading
navigationType
target
title
url
```
canGoBack
canGoForward
loading
navigationType
target
title
url
```
---
@ -382,9 +382,9 @@ Example:
```jsx
//only allow URIs that begin with https:// or git://
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
originWhitelist={['https://*', 'git://*']}
/>
source={{ uri: 'https://facebook.github.io/react-native' }}
originWhitelist={['https://*', 'git://*']}
/>
```
---
@ -397,17 +397,16 @@ Function that returns a view to show if there's an error.
| -------- | -------- |
| function | No |
Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
renderError={(errorName) => <Error name={errorName} /> }
/>
source={{ uri: 'https://facebook.github.io/react-native' }}
renderError={errorName => <Error name={errorName} />}
/>
```
The function passed to `renderError` will be called with the name of the error
The function passed to `renderError` will be called with the name of the error
---
@ -419,15 +418,14 @@ Function that returns a loading indicator. The startInLoadingState prop must be
| -------- | -------- |
| function | No |
Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
startInLoadingState={true}
renderLoading={() => <Loading /> }
/>
source={{ uri: 'https://facebook.github.io/react-native' }}
startInLoadingState={true}
renderLoading={() => <Loading />}
/>
```
---
@ -446,7 +444,7 @@ On iOS, when [`useWebKit=true`](Reference.md#usewebkit), this prop will not work
### `onShouldStartLoadWithRequest`
Function that allows custom handling of any web view requests. Return `true` from the function to continue loading the request and `false` to stop loading.
Function that allows custom handling of any web view requests. Return `true` from the function to continue loading the request and `false` to stop loading.
On Android, is not called on the first load.
@ -458,10 +456,10 @@ Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
onShouldStartLoadWithRequest={(request) => {
source={{ uri: 'https://facebook.github.io/react-native' }}
onShouldStartLoadWithRequest={request => {
// Only allow navigating within this website
return request.url.startsWith("https://facebook.github.io/react-native")
return request.url.startsWith('https://facebook.github.io/react-native');
}}
/>
```
@ -483,10 +481,10 @@ Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
onShouldStartLoadWithRequest={(request) => {
source={{ uri: 'https://facebook.github.io/react-native' }}
onShouldStartLoadWithRequest={request => {
// Only allow navigating within this website
return request.url.startsWith("https://facebook.github.io/react-native")
return request.url.startsWith('https://facebook.github.io/react-native');
}}
/>
```
@ -528,9 +526,9 @@ Example:
```jsx
<WebView
source={{ uri: "https://facebook.github.io/react-native" }}
style={{marginTop: 20}}
/>
source={{ uri: 'https://facebook.github.io/react-native' }}
style={{ marginTop: 20 }}
/>
```
---

8
index.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
import { ComponentType } from 'react';
// eslint-disable-next-line
import { IOSWebViewProps, AndroidWebViewProps } from './lib/WebViewTypes';
declare const WebView: ComponentType<IOSWebViewProps & AndroidWebViewProps>;
export { WebView };
export default WebView;

View File

@ -1,3 +1,4 @@
import WebView from './js/WebView';
import WebView from './lib/WebView';
export { WebView };
export default WebView;

View File

@ -88,7 +88,7 @@ module.exports = {
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: "react-native",
preset: 'react-native',
// Run tests from one or more projects
// projects: null,
@ -129,7 +129,7 @@ module.exports = {
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
testEnvironment: 'node',
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
@ -164,7 +164,12 @@ module.exports = {
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: null,
transform: {
'^.+\\.ts(x)?$': 'ts-jest',
'^.+\\.js$': 'babel-jest',
'^.+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$':
'<rootDir>/node_modules/react-native/jest/assetFileTransformer.js',
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [

View File

@ -1,352 +0,0 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
import React from 'react';
import ReactNative, {
ActivityIndicator,
Image,
requireNativeComponent,
StyleSheet,
UIManager,
View,
NativeModules,
} from 'react-native';
import invariant from 'fbjs/lib/invariant';
import keyMirror from 'fbjs/lib/keyMirror';
import {
defaultOriginWhitelist,
createOnShouldStartLoadWithRequest,
} from './WebViewShared';
import type {
WebViewError,
WebViewErrorEvent,
WebViewMessageEvent,
WebViewNavigationEvent,
WebViewProgressEvent,
WebViewSharedProps,
WebViewSource,
} from './WebViewTypes';
const resolveAssetSource = Image.resolveAssetSource;
const WebViewState = keyMirror({
IDLE: null,
LOADING: null,
ERROR: null,
});
const defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator style={styles.loadingProgressBar} />
</View>
);
type State = {|
viewState: WebViewState,
lastErrorEvent: ?WebViewError,
|};
/**
* Renders a native WebView.
*/
class WebView extends React.Component<WebViewSharedProps, State> {
static defaultProps = {
overScrollMode: 'always',
javaScriptEnabled: true,
thirdPartyCookiesEnabled: true,
scalesPageToFit: true,
allowFileAccess: false,
saveFormDataDisabled: false,
cacheEnabled: true,
androidHardwareAccelerationDisabled: false,
originWhitelist: defaultOriginWhitelist,
};
static isFileUploadSupported = async () => {
// native implementation should return "true" only for Android 5+
return NativeModules.RNCWebView.isFileUploadSupported();
};
state = {
viewState: this.props.startInLoadingState
? WebViewState.LOADING
: WebViewState.IDLE,
lastErrorEvent: null,
};
webViewRef = React.createRef();
render() {
let otherView = null;
if (this.state.viewState === WebViewState.LOADING) {
otherView = (this.props.renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === WebViewState.ERROR) {
const errorEvent = this.state.lastErrorEvent;
invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
otherView =
this.props.renderError &&
this.props.renderError(
errorEvent.domain,
errorEvent.code,
errorEvent.description,
);
} else if (this.state.viewState !== WebViewState.IDLE) {
console.error(
'RNCWebView invalid state encountered: ' + this.state.viewState,
);
}
const webViewStyles = [styles.container, this.props.style];
if (
this.state.viewState === WebViewState.LOADING ||
this.state.viewState === WebViewState.ERROR
) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
let source: WebViewSource = this.props.source || {};
if (!this.props.source && this.props.html) {
source = { html: this.props.html };
} else if (!this.props.source && this.props.url) {
source = { uri: this.props.url };
}
if (source.method === 'POST' && source.headers) {
console.warn(
'WebView: `source.headers` is not supported when using POST.',
);
} else if (source.method === 'GET' && source.body) {
console.warn('WebView: `source.body` is not supported when using GET.');
}
const nativeConfig = this.props.nativeConfig || {};
let NativeWebView = nativeConfig.component || RNCWebView;
const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
this.onShouldStartLoadWithRequestCallback,
this.props.originWhitelist,
this.props.onShouldStartLoadWithRequest,
);
const webView = (
<NativeWebView
ref={this.webViewRef}
key="webViewKey"
style={webViewStyles}
source={resolveAssetSource(source)}
scalesPageToFit={this.props.scalesPageToFit}
allowFileAccess={this.props.allowFileAccess}
injectedJavaScript={this.props.injectedJavaScript}
userAgent={this.props.userAgent}
javaScriptEnabled={this.props.javaScriptEnabled}
androidHardwareAccelerationDisabled={
this.props.androidHardwareAccelerationDisabled
}
thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
domStorageEnabled={this.props.domStorageEnabled}
cacheEnabled={this.props.cacheEnabled}
onMessage={this.onMessage}
messagingEnabled={typeof this.props.onMessage === 'function'}
overScrollMode={this.props.overScrollMode}
contentInset={this.props.contentInset}
automaticallyAdjustContentInsets={
this.props.automaticallyAdjustContentInsets
}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
onContentSizeChange={this.props.onContentSizeChange}
onLoadingStart={this.onLoadingStart}
onLoadingFinish={this.onLoadingFinish}
onLoadingError={this.onLoadingError}
onLoadingProgress={this.onLoadingProgress}
testID={this.props.testID}
geolocationEnabled={this.props.geolocationEnabled}
mediaPlaybackRequiresUserAction={
this.props.mediaPlaybackRequiresUserAction
}
allowUniversalAccessFromFileURLs={
this.props.allowUniversalAccessFromFileURLs
}
mixedContentMode={this.props.mixedContentMode}
saveFormDataDisabled={this.props.saveFormDataDisabled}
urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
showsHorizontalScrollIndicator={this.props.showsHorizontalScrollIndicator}
showsVerticalScrollIndicator={this.props.showsVerticalScrollIndicator}
{...nativeConfig.props}
/>
);
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
}
getViewManagerConfig = (viewManagerName: string) => {
if (!UIManager.getViewManagerConfig) {
return UIManager[viewManagerName];
}
return UIManager.getViewManagerConfig(viewManagerName);
};
getCommands = () => this.getViewManagerConfig('RNCWebView').Commands;
goForward = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().goForward,
null,
);
};
goBack = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().goBack,
null,
);
};
reload = () => {
this.setState({
viewState: WebViewState.LOADING,
});
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().reload,
null,
);
};
stopLoading = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().stopLoading,
null,
);
};
postMessage = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().postMessage,
[String(data)],
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().injectJavaScript,
[data],
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
updateNavigationState = (event: WebViewNavigationEvent) => {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
};
getWebViewHandle = () => {
return ReactNative.findNodeHandle(this.webViewRef.current);
};
onLoadingStart = (event: WebViewNavigationEvent) => {
const onLoadStart = this.props.onLoadStart;
onLoadStart && onLoadStart(event);
this.updateNavigationState(event);
};
onLoadingError = (event: WebViewErrorEvent) => {
event.persist(); // persist this event because we need to store it
const { onError, onLoadEnd } = this.props;
onError && onError(event);
onLoadEnd && onLoadEnd(event);
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: WebViewState.ERROR,
});
};
onLoadingFinish = (event: WebViewNavigationEvent) => {
const { onLoad, onLoadEnd } = this.props;
onLoad && onLoad(event);
onLoadEnd && onLoadEnd(event);
this.setState({
viewState: WebViewState.IDLE,
});
this.updateNavigationState(event);
};
onMessage = (event: WebViewMessageEvent) => {
const { onMessage } = this.props;
onMessage && onMessage(event);
};
onLoadingProgress = (event: WebViewProgressEvent) => {
const { onLoadProgress } = this.props;
onLoadProgress && onLoadProgress(event);
};
onShouldStartLoadWithRequestCallback = (
shouldStart: boolean,
url: string,
) => {
if (shouldStart) {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().loadUrl,
[String(url)],
);
}
};
}
const RNCWebView = requireNativeComponent('RNCWebView');
const styles = StyleSheet.create({
container: {
flex: 1,
},
hidden: {
height: 0,
flex: 0, // disable 'flex:1' when hiding a View
},
loadingView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
loadingProgressBar: {
height: 20,
},
});
module.exports = WebView;

View File

@ -1,528 +0,0 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
import React from 'react';
import {
ActivityIndicator,
Linking,
StyleSheet,
Text,
UIManager,
View,
requireNativeComponent,
NativeModules,
Image,
findNodeHandle,
} from 'react-native';
import invariant from 'fbjs/lib/invariant';
import keyMirror from 'fbjs/lib/keyMirror';
import {
defaultOriginWhitelist,
createOnShouldStartLoadWithRequest,
} from './WebViewShared';
import type {
WebViewEvent,
WebViewError,
WebViewErrorEvent,
WebViewMessageEvent,
WebViewNavigationEvent,
WebViewSharedProps,
WebViewSource,
WebViewProgressEvent,
} from './WebViewTypes';
const resolveAssetSource = Image.resolveAssetSource;
let didWarnAboutUIWebViewUsage = false;
// Imported from https://github.com/facebook/react-native/blob/master/Libraries/Components/ScrollView/processDecelerationRate.js
function processDecelerationRate(decelerationRate) {
if (decelerationRate === 'normal') {
decelerationRate = 0.998;
} else if (decelerationRate === 'fast') {
decelerationRate = 0.99;
}
return decelerationRate;
}
const RNCUIWebViewManager = NativeModules.RNCUIWebViewManager;
const RNCWKWebViewManager = NativeModules.RNCWKWebViewManager;
const BGWASH = 'rgba(255,255,255,0.8)';
const WebViewState = keyMirror({
IDLE: null,
LOADING: null,
ERROR: null,
});
const NavigationType = keyMirror({
click: true,
formsubmit: true,
backforward: true,
reload: true,
formresubmit: true,
other: true,
});
const JSNavigationScheme = 'react-js-navigation';
type State = {|
viewState: WebViewState,
lastErrorEvent: ?WebViewError,
|};
const DataDetectorTypes = [
'phoneNumber',
'link',
'address',
'calendarEvent',
'trackingNumber',
'flightNumber',
'lookupSuggestion',
'none',
'all',
];
const defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator />
</View>
);
const defaultRenderError = (errorDomain, errorCode, errorDesc) => (
<View style={styles.errorContainer}>
<Text style={styles.errorTextTitle}>Error loading page</Text>
<Text style={styles.errorText}>{'Domain: ' + errorDomain}</Text>
<Text style={styles.errorText}>{'Error Code: ' + errorCode}</Text>
<Text style={styles.errorText}>{'Description: ' + errorDesc}</Text>
</View>
);
/**
* `WebView` renders web content in a native view.
*
*```
* import React, { Component } from 'react';
* import { WebView } from 'react-native';
*
* class MyWeb extends Component {
* render() {
* return (
* <WebView
* source={{uri: 'https://github.com/facebook/react-native'}}
* style={{marginTop: 20}}
* />
* );
* }
* }
*```
*
* You can use this component to navigate back and forth in the web view's
* history and configure various properties for the web content.
*/
class WebView extends React.Component<WebViewSharedProps, State> {
static JSNavigationScheme = JSNavigationScheme;
static NavigationType = NavigationType;
static defaultProps = {
useWebKit: true,
cacheEnabled: true,
originWhitelist: defaultOriginWhitelist,
useSharedProcessPool: true,
};
static isFileUploadSupported = async () => {
// no native implementation for iOS, depends only on permissions
return true;
};
state = {
viewState: this.props.startInLoadingState
? WebViewState.LOADING
: WebViewState.IDLE,
lastErrorEvent: null,
};
webViewRef = React.createRef();
UNSAFE_componentWillMount() {
if (!this.props.useWebKit && !didWarnAboutUIWebViewUsage) {
didWarnAboutUIWebViewUsage = true;
console.warn(
'UIWebView is deprecated and will be removed soon, please use WKWebView (do not override useWebkit={true} prop),' +
' more infos here: https://github.com/react-native-community/react-native-webview/issues/312',
);
}
if (
this.props.useWebKit === true &&
this.props.scalesPageToFit !== undefined
) {
console.warn(
'The scalesPageToFit property is not supported when useWebKit = true',
);
}
if (
!this.props.useWebKit &&
this.props.allowsBackForwardNavigationGestures
) {
console.warn(
'The allowsBackForwardNavigationGestures property is not supported when useWebKit = false',
);
}
if (!this.props.useWebKit && this.props.incognito) {
console.warn(
'The incognito property is not supported when useWebKit = false',
);
}
}
render() {
let otherView = null;
let scalesPageToFit;
if (this.props.useWebKit) {
({ scalesPageToFit } = this.props);
} else {
({ scalesPageToFit = true } = this.props);
}
if (this.state.viewState === WebViewState.LOADING) {
otherView = (this.props.renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === WebViewState.ERROR) {
const errorEvent = this.state.lastErrorEvent;
invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
otherView = (this.props.renderError || defaultRenderError)(
errorEvent.domain,
errorEvent.code,
errorEvent.description,
);
} else if (this.state.viewState !== WebViewState.IDLE) {
console.error(
'RNCWebView invalid state encountered: ' + this.state.viewState,
);
}
const webViewStyles = [styles.container, styles.webView, this.props.style];
if (
this.state.viewState === WebViewState.LOADING ||
this.state.viewState === WebViewState.ERROR
) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
const nativeConfig = this.props.nativeConfig || {};
const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
this.onShouldStartLoadWithRequestCallback,
this.props.originWhitelist,
this.props.onShouldStartLoadWithRequest,
);
const decelerationRate = processDecelerationRate(
this.props.decelerationRate,
);
let source: WebViewSource = this.props.source || {};
if (!this.props.source && this.props.html) {
source = { html: this.props.html };
} else if (!this.props.source && this.props.url) {
source = { uri: this.props.url };
}
let NativeWebView = nativeConfig.component;
if (this.props.useWebKit) {
NativeWebView = NativeWebView || RNCWKWebView;
} else {
NativeWebView = NativeWebView || RNCUIWebView;
}
const webView = (
<NativeWebView
ref={this.webViewRef}
key="webViewKey"
style={webViewStyles}
source={resolveAssetSource(source)}
injectedJavaScript={this.props.injectedJavaScript}
bounces={this.props.bounces}
scrollEnabled={this.props.scrollEnabled}
pagingEnabled={this.props.pagingEnabled}
cacheEnabled={this.props.cacheEnabled}
decelerationRate={decelerationRate}
contentInset={this.props.contentInset}
automaticallyAdjustContentInsets={
this.props.automaticallyAdjustContentInsets
}
hideKeyboardAccessoryView={this.props.hideKeyboardAccessoryView}
allowsBackForwardNavigationGestures={
this.props.allowsBackForwardNavigationGestures
}
incognito={this.props.incognito}
userAgent={this.props.userAgent}
onLoadingStart={this._onLoadingStart}
onLoadingFinish={this._onLoadingFinish}
onLoadingError={this._onLoadingError}
onLoadingProgress={this._onLoadingProgress}
onMessage={this._onMessage}
messagingEnabled={typeof this.props.onMessage === 'function'}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
scalesPageToFit={scalesPageToFit}
allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
mediaPlaybackRequiresUserAction={
this.props.mediaPlaybackRequiresUserAction
}
dataDetectorTypes={this.props.dataDetectorTypes}
useSharedProcessPool={this.props.useSharedProcessPool}
allowsLinkPreview={this.props.allowsLinkPreview}
showsHorizontalScrollIndicator={this.props.showsHorizontalScrollIndicator}
showsVerticalScrollIndicator={this.props.showsVerticalScrollIndicator}
directionalLockEnabled={this.props.directionalLockEnabled}
{...nativeConfig.props}
/>
);
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
}
_getViewManagerConfig = (viewManagerName: string) => {
if (!UIManager.getViewManagerConfig) {
return UIManager[viewManagerName];
}
return UIManager.getViewManagerConfig(viewManagerName);
};
_getCommands = () =>
!this.props.useWebKit
? this._getViewManagerConfig('RNCUIWebView').Commands
: this._getViewManagerConfig('RNCWKWebView').Commands;
/**
* Go forward one page in the web view's history.
*/
goForward = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this._getCommands().goForward,
null,
);
};
/**
* Go back one page in the web view's history.
*/
goBack = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this._getCommands().goBack,
null,
);
};
/**
* Reloads the current page.
*/
reload = () => {
this.setState({ viewState: WebViewState.LOADING });
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this._getCommands().reload,
null,
);
};
/**
* Stop loading the current page.
*/
stopLoading = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this._getCommands().stopLoading,
null,
);
};
/**
* Posts a message to the web view, which will emit a `message` event.
* Accepts one argument, `data`, which must be a string.
*
* In your webview, you'll need to something like the following.
*
* ```js
* document.addEventListener('message', e => { document.title = e.data; });
* ```
*/
postMessage = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this._getCommands().postMessage,
[String(data)],
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this._getCommands().injectJavaScript,
[data],
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
_updateNavigationState = (event: WebViewNavigationEvent) => {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
};
/**
* Returns the native `WebView` node.
*/
getWebViewHandle = () => {
return findNodeHandle(this.webViewRef.current);
};
_onLoadingStart = (event: WebViewNavigationEvent) => {
const onLoadStart = this.props.onLoadStart;
onLoadStart && onLoadStart(event);
this._updateNavigationState(event);
};
_onLoadingError = (event: WebViewErrorEvent) => {
event.persist(); // persist this event because we need to store it
const { onError, onLoadEnd } = this.props;
onError && onError(event);
onLoadEnd && onLoadEnd(event);
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: WebViewState.ERROR,
});
};
_onLoadingFinish = (event: WebViewNavigationEvent) => {
const { onLoad, onLoadEnd } = this.props;
onLoad && onLoad(event);
onLoadEnd && onLoadEnd(event);
this.setState({
viewState: WebViewState.IDLE,
});
this._updateNavigationState(event);
};
_onMessage = (event: WebViewMessageEvent) => {
const { onMessage } = this.props;
onMessage && onMessage(event);
};
_onLoadingProgress = (event: WebViewProgressEvent) => {
const { onLoadProgress } = this.props;
onLoadProgress && onLoadProgress(event);
};
onShouldStartLoadWithRequestCallback = (
shouldStart: boolean,
url: string,
lockIdentifier: number,
) => {
let viewManager = (this.props.nativeConfig || {}).viewManager;
if (this.props.useWebKit) {
viewManager = viewManager || RNCWKWebViewManager;
} else {
viewManager = viewManager || RNCUIWebViewManager;
}
invariant(viewManager != null, 'viewManager expected to be non-null');
viewManager.startLoadWithResult(!!shouldStart, lockIdentifier);
};
componentDidUpdate(prevProps: WebViewSharedProps) {
if (!(prevProps.useWebKit && this.props.useWebKit)) {
return;
}
this._showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
this._showRedboxOnPropChanges(prevProps, 'incognito');
this._showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
this._showRedboxOnPropChanges(prevProps, 'dataDetectorTypes');
if (this.props.scalesPageToFit !== undefined) {
console.warn(
'The scalesPageToFit property is not supported when useWebKit = true',
);
}
}
_showRedboxOnPropChanges(prevProps, propName: string) {
if (this.props[propName] !== prevProps[propName]) {
console.error(
`Changes to property ${propName} do nothing after the initial render.`,
);
}
}
}
const RNCUIWebView = requireNativeComponent('RNCUIWebView');
const RNCWKWebView = requireNativeComponent('RNCWKWebView');
const styles = StyleSheet.create({
container: {
flex: 1,
},
errorContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: BGWASH,
},
errorText: {
fontSize: 14,
textAlign: 'center',
marginBottom: 2,
},
errorTextTitle: {
fontSize: 15,
fontWeight: '500',
marginBottom: 10,
},
hidden: {
height: 0,
flex: 0, // disable 'flex:1' when hiding a View
},
loadingView: {
backgroundColor: BGWASH,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 100,
},
webView: {
backgroundColor: '#ffffff',
},
});
module.exports = WebView;

View File

@ -11,38 +11,58 @@
"version": "5.3.1",
"homepage": "https://github.com/react-native-community/react-native-webview#readme",
"scripts": {
"test:js": "jest",
"test:ios:flow": "flow check",
"test:android:flow": "flow check --flowconfig-name .flowconfig.android",
"ci": "CI=true && yarn lint && yarn test",
"ci:publish": "yarn semantic-release",
"ci:test": "yarn ci:test:flow && yarn ci:test:js",
"ci:test:flow": "yarn test:ios:flow && yarn test:android:flow",
"ci:test:js": "yarn test:js",
"semantic-release": "semantic-release"
"lint": "yarn tsc --noEmit && yarn eslint ./src --ext .ts,.tsx",
"build": "yarn tsc",
"prepack": "yarn build",
"test": "yarn jest"
},
"peerDependencies": {
"react": "^16.0",
"react-native": ">=0.57 <0.59"
"react-native": ">=0.57 <0.60"
},
"dependencies": {
"escape-string-regexp": "^1.0.5",
"fbjs": "^0.8.17"
"escape-string-regexp": "1.0.5",
"invariant": "2.2.4"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/core": "7.3.4",
"@semantic-release/git": "7.0.5",
"@types/react": "^16.6.3",
"@types/react-native": "^0.57.8",
"@types/escape-string-regexp": "1.0.0",
"@types/invariant": "^2.2.29",
"@types/jest": "24.0.11",
"@types/react": "16.8.8",
"@types/react-native": "0.57.40",
"@typescript-eslint/eslint-plugin": "1.4.2",
"@typescript-eslint/parser": "1.4.2",
"babel-eslint": "10.0.1",
"babel-jest": "^24.0.0",
"flow-bin": "^0.80.0",
"jest": "^24.0.0",
"metro-react-native-babel-preset": "^0.51.1",
"react": "16.6.3",
"react-native": "^0.57.8",
"semantic-release": "15.10.3"
"eslint": "5.15.1",
"eslint-config-airbnb": "17.1.0",
"eslint-config-prettier": "4.1.0",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jsx-a11y": "6.2.1",
"eslint-plugin-react": "7.12.4",
"eslint-plugin-react-native": "3.6.0",
"jest": "24.5.0",
"metro-react-native-babel-preset": "0.53.1",
"react": "16.8.3",
"react-native": "0.59.1",
"semantic-release": "15.10.3",
"ts-jest": "24.0.0",
"typescript": "3.3.3333"
},
"repository": {
"type": "git",
"url": "https://github.com/react-native-community/react-native-webview.git"
}
},
"files": [
"android",
"ios",
"lib",
"index.js",
"index.d.ts",
"react-native-webview.podspec"
]
}

304
src/WebView.android.tsx Normal file
View File

@ -0,0 +1,304 @@
import React from 'react';
import {
ActivityIndicator,
Image,
requireNativeComponent,
UIManager as NotTypedUIManager,
View,
NativeModules,
ImageSourcePropType,
findNodeHandle,
} from 'react-native';
import invariant from 'invariant';
import {
defaultOriginWhitelist,
createOnShouldStartLoadWithRequest,
getViewManagerConfig,
} from './WebViewShared';
import {
WebViewErrorEvent,
WebViewMessageEvent,
WebViewNavigationEvent,
WebViewProgressEvent,
AndroidWebViewProps,
NativeWebViewAndroid,
State,
CustomUIManager,
} from './WebViewTypes';
import styles from './WebView.styles';
const UIManager = NotTypedUIManager as CustomUIManager;
const RNCWebView = requireNativeComponent(
'RNCWebView',
) as typeof NativeWebViewAndroid;
const { resolveAssetSource } = Image;
const defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator style={styles.loadingProgressBar} />
</View>
);
/**
* Renders a native WebView.
*/
class WebView extends React.Component<AndroidWebViewProps, State> {
static defaultProps = {
overScrollMode: 'always',
javaScriptEnabled: true,
thirdPartyCookiesEnabled: true,
scalesPageToFit: true,
allowFileAccess: false,
saveFormDataDisabled: false,
cacheEnabled: true,
androidHardwareAccelerationDisabled: false,
originWhitelist: defaultOriginWhitelist,
};
static isFileUploadSupported = async () => {
// native implementation should return "true" only for Android 5+
return NativeModules.RNCWebView.isFileUploadSupported();
};
state: State = {
viewState: this.props.startInLoadingState ? 'LOADING' : 'IDLE',
lastErrorEvent: null,
};
webViewRef = React.createRef<NativeWebViewAndroid>();
getCommands = () => getViewManagerConfig('RNCWebView').Commands;
goForward = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().goForward,
null,
);
};
goBack = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().goBack,
null,
);
};
reload = () => {
this.setState({
viewState: 'LOADING',
});
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().reload,
null,
);
};
stopLoading = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().stopLoading,
null,
);
};
postMessage = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().postMessage,
[String(data)],
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().injectJavaScript,
[data],
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
updateNavigationState = (event: WebViewNavigationEvent) => {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
};
/**
* Returns the native `WebView` node.
*/
getWebViewHandle = () => {
const nodeHandle = findNodeHandle(this.webViewRef.current);
invariant(nodeHandle != null, 'nodeHandle expected to be non-null');
return nodeHandle as number;
};
onLoadingStart = (event: WebViewNavigationEvent) => {
const { onLoadStart } = this.props;
if (onLoadStart) {
onLoadStart(event);
}
this.updateNavigationState(event);
};
onLoadingError = (event: WebViewErrorEvent) => {
event.persist(); // persist this event because we need to store it
const { onError, onLoadEnd } = this.props;
if (onError) {
onError(event);
}
if (onLoadEnd) {
onLoadEnd(event);
}
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: 'ERROR',
});
};
onLoadingFinish = (event: WebViewNavigationEvent) => {
const { onLoad, onLoadEnd } = this.props;
if (onLoad) {
onLoad(event);
}
if (onLoadEnd) {
onLoadEnd(event);
}
this.setState({
viewState: 'IDLE',
});
this.updateNavigationState(event);
};
onMessage = (event: WebViewMessageEvent) => {
const { onMessage } = this.props;
if (onMessage) {
onMessage(event);
}
};
onLoadingProgress = (event: WebViewProgressEvent) => {
const { onLoadProgress } = this.props;
if (onLoadProgress) {
onLoadProgress(event);
}
};
onShouldStartLoadWithRequestCallback = (
shouldStart: boolean,
url: string,
) => {
if (shouldStart) {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().loadUrl,
[String(url)],
);
}
};
render() {
const {
onMessage,
onShouldStartLoadWithRequest: onShouldStartLoadWithRequestProp,
originWhitelist,
renderError,
renderLoading,
source,
style,
nativeConfig = {},
...otherProps
} = this.props;
let otherView = null;
if (this.state.viewState === 'LOADING') {
otherView = (renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === 'ERROR') {
const errorEvent = this.state.lastErrorEvent;
invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
otherView
= renderError
&& renderError(errorEvent.domain, errorEvent.code, errorEvent.description);
} else if (this.state.viewState !== 'IDLE') {
console.error(
`RNCWebView invalid state encountered: ${this.state.viewState}`,
);
}
const webViewStyles = [styles.container, style];
if (
this.state.viewState === 'LOADING'
|| this.state.viewState === 'ERROR'
) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
if (source && 'method' in source) {
if (source.method === 'POST' && source.headers) {
console.warn(
'WebView: `source.headers` is not supported when using POST.',
);
} else if (source.method === 'GET' && source.body) {
console.warn('WebView: `source.body` is not supported when using GET.');
}
}
const NativeWebView
= (nativeConfig.component as typeof NativeWebViewAndroid) || RNCWebView;
const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
this.onShouldStartLoadWithRequestCallback,
// casting cause it's in the default props
originWhitelist as ReadonlyArray<string>,
onShouldStartLoadWithRequestProp,
);
const webView = (
<NativeWebView
key="webViewKey"
{...otherProps}
messagingEnabled={typeof onMessage === 'function'}
onLoadingError={this.onLoadingError}
onLoadingFinish={this.onLoadingFinish}
onLoadingProgress={this.onLoadingProgress}
onLoadingStart={this.onLoadingStart}
onMessage={this.onMessage}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
ref={this.webViewRef}
// TODO: find a better way to type this.
source={resolveAssetSource(source as ImageSourcePropType)}
style={webViewStyles}
{...nativeConfig.props}
/>
);
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
}
}
export default WebView;

422
src/WebView.ios.tsx Normal file
View File

@ -0,0 +1,422 @@
import React from 'react';
import {
ActivityIndicator,
Text,
UIManager as NotTypedUIManager,
View,
requireNativeComponent,
NativeModules,
Image,
findNodeHandle,
ImageSourcePropType,
} from 'react-native';
import invariant from 'invariant';
import {
defaultOriginWhitelist,
createOnShouldStartLoadWithRequest,
getViewManagerConfig,
} from './WebViewShared';
import {
WebViewErrorEvent,
WebViewMessageEvent,
WebViewNavigationEvent,
WebViewProgressEvent,
IOSWebViewProps,
DecelerationRateConstant,
NativeWebViewIOS,
ViewManager,
State,
CustomUIManager,
WebViewNativeConfig,
} from './WebViewTypes';
import styles from './WebView.styles';
const UIManager = NotTypedUIManager as CustomUIManager;
const { resolveAssetSource } = Image;
let didWarnAboutUIWebViewUsage = false;
// Imported from https://github.com/facebook/react-native/blob/master/Libraries/Components/ScrollView/processDecelerationRate.js
const processDecelerationRate = (
decelerationRate: DecelerationRateConstant | number | undefined,
) => {
let newDecelerationRate = decelerationRate;
if (newDecelerationRate === 'normal') {
newDecelerationRate = 0.998;
} else if (newDecelerationRate === 'fast') {
newDecelerationRate = 0.99;
}
return newDecelerationRate;
};
const RNCUIWebViewManager = NativeModules.RNCUIWebViewManager as ViewManager;
const RNCWKWebViewManager = NativeModules.RNCWKWebViewManager as ViewManager;
const RNCUIWebView: typeof NativeWebViewIOS = requireNativeComponent(
'RNCUIWebView',
);
const RNCWKWebView: typeof NativeWebViewIOS = requireNativeComponent(
'RNCWKWebView',
);
const defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator />
</View>
);
const defaultRenderError = (
errorDomain: string | undefined,
errorCode: number,
errorDesc: string,
) => (
<View style={styles.errorContainer}>
<Text style={styles.errorTextTitle}>Error loading page</Text>
<Text style={styles.errorText}>{`Domain: ${errorDomain}`}</Text>
<Text style={styles.errorText}>{`Error Code: ${errorCode}`}</Text>
<Text style={styles.errorText}>{`Description: ${errorDesc}`}</Text>
</View>
);
class WebView extends React.Component<IOSWebViewProps, State> {
static defaultProps = {
useWebKit: true,
cacheEnabled: true,
originWhitelist: defaultOriginWhitelist,
useSharedProcessPool: true,
};
static isFileUploadSupported = async () => {
// no native implementation for iOS, depends only on permissions
return true;
};
state: State = {
viewState: this.props.startInLoadingState ? 'LOADING' : 'IDLE',
lastErrorEvent: null,
};
webViewRef = React.createRef<NativeWebViewIOS>();
// eslint-disable-next-line camelcase
UNSAFE_componentWillMount() {
if (!this.props.useWebKit && !didWarnAboutUIWebViewUsage) {
didWarnAboutUIWebViewUsage = true;
console.warn(
'UIWebView is deprecated and will be removed soon, please use WKWebView (do not override useWebkit={true} prop),'
+ ' more infos here: https://github.com/react-native-community/react-native-webview/issues/312',
);
}
if (
this.props.useWebKit === true
&& this.props.scalesPageToFit !== undefined
) {
console.warn(
'The scalesPageToFit property is not supported when useWebKit = true',
);
}
if (
!this.props.useWebKit
&& this.props.allowsBackForwardNavigationGestures
) {
console.warn(
'The allowsBackForwardNavigationGestures property is not supported when useWebKit = false',
);
}
if (!this.props.useWebKit && this.props.incognito) {
console.warn(
'The incognito property is not supported when useWebKit = false',
);
}
}
// eslint-disable-next-line react/sort-comp
getCommands = () =>
!this.props.useWebKit
? getViewManagerConfig('RNCUIWebView').Commands
: getViewManagerConfig('RNCWKWebView').Commands;
/**
* Go forward one page in the web view's history.
*/
goForward = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().goForward,
null,
);
};
/**
* Go back one page in the web view's history.
*/
goBack = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().goBack,
null,
);
};
/**
* Reloads the current page.
*/
reload = () => {
this.setState({ viewState: 'LOADING' });
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().reload,
null,
);
};
/**
* Stop loading the current page.
*/
stopLoading = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().stopLoading,
null,
);
};
/**
* Posts a message to the web view, which will emit a `message` event.
* Accepts one argument, `data`, which must be a string.
*
* In your webview, you'll need to something like the following.
*
* ```js
* document.addEventListener('message', e => { document.title = e.data; });
* ```
*/
postMessage = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().postMessage,
[String(data)],
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data: string) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
this.getCommands().injectJavaScript,
[data],
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
updateNavigationState = (event: WebViewNavigationEvent) => {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
};
/**
* Returns the native `WebView` node.
*/
getWebViewHandle = () => {
const nodeHandle = findNodeHandle(this.webViewRef.current);
invariant(nodeHandle != null, 'nodeHandle expected to be non-null');
return nodeHandle as number;
};
onLoadingStart = (event: WebViewNavigationEvent) => {
const { onLoadStart } = this.props;
if (onLoadStart) {
onLoadStart(event);
}
this.updateNavigationState(event);
};
onLoadingError = (event: WebViewErrorEvent) => {
event.persist(); // persist this event because we need to store it
const { onError, onLoadEnd } = this.props;
if (onLoadEnd) {
onLoadEnd(event);
}
if (onError) {
onError(event);
}
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: 'ERROR',
});
};
onLoadingFinish = (event: WebViewNavigationEvent) => {
const { onLoad, onLoadEnd } = this.props;
if (onLoad) {
onLoad(event);
}
if (onLoadEnd) {
onLoadEnd(event);
}
this.setState({
viewState: 'IDLE',
});
this.updateNavigationState(event);
};
onMessage = (event: WebViewMessageEvent) => {
const { onMessage } = this.props;
if (onMessage) {
onMessage(event);
}
};
onLoadingProgress = (event: WebViewProgressEvent) => {
const { onLoadProgress } = this.props;
if (onLoadProgress) {
onLoadProgress(event);
}
};
onShouldStartLoadWithRequestCallback = (
shouldStart: boolean,
_url: string,
lockIdentifier: number,
) => {
let { viewManager }: WebViewNativeConfig = this.props.nativeConfig || {};
if (this.props.useWebKit) {
viewManager = viewManager || RNCWKWebViewManager;
} else {
viewManager = viewManager || RNCUIWebViewManager;
}
invariant(viewManager != null, 'viewManager expected to be non-null');
viewManager.startLoadWithResult(!!shouldStart, lockIdentifier);
};
componentDidUpdate(prevProps: IOSWebViewProps) {
if (!(prevProps.useWebKit && this.props.useWebKit)) {
return;
}
this.showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
this.showRedboxOnPropChanges(prevProps, 'incognito');
this.showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
this.showRedboxOnPropChanges(prevProps, 'dataDetectorTypes');
if (this.props.scalesPageToFit !== undefined) {
console.warn(
'The scalesPageToFit property is not supported when useWebKit = true',
);
}
}
showRedboxOnPropChanges(
prevProps: IOSWebViewProps,
propName: keyof IOSWebViewProps,
) {
if (this.props[propName] !== prevProps[propName]) {
console.error(
`Changes to property ${propName} do nothing after the initial render.`,
);
}
}
render() {
const {
decelerationRate: decelerationRateProp,
nativeConfig = {},
onMessage,
onShouldStartLoadWithRequest: onShouldStartLoadWithRequestProp,
originWhitelist,
renderError,
renderLoading,
scalesPageToFit = this.props.useWebKit ? undefined : true,
style,
useWebKit,
...otherProps
} = this.props;
let otherView = null;
if (this.state.viewState === 'LOADING') {
otherView = (renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === 'ERROR') {
const errorEvent = this.state.lastErrorEvent;
invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
otherView = (renderError || defaultRenderError)(
errorEvent.domain,
errorEvent.code,
errorEvent.description,
);
} else if (this.state.viewState !== 'IDLE') {
console.error(
`RNCWebView invalid state encountered: ${this.state.viewState}`,
);
}
const webViewStyles = [styles.container, styles.webView, style];
if (
this.state.viewState === 'LOADING'
|| this.state.viewState === 'ERROR'
) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
this.onShouldStartLoadWithRequestCallback,
// casting cause it's in the default props
originWhitelist as ReadonlyArray<string>,
onShouldStartLoadWithRequestProp,
);
const decelerationRate = processDecelerationRate(decelerationRateProp);
let NativeWebView = nativeConfig.component as typeof NativeWebViewIOS;
if (useWebKit) {
NativeWebView = NativeWebView || RNCWKWebView;
} else {
NativeWebView = NativeWebView || RNCUIWebView;
}
const webView = (
<NativeWebView
key="webViewKey"
{...otherProps}
decelerationRate={decelerationRate}
messagingEnabled={typeof onMessage === 'function'}
onLoadingError={this.onLoadingError}
onLoadingFinish={this.onLoadingFinish}
onLoadingProgress={this.onLoadingProgress}
onLoadingStart={this.onLoadingStart}
onMessage={this.onMessage}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
ref={this.webViewRef}
scalesPageToFit={scalesPageToFit}
// TODO: find a better way to type this.
source={resolveAssetSource(this.props.source as ImageSourcePropType)}
style={webViewStyles}
{...nativeConfig.props}
/>
);
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
}
}
export default WebView;

53
src/WebView.styles.ts Normal file
View File

@ -0,0 +1,53 @@
import { StyleSheet, ViewStyle, TextStyle } from 'react-native';
interface Styles {
container: ViewStyle;
errorContainer: ViewStyle;
errorText: TextStyle;
errorTextTitle: TextStyle;
hidden: ViewStyle;
loadingView: ViewStyle;
webView: ViewStyle;
loadingProgressBar: ViewStyle;
}
const BGWASH = 'rgba(255,255,255,0.8)';
const styles = StyleSheet.create<Styles>({
container: {
flex: 1,
},
errorContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: BGWASH,
},
hidden: {
height: 0,
flex: 0, // disable 'flex:1' when hiding a View
},
loadingView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
loadingProgressBar: {
height: 20,
},
errorText: {
fontSize: 14,
textAlign: 'center',
marginBottom: 2,
},
errorTextTitle: {
fontSize: 15,
fontWeight: '500',
marginBottom: 10,
},
webView: {
backgroundColor: '#ffffff',
},
});
export default styles;

5
src/WebView.tsx Normal file
View File

@ -0,0 +1,5 @@
// This files provides compatibility with out out tree platform.
import { WebView } from 'react-native';
export { WebView };
export default WebView;

View File

@ -1,39 +1,34 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
import escapeStringRegexp from 'escape-string-regexp';
import { Linking } from 'react-native';
import type {
import { Linking, UIManager as NotTypedUIManager } from 'react-native';
import {
WebViewNavigationEvent,
WebViewNavigation,
OnShouldStartLoadWithRequest,
CustomUIManager,
} from './WebViewTypes';
const UIManager = NotTypedUIManager as CustomUIManager;
const defaultOriginWhitelist = ['http://*', 'https://*'];
const extractOrigin = (url: string): string => {
const result = /^[A-Za-z][A-Za-z0-9\+\-\.]+:(\/\/)?[^/]*/.exec(url);
const result = /^[A-Za-z][A-Za-z0-9+\-.]+:(\/\/)?[^/]*/.exec(url);
return result === null ? '' : result[0];
};
const originWhitelistToRegex = (originWhitelist: string): string =>
`^${escapeStringRegexp(originWhitelist).replace(/\\\*/g, '.*')}`;
`^${escapeStringRegexp(originWhitelist).replace(/\\\*/g, '.*')}`;
const passesWhitelist = (compiledWhitelist: Array<string>, url: string) => {
const passesWhitelist = (
compiledWhitelist: ReadonlyArray<string>,
url: string,
) => {
const origin = extractOrigin(url);
return compiledWhitelist.some(x => new RegExp(x).test(origin));
};
const compileWhitelist = (
originWhitelist: ?$ReadOnlyArray<string>,
): Array<string> =>
originWhitelist: ReadonlyArray<string>,
): ReadonlyArray<string> =>
['about:blank', ...(originWhitelist || [])].map(originWhitelistToRegex);
const createOnShouldStartLoadWithRequest = (
@ -42,8 +37,8 @@ const createOnShouldStartLoadWithRequest = (
url: string,
lockIdentifier: number,
) => void,
originWhitelist: ?$ReadOnlyArray<string>,
onShouldStartLoadWithRequest: ?OnShouldStartLoadWithRequest,
originWhitelist: ReadonlyArray<string>,
onShouldStartLoadWithRequest?: OnShouldStartLoadWithRequest,
) => {
return ({ nativeEvent }: WebViewNavigationEvent) => {
let shouldStart = true;
@ -51,7 +46,7 @@ const createOnShouldStartLoadWithRequest = (
if (!passesWhitelist(compileWhitelist(originWhitelist), url)) {
Linking.openURL(url);
shouldStart = false
shouldStart = false;
}
if (onShouldStartLoadWithRequest) {
@ -62,4 +57,17 @@ const createOnShouldStartLoadWithRequest = (
};
};
export { defaultOriginWhitelist, createOnShouldStartLoadWithRequest };
const getViewManagerConfig = (
viewManagerName: 'RNCUIWebView' | 'RNCWKWebView' | 'RNCWebView',
) => {
if (!UIManager.getViewManagerConfig) {
return UIManager[viewManagerName];
}
return UIManager.getViewManagerConfig(viewManagerName);
};
export {
defaultOriginWhitelist,
createOnShouldStartLoadWithRequest,
getViewManagerConfig,
};

View File

@ -1,72 +1,135 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
/* eslint-disable react/no-multi-comp */
'use strict';
import { ReactElement, Component } from 'react';
import {
NativeSyntheticEvent,
ViewProps,
NativeMethodsMixin,
Constructor,
UIManagerStatic,
} from 'react-native';
import type { Node, Element, ComponentType } from 'react';
export interface WebViewCommands {
goForward: Function;
goBack: Function;
reload: Function;
stopLoading: Function;
postMessage: Function;
injectJavaScript: Function;
loadUrl: Function;
}
import type { SyntheticEvent } from 'CoreEventTypes';
import type { EdgeInsetsProp } from 'EdgeInsetsPropType';
import type { ViewStyleProp } from 'StyleSheet';
import type { ViewProps } from 'ViewPropTypes';
export interface CustomUIManager extends UIManagerStatic {
getViewManagerConfig?: (
name: string,
) => {
Commands: WebViewCommands;
};
dispatchViewManagerCommand: (
viewHandle: number,
command: Function,
params: object | null,
) => void;
RNCUIWebView: {
Commands: WebViewCommands;
};
RNCWKWebView: {
Commands: WebViewCommands;
};
RNCWebView: {
Commands: WebViewCommands;
};
}
export type WebViewNativeEvent = $ReadOnly<{|
url: string,
loading: boolean,
title: string,
canGoBack: boolean,
canGoForward: boolean,
lockIdentifier: number,
|}>;
type WebViewState = 'IDLE' | 'LOADING' | 'ERROR';
export type WebViewProgressEvent = $ReadOnly<{|
...WebViewNativeEvent,
progress: number,
|}>;
interface BaseState {
viewState: WebViewState;
}
export type WebViewNavigation = $ReadOnly<{|
...WebViewNativeEvent,
interface NormalState extends BaseState {
viewState: 'IDLE' | 'LOADING';
lastErrorEvent: WebViewError | null;
}
interface ErrorState extends BaseState {
viewState: 'ERROR';
lastErrorEvent: WebViewError;
}
export type State = NormalState | ErrorState;
// eslint-disable-next-line react/prefer-stateless-function
declare class NativeWebViewIOSComponent extends Component<
IOSNativeWebViewProps
> {}
declare const NativeWebViewIOSBase: Constructor<NativeMethodsMixin> &
typeof NativeWebViewIOSComponent;
export class NativeWebViewIOS extends NativeWebViewIOSBase {}
// eslint-disable-next-line react/prefer-stateless-function
declare class NativeWebViewAndroidComponent extends Component<
AndroidNativeWebViewProps
> {}
declare const NativeWebViewAndroidBase: Constructor<NativeMethodsMixin> &
typeof NativeWebViewAndroidComponent;
export class NativeWebViewAndroid extends NativeWebViewAndroidBase {}
export interface ContentInsetProp {
top?: number;
left?: number;
bottom?: number;
right?: number;
}
export interface WebViewNativeEvent {
url: string;
loading: boolean;
title: string;
canGoBack: boolean;
canGoForward: boolean;
lockIdentifier: number;
}
export interface WebViewProgressEvent extends WebViewNativeEvent {
progress: number;
}
export interface WebViewNavigation extends WebViewNativeEvent {
navigationType:
| 'click'
| 'formsubmit'
| 'backforward'
| 'reload'
| 'formresubmit'
| 'other',
|}>;
| 'other';
}
export type WebViewMessage = $ReadOnly<{|
...WebViewNativeEvent,
data: string,
|}>;
export type DecelerationRateConstant = 'normal' | 'fast';
export type WebViewError = $ReadOnly<{|
...WebViewNativeEvent,
export interface WebViewMessage extends WebViewNativeEvent {
data: string;
}
export interface WebViewError extends WebViewNativeEvent {
/**
* `domain` is only used on iOS
*/
domain: ?string,
code: number,
description: string,
|}>;
domain?: string;
code: number;
description: string;
}
export type WebViewEvent = SyntheticEvent<WebViewNativeEvent>;
export type WebViewEvent = NativeSyntheticEvent<WebViewNativeEvent>;
export type WebViewNavigationEvent = SyntheticEvent<WebViewNavigation>;
export type WebViewNavigationEvent = NativeSyntheticEvent<WebViewNavigation>;
export type WebViewMessageEvent = SyntheticEvent<WebViewMessage>;
export type WebViewMessageEvent = NativeSyntheticEvent<WebViewMessage>;
export type WebViewErrorEvent = SyntheticEvent<WebViewError>;
export type WebViewErrorEvent = NativeSyntheticEvent<WebViewError>;
export type DataDetectorTypes =
| 'phoneNumber'
export type DataDetectorTypes
= | 'phoneNumber'
| 'link'
| 'address'
| 'calendarEvent'
@ -78,23 +141,23 @@ export type DataDetectorTypes =
export type OverScrollModeType = 'always' | 'content' | 'never';
export type WebViewSourceUri = $ReadOnly<{|
export interface WebViewSourceUri {
/**
* The URI to load in the `WebView`. Can be a local or remote file.
*/
uri?: ?string,
uri: string;
/**
* The HTTP Method to use. Defaults to GET if not specified.
* NOTE: On Android, only GET and POST are supported.
*/
method?: string,
method?: string;
/**
* Additional HTTP headers to send with the request.
* NOTE: On Android, this can only be used with GET requests.
*/
headers?: Object,
headers?: Object;
/**
* The HTTP body to send with the request. This must be a valid
@ -102,56 +165,117 @@ export type WebViewSourceUri = $ReadOnly<{|
* additional encoding (e.g. URL-escaping or base64) applied.
* NOTE: On Android, this can only be used with POST requests.
*/
body?: string,
|}>;
body?: string;
}
export type WebViewSourceHtml = $ReadOnly<{|
export interface WebViewSourceHtml {
/**
* A static HTML page to display in the WebView.
*/
html?: ?string,
html: string;
/**
* The base URL to be used for any relative links in the HTML.
*/
baseUrl?: ?string,
|}>;
baseUrl: string;
}
export type WebViewSource = WebViewSourceUri | WebViewSourceHtml;
export type WebViewNativeConfig = $ReadOnly<{|
export interface ViewManager {
startLoadWithResult: Function;
}
export interface WebViewNativeConfig {
/**
* The native component used to render the WebView.
*/
component?: ComponentType<WebViewSharedProps>,
component?: typeof NativeWebViewIOS | typeof NativeWebViewAndroid;
/**
* Set props directly on the native component WebView. Enables custom props which the
* original WebView doesn't pass through.
*/
props?: ?Object,
props?: Object;
/**
* Set the ViewManager to use for communication with the native side.
* @platform ios
*/
viewManager?: ?Object,
|}>;
viewManager?: ViewManager;
}
export type OnShouldStartLoadWithRequest = (
event: WebViewNavigation,
) => boolean;
export type IOSWebViewProps = $ReadOnly<{|
export interface CommonNativeWebViewProps extends ViewProps {
cacheEnabled?: boolean;
injectedJavaScript?: string;
mediaPlaybackRequiresUserAction?: boolean;
messagingEnabled: boolean;
onLoadingError: (event: WebViewErrorEvent) => void;
onLoadingFinish: (event: WebViewNavigationEvent) => void;
onLoadingProgress: (event: WebViewProgressEvent) => void;
onLoadingStart: (event: WebViewNavigationEvent) => void;
onMessage: (event: WebViewMessageEvent) => void;
onShouldStartLoadWithRequest: (event: WebViewNavigationEvent) => void;
scalesPageToFit?: boolean;
showsHorizontalScrollIndicator?: boolean;
showsVerticalScrollIndicator?: boolean;
// TODO: find a better way to type this.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
source: any;
userAgent?: string;
}
export interface AndroidNativeWebViewProps extends CommonNativeWebViewProps {
allowFileAccess?: boolean;
allowUniversalAccessFromFileURLs?: boolean;
androidHardwareAccelerationDisabled?: boolean;
domStorageEnabled?: boolean;
geolocationEnabled?: boolean;
javaScriptEnabled?: boolean;
mixedContentMode?: 'never' | 'always' | 'compatibility';
onContentSizeChange?: (event: WebViewEvent) => void;
overScrollMode?: OverScrollModeType;
saveFormDataDisabled?: boolean;
thirdPartyCookiesEnabled?: boolean;
urlPrefixesForDefaultIntent?: ReadonlyArray<string>;
}
export interface IOSNativeWebViewProps extends CommonNativeWebViewProps {
allowsBackForwardNavigationGestures?: boolean;
allowsInlineMediaPlayback?: boolean;
allowsLinkPreview?: boolean;
automaticallyAdjustContentInsets?: boolean;
bounces?: boolean;
contentInset?: ContentInsetProp;
dataDetectorTypes?: DataDetectorTypes | ReadonlyArray<DataDetectorTypes>;
decelerationRate?: number;
directionalLockEnabled?: boolean;
hideKeyboardAccessoryView?: boolean;
incognito?: boolean;
pagingEnabled?: boolean;
scrollEnabled?: boolean;
useSharedProcessPool?: boolean;
}
export interface IOSWebViewProps extends WebViewSharedProps {
/**
* If true, use WKWebView instead of UIWebView.
* @platform ios
*/
useWebKit?: ?boolean,
useWebKit?: boolean;
/**
* Does not store any data within the lifetime of the WebView.
*/
incognito?: boolean;
/**
* Boolean value that determines whether the web view bounces
* when it reaches the edge of the content. The default value is `true`.
* @platform ios
*/
bounces?: ?boolean,
bounces?: boolean;
/**
* A floating-point number that determines how quickly the scroll view
@ -164,14 +288,14 @@ export type IOSWebViewProps = $ReadOnly<{|
* - fast: 0.99 (the default for iOS web view)
* @platform ios
*/
decelerationRate?: ?('fast' | 'normal' | number),
decelerationRate?: DecelerationRateConstant | number;
/**
* Boolean value that determines whether scrolling is enabled in the
* `WebView`. The default value is `true`.
* @platform ios
*/
scrollEnabled?: ?boolean,
scrollEnabled?: boolean;
/**
* If the value of this property is true, the scroll view stops on multiples
@ -179,14 +303,22 @@ export type IOSWebViewProps = $ReadOnly<{|
* The default value is false.
* @platform ios
*/
pagingEnabled?: ?boolean,
pagingEnabled?: boolean;
/**
* Controls whether to adjust the content inset for web views that are
* placed behind a navigation bar, tab bar, or toolbar. The default value
* is `true`.
* @platform ios
*/
automaticallyAdjustContentInsets?: boolean;
/**
* The amount by which the web view content is inset from the edges of
* the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}.
* @platform ios
*/
contentInset?: ?EdgeInsetsProp,
contentInset?: ContentInsetProp;
/**
* Determines the types of data converted to clickable URLs in the web view's content.
@ -210,7 +342,7 @@ export type IOSWebViewProps = $ReadOnly<{|
*
* @platform ios
*/
dataDetectorTypes?: ?DataDetectorTypes | $ReadOnlyArray<DataDetectorTypes>,
dataDetectorTypes?: DataDetectorTypes | ReadonlyArray<DataDetectorTypes>;
/**
* Boolean that determines whether HTML5 videos play inline or use the
@ -221,28 +353,28 @@ export type IOSWebViewProps = $ReadOnly<{|
* document must also include the `webkit-playsinline` attribute.
* @platform ios
*/
allowsInlineMediaPlayback?: ?boolean,
allowsInlineMediaPlayback?: boolean;
/**
* Hide the accessory view when the keyboard is open. Default is false to be
* backward compatible.
*/
hideKeyboardAccessoryView?: ?boolean,
hideKeyboardAccessoryView?: boolean;
/**
* A Boolean value indicating whether horizontal swipe gestures will trigger
* back-forward list navigations.
*/
allowsBackForwardNavigationGestures?: ?boolean,
allowsBackForwardNavigationGestures?: boolean;
/**
* A Boolean value indicating whether WebKit WebView should be created using a shared
* process pool, enabling WebViews to share cookies and localStorage between each other.
* Default is true but can be set to false for backwards compatibility.
* @platform ios
*/
useSharedProcessPool?: ?boolean,
useSharedProcessPool?: boolean;
/**
* The custom user agent string.
*/
userAgent?: ?string,
userAgent?: string;
/**
* A Boolean value that determines whether pressing on a link
@ -252,19 +384,19 @@ export type IOSWebViewProps = $ReadOnly<{|
* In iOS 10 and later, the default value is `true`; before that, the default value is `false`.
* @platform ios
*/
allowsLinkPreview?: ?boolean,
allowsLinkPreview?: boolean;
/**
* A Boolean value that determines whether scrolling is disabled in a particular direction.
* The default value is `true`.
* @platform ios
*/
directionalLockEnabled?: ?boolean,
|}>;
directionalLockEnabled?: boolean;
}
export type AndroidWebViewProps = $ReadOnly<{|
onNavigationStateChange?: (event: WebViewNavigation) => mixed,
onContentSizeChange?: (event: WebViewEvent) => mixed,
export interface AndroidWebViewProps extends WebViewSharedProps {
onNavigationStateChange?: (event: WebViewNavigation) => void;
onContentSizeChange?: (event: WebViewEvent) => void;
/**
* https://developer.android.com/reference/android/view/View#OVER_SCROLL_NEVER
@ -276,13 +408,13 @@ export type AndroidWebViewProps = $ReadOnly<{|
*
* @platform android
*/
overScrollMode?: ?OverScrollModeType,
overScrollMode?: OverScrollModeType;
/**
* Sets whether Geolocation is enabled. The default is false.
* @platform android
*/
geolocationEnabled?: ?boolean,
geolocationEnabled?: boolean;
/**
* Boolean that sets whether JavaScript running in the context of a file
@ -290,19 +422,19 @@ export type AndroidWebViewProps = $ReadOnly<{|
* Including accessing content from other file scheme URLs
* @platform android
*/
allowUniversalAccessFromFileURLs?: ?boolean,
allowUniversalAccessFromFileURLs?: boolean;
/**
* Sets whether the webview allow access to file system.
* @platform android
*/
allowFileAccess?: ?boolean,
allowFileAccess?: boolean;
/**
* Used on Android only, controls whether form autocomplete data should be saved
* @platform android
*/
saveFormDataDisabled?: ?boolean,
saveFormDataDisabled?: boolean;
/**
* Used on Android only, controls whether the given list of URL prefixes should
@ -311,21 +443,21 @@ export type AndroidWebViewProps = $ReadOnly<{|
* Use this to list URLs that WebView cannot handle, e.g. a PDF url.
* @platform android
*/
urlPrefixesForDefaultIntent?: $ReadOnlyArray<string>,
urlPrefixesForDefaultIntent?: ReadonlyArray<string>;
/**
* Boolean value to enable JavaScript in the `WebView`. Used on Android only
* as JavaScript is enabled by default on iOS. The default value is `true`.
* @platform android
*/
javaScriptEnabled?: ?boolean,
javaScriptEnabled?: boolean;
/**
* Boolean value to disable Hardware Acceleration in the `WebView`. Used on Android only
* as Hardware Acceleration is a feature only for Android. The default value is `false`.
* @platform android
*/
androidHardwareAccelerationDisabled?: ?boolean,
androidHardwareAccelerationDisabled?: boolean;
/**
* Boolean value to enable third party cookies in the `WebView`. Used on
@ -333,20 +465,20 @@ export type AndroidWebViewProps = $ReadOnly<{|
* default on Android Kitkat and below and on iOS. The default value is `true`.
* @platform android
*/
thirdPartyCookiesEnabled?: ?boolean,
thirdPartyCookiesEnabled?: boolean;
/**
* Boolean value to control whether DOM Storage is enabled. Used only in
* Android.
* @platform android
*/
domStorageEnabled?: ?boolean,
domStorageEnabled?: boolean;
/**
* Sets the user-agent for the `WebView`.
* @platform android
*/
userAgent?: ?string,
userAgent?: string;
/**
* Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.
@ -358,77 +490,53 @@ export type AndroidWebViewProps = $ReadOnly<{|
* - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.
* @platform android
*/
mixedContentMode?: ?('never' | 'always' | 'compatibility'),
|}>;
export type WebViewSharedProps = $ReadOnly<{|
...ViewProps,
...IOSWebViewProps,
...AndroidWebViewProps,
/**
* Deprecated. Use `source` instead.
*/
url?: ?string,
/**
* Deprecated. Use `source` instead.
*/
html?: ?string,
mixedContentMode?: 'never' | 'always' | 'compatibility';
}
export interface WebViewSharedProps extends ViewProps {
/**
* Loads static html or a uri (with optional headers) in the WebView.
*/
source?: ?WebViewSource,
/**
* Does not store any data within the lifetime of the WebView.
*/
incognito?: ?boolean,
source?: WebViewSource;
/**
* Function that returns a view to show if there's an error.
*/
renderError: (
errorDomain: ?string,
renderError?: (
errorDomain: string | undefined,
errorCode: number,
errorDesc: string,
) => Element<any>, // view to show if there's an error
) => ReactElement; // view to show if there's an error
/**
* Function that returns a loading indicator.
*/
renderLoading: () => Element<any>,
renderLoading?: () => ReactElement;
/**
* Function that is invoked when the `WebView` has finished loading.
*/
onLoad: (event: WebViewNavigationEvent) => mixed,
onLoad?: (event: WebViewNavigationEvent) => void;
/**
* Function that is invoked when the `WebView` load succeeds or fails.
*/
onLoadEnd: (event: WebViewNavigationEvent | WebViewErrorEvent) => mixed,
onLoadEnd?: (event: WebViewNavigationEvent | WebViewErrorEvent) => void;
/**
* Function that is invoked when the `WebView` starts loading.
*/
onLoadStart: (event: WebViewNavigationEvent) => mixed,
onLoadStart?: (event: WebViewNavigationEvent) => void;
/**
* Function that is invoked when the `WebView` load fails.
*/
onError: (event: WebViewErrorEvent) => mixed,
/**
* Controls whether to adjust the content inset for web views that are
* placed behind a navigation bar, tab bar, or toolbar. The default value
* is `true`.
*/
automaticallyAdjustContentInsets?: ?boolean,
onError?: (event: WebViewErrorEvent) => void;
/**
* Function that is invoked when the `WebView` loading starts or ends.
*/
onNavigationStateChange?: (event: WebViewNavigation) => mixed,
onNavigationStateChange?: (event: WebViewNavigation) => void;
/**
* Function that is invoked when the webview calls `window.ReactNativeWebView.postMessage`.
@ -437,36 +545,36 @@ export type WebViewSharedProps = $ReadOnly<{|
* `window.ReactNativeWebView.postMessage` accepts one argument, `data`, which will be
* available on the event object, `event.nativeEvent.data`. `data` must be a string.
*/
onMessage?: (event: WebViewMessageEvent) => mixed,
onMessage?: (event: WebViewMessageEvent) => void;
/**
* Function that is invoked when the `WebView` is loading.
*/
onLoadProgress?: (event: WebViewProgressEvent) => mixed,
onLoadProgress?: (event: WebViewProgressEvent) => void;
/**
* Boolean value that forces the `WebView` to show the loading view
* on the first load.
*/
startInLoadingState?: ?boolean,
startInLoadingState?: boolean;
/**
* Set this to provide JavaScript that will be injected into the web page
* when the view loads.
*/
injectedJavaScript?: ?string,
injectedJavaScript?: string;
/**
* Boolean value that determines whether a horizontal scroll indicator is
* shown in the `WebView`. The default value is `true`.
*/
showsHorizontalScrollIndicator?: ?boolean,
showsHorizontalScrollIndicator?: boolean;
/**
* Boolean value that determines whether a vertical scroll indicator is
* shown in the `WebView`. The default value is `true`.
*/
showsVerticalScrollIndicator?: ?boolean,
showsVerticalScrollIndicator?: boolean;
/**
* Boolean that controls whether the web content is scaled to fit
@ -475,13 +583,13 @@ export type WebViewSharedProps = $ReadOnly<{|
*
* On iOS, when `useWebKit=true`, this prop will not work.
*/
scalesPageToFit?: ?boolean,
scalesPageToFit?: boolean;
/**
* Boolean that determines whether HTML5 audio and video requires the user
* to tap them before they start playing. The default value is `true`.
*/
mediaPlaybackRequiresUserAction?: ?boolean,
mediaPlaybackRequiresUserAction?: boolean;
/**
* List of origin strings to allow being navigated to. The strings allow
@ -490,26 +598,23 @@ export type WebViewSharedProps = $ReadOnly<{|
* this whitelist, we will open the URL in Safari.
* The default whitelisted origins are "http://*" and "https://*".
*/
originWhitelist?: $ReadOnlyArray<string>,
originWhitelist?: ReadonlyArray<string>;
/**
* Function that allows custom handling of any web view requests. Return
* `true` from the function to continue loading the request and `false`
* to stop loading. The `navigationType` is always `other` on android.
*/
onShouldStartLoadWithRequest?: OnShouldStartLoadWithRequest,
onShouldStartLoadWithRequest?: OnShouldStartLoadWithRequest;
/**
* Override the native component used to render the WebView. Enables a custom native
* WebView which uses the same JavaScript as the original WebView.
*/
nativeConfig?: ?WebViewNativeConfig,
nativeConfig?: WebViewNativeConfig;
/**
* Should caching be enabled. Default is true.
*/
cacheEnabled?: ?boolean,
style?: ViewStyleProp,
children: Node,
|}>;
cacheEnabled?: boolean;
}

24
tsconfig.json Normal file
View File

@ -0,0 +1,24 @@
{
"include": ["src/*"],
"compilerOptions": {
"baseUrl": "./src/",
"jsx": "react-native",
"module": "esnext",
"moduleResolution": "node",
"lib": ["es2017"],
"declaration": true,
"declarationMap": true,
"outDir": "lib",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true
}
}

483
typings/index.d.ts vendored
View File

@ -1,483 +0,0 @@
import { ComponentType, ReactElement, ReactNode, Component } from 'react';
import { Insets, NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from 'react-native';
export interface WebViewNativeEvent {
readonly url: string;
readonly loading: boolean;
readonly title: string;
readonly canGoBack: boolean;
readonly canGoForward: boolean;
}
export interface WebViewIOSLoadRequestEvent extends WebViewNativeEvent {
target: number;
lockIdentifier: number;
navigationType: "click" | "formsubmit" | "backforward" | "reload" | "formresubmit" | "other";
}
export interface WebViewProgressEvent extends WebViewNativeEvent {
readonly progress: number;
}
export interface WebViewNavigation extends WebViewNativeEvent {
readonly navigationType:
| 'click'
| 'formsubmit'
| 'backforward'
| 'reload'
| 'formresubmit'
| 'other';
}
export interface WebViewMessage extends WebViewNativeEvent {
readonly data: string;
}
export interface WebViewError extends WebViewNativeEvent {
readonly domain?: string;
readonly code: number;
readonly description: string;
}
export type WebViewEvent = NativeSyntheticEvent<WebViewNativeEvent>;
export type WebViewNavigationEvent = NativeSyntheticEvent<WebViewNavigation>;
export type WebViewMessageEvent = NativeSyntheticEvent<WebViewMessage>;
export type WebViewErrorEvent = NativeSyntheticEvent<WebViewError>;
export type DataDetectorTypes =
| 'phoneNumber'
| 'link'
| 'address'
| 'calendarEvent'
| 'trackingNumber'
| 'flightNumber'
| 'lookupSuggestion'
| 'none'
| 'all';
export type OverScrollModeType = 'always' | 'content' | 'never';
export interface WebViewSourceUri {
/**
* The URI to load in the `WebView`. Can be a local or remote file.
*/
uri?: string;
/**
* The HTTP Method to use. Defaults to GET if not specified.
* NOTE: On Android, only GET and POST are supported.
*/
method?: string;
/**
* Additional HTTP headers to send with the request.
* NOTE: On Android, this can only be used with GET requests.
*/
headers?: {[key: string]: string};
/**
* The HTTP body to send with the request. This must be a valid
* UTF-8 string, and will be sent exactly as specified, with no
* additional encoding (e.g. URL-escaping or base64) applied.
* NOTE: On Android, this can only be used with POST requests.
*/
body?: string;
}
export interface WebViewSourceHtml {
/**
* A static HTML page to display in the WebView.
*/
html?: string;
/**
* The base URL to be used for any relative links in the HTML.
*/
baseUrl?: string;
}
export type WebViewSource = WebViewSourceUri | WebViewSourceHtml;
export interface WebViewNativeConfig {
/*
* The native component used to render the WebView.
*/
component?: ComponentType<WebViewSharedProps>;
/*
* Set props directly on the native component WebView. Enables custom props which the
* original WebView doesn't pass through.
*/
props?: any;
/*
* Set the ViewManager to use for communication with the native side.
* @platform ios
*/
viewManager?: any;
}
export interface IOSWebViewProps {
/**
* If true, use WKWebView instead of UIWebView.
* @platform ios
*/
useWebKit?: boolean;
/**
* Boolean value that determines whether the web view bounces
* when it reaches the edge of the content. The default value is `true`.
* @platform ios
*/
bounces?: boolean;
/**
* A floating-point number that determines how quickly the scroll view
* decelerates after the user lifts their finger. You may also use the
* string shortcuts `"normal"` and `"fast"` which match the underlying iOS
* settings for `UIScrollViewDecelerationRateNormal` and
* `UIScrollViewDecelerationRateFast` respectively:
*
* - normal: 0.998
* - fast: 0.99 (the default for iOS web view)
* @platform ios
*/
decelerationRate?: 'fast' | 'normal' | number;
/**
* Boolean value that determines whether scrolling is enabled in the
* `WebView`. The default value is `true`.
* @platform ios
*/
scrollEnabled?: boolean;
/**
* A Boolean value that determines whether scrolling is disabled in a particular direction.
* The default value is `true`.
* @platform ios
*/
directionalLockEnabled?: boolean;
/**
* If the value of this property is true, the scroll view stops on multiples
* of the scroll views bounds when the user scrolls.
* The default value is false.
* @platform ios
*/
pagingEnabled?: boolean,
/**
* The amount by which the web view content is inset from the edges of
* the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}.
* @platform ios
*/
contentInset?: Insets;
/**
* Determines the types of data converted to clickable URLs in the web view's content.
* By default only phone numbers are detected.
*
* You can provide one type or an array of many types.
*
* Possible values for `dataDetectorTypes` are:
*
* - `'phoneNumber'`
* - `'link'`
* - `'address'`
* - `'calendarEvent'`
* - `'none'`
* - `'all'`
*
* With the new WebKit implementation, we have three new values:
* - `'trackingNumber'`,
* - `'flightNumber'`,
* - `'lookupSuggestion'`,
*
* @platform ios
*/
dataDetectorTypes?: DataDetectorTypes | DataDetectorTypes[];
/**
* Function that allows custom handling of any web view requests. Return
* `true` from the function to continue loading the request and `false`
* to stop loading.
* @platform ios
*/
onShouldStartLoadWithRequest?: (event: WebViewIOSLoadRequestEvent) => any;
/**
* Boolean that determines whether HTML5 videos play inline or use the
* native full-screen controller. The default value is `false`.
*
* **NOTE** : In order for video to play inline, not only does this
* property need to be set to `true`, but the video element in the HTML
* document must also include the `webkit-playsinline` attribute.
* @platform ios
*/
allowsInlineMediaPlayback?: boolean;
/**
* Hide the accessory view when the keyboard is open. Default is false to be
* backward compatible.
*/
hideKeyboardAccessoryView?: boolean;
/**
* If true, this will be able horizontal swipe gestures when using the WKWebView. The default value is `false`.
*/
allowsBackForwardNavigationGestures?: boolean;
/**
* A Boolean value that determines whether pressing on a link
* displays a preview of the destination for the link.
*
* This property is available on devices that support 3D Touch.
* In iOS 10 and later, the default value is `true`; before that, the default value is `false`.
* @platform ios
*/
allowsLinkPreview?: boolean;
}
export interface AndroidWebViewProps {
onNavigationStateChange?: (event: WebViewNavigation) => any;
onContentSizeChange?: (event: WebViewEvent) => any;
/**
* https://developer.android.com/reference/android/view/View#OVER_SCROLL_NEVER
* Sets the overScrollMode. Possible values are:
*
* - `'always'` (default)
* - `'content'`
* - `'never'`
*
* @platform android
*/
overScrollMode?: OverScrollModeType;
/**
* Sets whether Geolocation is enabled. The default is false.
* @platform android
*/
geolocationEnabled?: boolean;
/**
* Boolean that sets whether JavaScript running in the context of a file
* scheme URL should be allowed to access content from any origin.
* Including accessing content from other file scheme URLs
* @platform android
*/
allowUniversalAccessFromFileURLs?: boolean;
/**
* Sets whether the webview allow access to file system.
* @platform android
*/
allowFileAccess?: boolean;
/**
* Used on Android only, controls whether form autocomplete data should be saved
* @platform android
*/
saveFormDataDisabled?: boolean;
/*
* Used on Android only, controls whether the given list of URL prefixes should
* make {@link com.facebook.react.views.webview.ReactWebViewClient} to launch a
* default activity intent for those URL instead of loading it within the webview.
* Use this to list URLs that WebView cannot handle, e.g. a PDF url.
* @platform android
*/
urlPrefixesForDefaultIntent?: string[];
/**
* Boolean value to enable JavaScript in the `WebView`. Used on Android only
* as JavaScript is enabled by default on iOS. The default value is `true`.
* @platform android
*/
javaScriptEnabled?: boolean;
/**
* Boolean value to disable Hardware Acceleration in the `WebView`. Used on Android only
* as Hardware Acceleration is a feature only for Android. The default value is `false`.
* @platform android
*/
androidHardwareAccelerationDisabled?: boolean;
/**
* Boolean value to enable third party cookies in the `WebView`. Used on
* Android Lollipop and above only as third party cookies are enabled by
* default on Android Kitkat and below and on iOS. The default value is `true`.
* @platform android
*/
thirdPartyCookiesEnabled?: boolean;
/**
* Boolean value to control whether DOM Storage is enabled. Used only in
* Android.
* @platform android
*/
domStorageEnabled?: boolean;
/**
* Sets the user-agent for the `WebView`.
* @platform android
*/
userAgent?: string;
/**
* Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.
*
* Possible values for `mixedContentMode` are:
*
* - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin.
* - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
* - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.
* @platform android
*/
mixedContentMode?: 'never' | 'always' | 'compatibility';
}
export interface WebViewSharedProps extends ViewProps, IOSWebViewProps, AndroidWebViewProps {
/**
* @Deprecated. Use `source` instead.
*/
url?: string;
/**
* @Deprecated. Use `source` instead.
*/
html?: string;
/**
* Loads static html or a uri (with optional headers) in the WebView.
*/
source?: WebViewSource;
/**
* Function that returns a view to show if there's an error.
*/
renderError?: (errorDomain: string | undefined, errorCode: number, errorDesc: string) => ReactElement<any>; // view to show if there's an error
/**
* Function that returns a loading indicator.
*/
renderLoading?: () => ReactElement<any>;
/**
* Function that is invoked when the `WebView` has finished loading.
*/
onLoad?: (event: WebViewNavigationEvent) => any;
/**
* Function that is invoked when the `WebView` load succeeds or fails.
*/
onLoadEnd?: (event: WebViewNavigationEvent | WebViewErrorEvent) => any;
/**
* Function that is invoked when the `WebView` starts loading.
*/
onLoadStart?: (event: WebViewNavigationEvent) => any;
/**
* Function that is invoked when the `WebView` load fails.
*/
onError?: (event: WebViewErrorEvent) => any;
/**
* Controls whether to adjust the content inset for web views that are
* placed behind a navigation bar, tab bar, or toolbar. The default value
* is `true`.
*/
automaticallyAdjustContentInsets?: boolean;
/**
* Function that is invoked when the `WebView` loading starts or ends.
*/
onNavigationStateChange?: (event: WebViewNavigation) => any;
/**
* A function that is invoked when the webview calls `window.postMessage`.
* Setting this property will inject a `postMessage` global into your
* webview, but will still call pre-existing values of `postMessage`.
*
* `window.postMessage` accepts one argument, `data`, which will be
* available on the event object, `event.nativeEvent.data`. `data`
* must be a string.
*/
onMessage?: (event: WebViewMessageEvent) => any;
/**
* Function that is invoked when the `WebView` is loading.
*/
onLoadProgress?: (event: NativeSyntheticEvent<WebViewProgressEvent>) => any;
/**
* Boolean value that forces the `WebView` to show the loading view
* on the first load.
*/
startInLoadingState?: boolean;
/**
* Set this to provide JavaScript that will be injected into the web page
* when the view loads.
*/
injectedJavaScript?: string;
/**
* Boolean that controls whether the web content is scaled to fit
* the view and enables the user to change the scale. The default value
* is `true`.
*
* On iOS, when `useWebKit=true`, this prop will not work.
*/
scalesPageToFit?: boolean;
/**
* Boolean that determines whether HTML5 audio and video requires the user
* to tap them before they start playing. The default value is `true`.
*/
mediaPlaybackRequiresUserAction?: boolean;
/**
* List of origin strings to allow being navigated to. The strings allow
* wildcards and get matched against *just* the origin (not the full URL).
* If the user taps to navigate to a new page but the new page is not in
* this whitelist, we will open the URL in Safari.
* The default whitelisted origins are "http://*" and "https://*".
*/
originWhitelist?: string[];
/**
* Boolean value that determines whether caching is enabled in the
* `WebView`. The default value is `true` - i.e. caching is *enabled by default*
*/
cacheEnabled?: boolean,
/**
* Override the native component used to render the WebView. Enables a custom native
* WebView which uses the same JavaScript as the original WebView.
*/
nativeConfig?: WebViewNativeConfig;
/**
* A Boolean value that controls whether the horizontal scroll indicator is visible
* The default value is `true`.
*/
showsHorizontalScrollIndicator?: boolean;
/**
* A Boolean value that controls whether the vertical scroll indicator is visible
* The default value is `true`
*/
showsVerticalScrollIndicator?: boolean;
style?: StyleProp<ViewStyle>;
children?: ReactNode;
}
export class WebView extends Component<WebViewSharedProps> {
static isFileUploadSupported: () => Promise<boolean>;
public goForward: () => void;
public goBack: () => void;
public reload: () => void;
public stopLoading: () => void;
public postMessage: (msg: string) => void;
public injectJavaScript: (js: string) => void;
}

1985
yarn.lock

File diff suppressed because it is too large Load Diff