説明なし

index.android.js 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. 'use strict';
  2. import React, { PureComponent } from 'react';
  3. import {
  4. findNodeHandle,
  5. requireNativeComponent,
  6. Animated,
  7. DeviceEventEmitter,
  8. Dimensions,
  9. StyleSheet,
  10. Platform,
  11. UIManager,
  12. ViewPropTypes,
  13. WebView
  14. } from 'react-native';
  15. import PropTypes from 'prop-types';
  16. import Immutable from 'immutable';
  17. import { getScript, onHeightUpdated, DomMutationObserveScript } from './common.js';
  18. const RCTAutoHeightWebView = requireNativeComponent('RCTAutoHeightWebView', AutoHeightWebView, {
  19. nativeOnly: {
  20. nativeOnly: {
  21. onLoadingStart: true,
  22. onLoadingError: true,
  23. onLoadingFinish: true,
  24. messagingEnabled: PropTypes.bool
  25. }
  26. }
  27. });
  28. export default class AutoHeightWebView extends PureComponent {
  29. static propTypes = {
  30. source: WebView.propTypes.source,
  31. onHeightUpdated: PropTypes.func,
  32. customScript: PropTypes.string,
  33. customStyle: PropTypes.string,
  34. enableAnimation: PropTypes.bool,
  35. // if set to false may cause some layout issues (width of container will be than width of screen)
  36. scalesPageToFit: PropTypes.bool,
  37. // only works on enable animation
  38. animationDuration: PropTypes.number,
  39. // offset of rn webView margin
  40. heightOffset: PropTypes.number,
  41. // baseUrl not work in android 4.3 or below version
  42. enableBaseUrl: PropTypes.bool,
  43. style: ViewPropTypes.style,
  44. // rn WebView callback
  45. onError: PropTypes.func,
  46. onLoad: PropTypes.func,
  47. onLoadStart: PropTypes.func,
  48. onLoadEnd: PropTypes.func,
  49. // works if set enableBaseUrl to true; add web/files... to android/app/src/assets/
  50. files: PropTypes.arrayOf(
  51. PropTypes.shape({
  52. href: PropTypes.string,
  53. type: PropTypes.string,
  54. rel: PropTypes.string
  55. })
  56. )
  57. };
  58. static defaultProps = {
  59. scalesPageToFit: true,
  60. enableBaseUrl: false,
  61. enableAnimation: true,
  62. animationDuration: 555,
  63. heightOffset: 20
  64. };
  65. constructor(props) {
  66. super(props);
  67. props.enableAnimation && (this.opacityAnimatedValue = new Animated.Value(0));
  68. this.state = {
  69. isChangingSource: false,
  70. height: 0,
  71. heightOffset: 0,
  72. script: getScript(props, BaseScript)
  73. };
  74. }
  75. componentWillMount() {
  76. IsBelowKitKat && DeviceEventEmitter.addListener('webViewBridgeMessage', this.listenWebViewBridgeMessage);
  77. }
  78. componentDidMount() {
  79. this.startInterval();
  80. }
  81. componentWillReceiveProps(nextProps) {
  82. // injectedJavaScript only works when webView reload (source changed)
  83. if (Immutable.is(Immutable.fromJS(this.props.source), Immutable.fromJS(nextProps.source))) {
  84. return;
  85. } else {
  86. this.setState(
  87. {
  88. isChangingSource: true,
  89. height: 0,
  90. heightOffset: 0
  91. },
  92. () => {
  93. this.startInterval();
  94. this.setState({ isChangingSource: false });
  95. }
  96. );
  97. }
  98. this.setState({ script: getScript(nextProps, BaseScript) });
  99. }
  100. componentWillUnmount() {
  101. this.stopInterval();
  102. IsBelowKitKat && DeviceEventEmitter.removeListener('webViewBridgeMessage', this.listenWebViewBridgeMessage);
  103. }
  104. // below kitkat
  105. listenWebViewBridgeMessage = body => this.onMessage(body.message);
  106. // below kitkat
  107. sendToWebView(message) {
  108. UIManager.dispatchViewManagerCommand(
  109. findNodeHandle(this.webView),
  110. UIManager.RCTAutoHeightWebView.Commands.sendToWebView,
  111. [String(message)]
  112. );
  113. }
  114. postMessage(data) {
  115. UIManager.dispatchViewManagerCommand(
  116. findNodeHandle(this.webView),
  117. UIManager.RCTAutoHeightWebView.Commands.postMessage,
  118. [String(data)]
  119. );
  120. }
  121. startInterval() {
  122. this.finishInterval = false;
  123. this.interval = setInterval(() => {
  124. if (!this.finishInterval) {
  125. IsBelowKitKat ? this.sendToWebView('getBodyHeight') : this.postMessage('getBodyHeight');
  126. }
  127. }, 205);
  128. }
  129. stopInterval() {
  130. this.finishInterval = true;
  131. clearInterval(this.interval);
  132. }
  133. onMessage = e => {
  134. const height = parseInt(IsBelowKitKat ? e.nativeEvent.message : e.nativeEvent.data);
  135. if (height) {
  136. const { enableAnimation, animationDuration, heightOffset } = this.props;
  137. if (enableAnimation) {
  138. this.opacityAnimatedValue.setValue(0);
  139. }
  140. this.stopInterval();
  141. this.setState(
  142. {
  143. heightOffset,
  144. height
  145. },
  146. () => {
  147. if (enableAnimation) {
  148. Animated.timing(this.opacityAnimatedValue, {
  149. toValue: 1,
  150. duration: animationDuration
  151. }).start(() => onHeightUpdated(height, this.props));
  152. } else {
  153. onHeightUpdated(height, this.props);
  154. }
  155. }
  156. );
  157. }
  158. };
  159. onLoadingStart = event => {
  160. const { onLoadStart } = this.props;
  161. onLoadStart && onLoadStart(event);
  162. };
  163. onLoadingError = event => {
  164. const { onError, onLoadEnd } = this.props;
  165. onError && onError(event);
  166. onLoadEnd && onLoadEnd(event);
  167. console.warn('Encountered an error loading page', event.nativeEvent);
  168. };
  169. onLoadingFinish = event => {
  170. const { onLoad, onLoadEnd } = this.props;
  171. onLoad && onLoad(event);
  172. onLoadEnd && onLoadEnd(event);
  173. };
  174. getWebView = webView => (this.webView = webView);
  175. stopLoading() {
  176. UIManager.dispatchViewManagerCommand(
  177. findNodeHandle(this.webView),
  178. UIManager.RCTAutoHeightWebView.Commands.stopLoading,
  179. null
  180. );
  181. }
  182. render() {
  183. const { height, script, isChangingSource, heightOffset } = this.state;
  184. const { scalesPageToFit, enableAnimation, source, customScript, style, enableBaseUrl } = this.props;
  185. let webViewSource = source;
  186. if (enableBaseUrl) {
  187. webViewSource = Object.assign({}, source, {
  188. baseUrl: 'file:///android_asset/web/'
  189. });
  190. }
  191. return (
  192. <Animated.View
  193. style={[
  194. Styles.container,
  195. {
  196. opacity: enableAnimation ? this.opacityAnimatedValue : 1,
  197. height: height + heightOffset
  198. },
  199. style
  200. ]}
  201. >
  202. {isChangingSource ? null : (
  203. <RCTAutoHeightWebView
  204. onLoadingStart={this.onLoadingStart}
  205. onLoadingFinish={this.onLoadingFinish}
  206. onLoadingError={this.onLoadingError}
  207. ref={this.getWebView}
  208. style={Styles.webView}
  209. javaScriptEnabled={true}
  210. injectedJavaScript={script + customScript}
  211. scalesPageToFit={scalesPageToFit}
  212. source={webViewSource}
  213. onMessage={this.onMessage}
  214. messagingEnabled={true}
  215. // below kitkat
  216. onChange={this.onMessage}
  217. />
  218. )}
  219. </Animated.View>
  220. );
  221. }
  222. }
  223. const ScreenWidth = Dimensions.get('window').width;
  224. const IsBelowKitKat = Platform.Version < 19;
  225. const Styles = StyleSheet.create({
  226. container: {
  227. width: ScreenWidth,
  228. backgroundColor: 'transparent'
  229. },
  230. webView: {
  231. flex: 1,
  232. backgroundColor: 'transparent'
  233. }
  234. });
  235. const BaseScript = IsBelowKitKat
  236. ? `
  237. ; (function () {
  238. AutoHeightWebView.onMessage = function (message) {
  239. AutoHeightWebView.send(String(document.body.offsetHeight));
  240. };
  241. ${DomMutationObserveScript}
  242. } ());
  243. `
  244. : `
  245. ; (function () {
  246. document.addEventListener('message', function (e) {
  247. window.postMessage(String(document.body.offsetHeight));
  248. });
  249. ${DomMutationObserveScript}
  250. } ());
  251. `;