Nessuna descrizione

index.android.js 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. View,
  13. ViewPropTypes,
  14. WebView
  15. } from "react-native";
  16. import PropTypes from "prop-types";
  17. import Immutable from "immutable";
  18. const RCTAutoHeightWebView = requireNativeComponent(
  19. "RCTAutoHeightWebView",
  20. AutoHeightWebView,
  21. { nativeOnly: { messagingEnabled: PropTypes.bool } }
  22. );
  23. export default class AutoHeightWebView extends PureComponent {
  24. static propTypes = {
  25. source: WebView.propTypes.source,
  26. onHeightUpdated: PropTypes.func,
  27. customScript: PropTypes.string,
  28. customStyle: PropTypes.string,
  29. enableAnimation: PropTypes.bool,
  30. // if set to false may cause some layout issues (width of container will be than width of screen)
  31. scalesPageToFit: PropTypes.bool,
  32. // only works on enable animation
  33. animationDuration: PropTypes.number,
  34. // offset of rn webview margin
  35. heightOffset: PropTypes.number,
  36. // baseUrl not work in android 4.3 or below version
  37. enableBaseUrl: PropTypes.bool,
  38. style: ViewPropTypes.style,
  39. // works if set enableBaseUrl to true; add web/files... to android/app/src/assets/
  40. files: PropTypes.arrayOf(
  41. PropTypes.shape({
  42. href: PropTypes.string,
  43. type: PropTypes.string,
  44. rel: PropTypes.string
  45. })
  46. )
  47. };
  48. static defaultProps = {
  49. scalesPageToFit: true,
  50. enableBaseUrl: false,
  51. enableAnimation: true,
  52. animationDuration: 555,
  53. heightOffset: 20
  54. };
  55. constructor(props) {
  56. super(props);
  57. this.onMessage = this.onMessage.bind(this);
  58. if (this.props.enableAnimation) {
  59. this.opacityAnimatedValue = new Animated.Value(0);
  60. }
  61. if (IsBelowKitKat) {
  62. this.listenWebViewBridgeMessage = this.listenWebViewBridgeMessage.bind(
  63. this
  64. );
  65. }
  66. let initialScript = props.files
  67. ? this.appendFilesToHead(props.files, BaseScript)
  68. : BaseScript;
  69. initialScript = props.customStyle
  70. ? this.appendStylesToHead(props.customStyle, initialScript)
  71. : initialScript;
  72. this.state = {
  73. isChangingSource: false,
  74. height: 0,
  75. heightOffset: 0,
  76. script: initialScript
  77. };
  78. }
  79. componentWillMount() {
  80. if (IsBelowKitKat) {
  81. DeviceEventEmitter.addListener(
  82. "webViewBridgeMessage",
  83. this.listenWebViewBridgeMessage
  84. );
  85. }
  86. }
  87. componentDidMount() {
  88. this.startInterval();
  89. }
  90. componentWillReceiveProps(nextProps) {
  91. // injectedJavaScript only works when webview reload (source changed)
  92. if (
  93. Immutable.is(
  94. Immutable.fromJS(this.props.source),
  95. Immutable.fromJS(nextProps.source)
  96. )
  97. ) {
  98. return;
  99. } else {
  100. this.setState(
  101. {
  102. isChangingSource: true,
  103. height: 0,
  104. heightOffset: 0
  105. },
  106. () => {
  107. this.startInterval();
  108. this.setState({ isChangingSource: false });
  109. }
  110. );
  111. }
  112. let currentScript = BaseScript;
  113. if (nextProps.files) {
  114. currentScript = this.appendFilesToHead(nextProps.files, BaseScript);
  115. }
  116. currentScript = nextProps.customStyle
  117. ? this.appendStylesToHead(nextProps.customStyle, currentScript)
  118. : currentScript;
  119. this.setState({ script: currentScript });
  120. }
  121. componentWillUnmount() {
  122. this.stopInterval();
  123. if (IsBelowKitKat) {
  124. DeviceEventEmitter.removeListener(
  125. "webViewBridgeMessage",
  126. this.listenWebViewBridgeMessage
  127. );
  128. }
  129. }
  130. // below kitkat
  131. listenWebViewBridgeMessage(body) {
  132. this.onMessage(body.message);
  133. }
  134. // below kitkat
  135. sendToWebView(message) {
  136. UIManager.dispatchViewManagerCommand(
  137. findNodeHandle(this.webview),
  138. UIManager.RCTAutoHeightWebView.Commands.sendToWebView,
  139. [String(message)]
  140. );
  141. }
  142. postMessage(data) {
  143. UIManager.dispatchViewManagerCommand(
  144. findNodeHandle(this.webview),
  145. UIManager.RCTAutoHeightWebView.Commands.postMessage,
  146. [String(data)]
  147. );
  148. }
  149. startInterval() {
  150. this.finishInterval = false;
  151. this.interval = setInterval(() => {
  152. if (!this.finishInterval) {
  153. IsBelowKitKat
  154. ? this.sendToWebView("getBodyHeight")
  155. : this.postMessage("getBodyHeight");
  156. }
  157. }, 205);
  158. }
  159. stopInterval() {
  160. this.finishInterval = true;
  161. clearInterval(this.interval);
  162. }
  163. onHeightUpdated(height) {
  164. if (this.props.onHeightUpdated) {
  165. this.props.onHeightUpdated(height);
  166. }
  167. }
  168. onMessage(e) {
  169. const height = parseInt(
  170. IsBelowKitKat ? e.nativeEvent.message : e.nativeEvent.data
  171. );
  172. if (height) {
  173. if (this.props.enableAnimation) {
  174. this.opacityAnimatedValue.setValue(0);
  175. }
  176. this.stopInterval();
  177. this.setState(
  178. {
  179. heightOffset: this.props.heightOffset,
  180. height
  181. },
  182. () => {
  183. if (this.props.enableAnimation) {
  184. Animated.timing(this.opacityAnimatedValue, {
  185. toValue: 1,
  186. duration: this.props.animationDuration
  187. }).start(() => this.onHeightUpdated(height));
  188. } else {
  189. this.onHeightUpdated(height);
  190. }
  191. }
  192. );
  193. }
  194. }
  195. appendFilesToHead(files, script) {
  196. if (!files) {
  197. return script;
  198. }
  199. return files.reduceRight((file, combinedScript) => `
  200. var link = document.createElement('link');
  201. link.rel = '${file.rel}';
  202. link.type = '${file.type}';
  203. link.href = '${file.href}';
  204. document.head.appendChild(link);
  205. ${combinedScript}
  206. `, script)
  207. }
  208. appendStylesToHead(styles, script) {
  209. if (!styles) {
  210. return script;
  211. }
  212. // Escape any single quotes or newlines in the CSS with .replace()
  213. const escaped = styles.replace(/\'/g, "\\'").replace(/\n/g, '\\n')
  214. return `
  215. var styleElement = document.createElement('style');
  216. var styleText = document.createTextNode('${escaped}');
  217. styleElement.appendChild(styleText);
  218. document.head.appendChild(styleElement);
  219. ${script}
  220. `
  221. }
  222. render() {
  223. const { height, script, isChangingSource, heightOffset } = this.state;
  224. const {
  225. scalesPageToFit,
  226. enableAnimation,
  227. source,
  228. customScript,
  229. style,
  230. enableBaseUrl
  231. } = this.props;
  232. let webViewSource = source;
  233. if (enableBaseUrl) {
  234. webViewSource = Object.assign({}, source, {
  235. baseUrl: "file:///android_asset/web/"
  236. });
  237. }
  238. return (
  239. <Animated.View
  240. style={[
  241. Styles.container,
  242. {
  243. opacity: enableAnimation ? this.opacityAnimatedValue : 1,
  244. height: height + heightOffset
  245. },
  246. style
  247. ]}
  248. >
  249. {isChangingSource ? null : (
  250. <RCTAutoHeightWebView
  251. ref={webview => (this.webview = webview)}
  252. style={Styles.webView}
  253. javaScriptEnabled={true}
  254. injectedJavaScript={script + customScript}
  255. scalesPageToFit={scalesPageToFit}
  256. source={webViewSource}
  257. onMessage={this.onMessage}
  258. messagingEnabled={true}
  259. // below kitkat
  260. onChange={this.onMessage}
  261. />
  262. )}
  263. </Animated.View>
  264. );
  265. }
  266. }
  267. const ScreenWidth = Dimensions.get("window").width;
  268. const IsBelowKitKat = Platform.Version < 19;
  269. const Styles = StyleSheet.create({
  270. container: {
  271. width: ScreenWidth,
  272. backgroundColor: "transparent"
  273. },
  274. webView: {
  275. flex: 1,
  276. backgroundColor: "transparent"
  277. }
  278. });
  279. const BaseScript = IsBelowKitKat
  280. ? `
  281. ; (function () {
  282. AutoHeightWebView.onMessage = function (message) {
  283. AutoHeightWebView.send(String(document.body.offsetHeight));
  284. };
  285. } ());
  286. `
  287. : `
  288. ; (function () {
  289. document.addEventListener('message', function (e) {
  290. window.postMessage(String(document.body.offsetHeight));
  291. });
  292. } ());
  293. `;