暫無描述

utils.js 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. 'use strict';
  2. import { Dimensions, Platform } from 'react-native';
  3. const domMutationObserveScript = `
  4. var MutationObserver =
  5. window.MutationObserver || window.WebKitMutationObserver;
  6. var observer = new MutationObserver(updateSize);
  7. observer.observe(document, {
  8. subtree: true,
  9. attributes: true
  10. });
  11. `;
  12. const updateSizeWithMessage = (element, scalesPageToFit) =>
  13. `
  14. var lastHeight = 0;
  15. var heightTheSameTimes = 0;
  16. var maxHeightTheSameTimes = 5;
  17. var forceRefreshDelay = 1000;
  18. var forceRefreshTimeout;
  19. var checkPostMessageTimeout;
  20. function updateSize(event) {
  21. if (
  22. !window.hasOwnProperty('ReactNativeWebView') ||
  23. !window.ReactNativeWebView.hasOwnProperty('postMessage')
  24. ) {
  25. checkPostMessageTimeout = setTimeout(updateSize, 200);
  26. return;
  27. }
  28. clearTimeout(checkPostMessageTimeout);
  29. height = ${element}.offsetHeight || document.documentElement.offsetHeight;
  30. width = ${element}.offsetWidth || document.documentElement.offsetWidth;
  31. var scale = ${scalesPageToFit ? 'screen.width / window.innerWidth' : '1'};
  32. window.ReactNativeWebView.postMessage(JSON.stringify({ width: Math.min(width, screen.width), height: height * scale }));
  33. // Make additional height checks (required to fix issues wit twitter embeds)
  34. clearTimeout(forceRefreshTimeout);
  35. if (lastHeight !== height) {
  36. heightTheSameTimes = 1;
  37. } else {
  38. heightTheSameTimes++;
  39. }
  40. lastHeight = height;
  41. if (heightTheSameTimes <= maxHeightTheSameTimes) {
  42. forceRefreshTimeout = setTimeout(
  43. updateSize,
  44. heightTheSameTimes * forceRefreshDelay
  45. );
  46. }
  47. }
  48. `;
  49. const disableZoom = `
  50. var meta = document.createElement("meta");
  51. meta.setAttribute("name", "viewport");
  52. meta.setAttribute("content", "width=device-width, user-scalable=no");
  53. document.getElementsByTagName("head")[0].appendChild(meta);
  54. `;
  55. const detectZoomChanged = `
  56. var zoomedin = false;
  57. var latestTapStamp = 0;
  58. var lastScale = false;
  59. var doubleTapDelay = 400;
  60. function detectZoomChanged() {
  61. var tempZoomedin = (screen.width / window.innerWidth) > 1;
  62. tempZoomedin !== zoomedin && window.ReactNativeWebView.postMessage(JSON.stringify({ zoomedin: tempZoomedin }));
  63. zoomedin = tempZoomedin;
  64. }
  65. window.addEventListener('touchend', event => {
  66. var tempScale = event.scale;
  67. tempScale !== lastScale && detectZoomChanged();
  68. lastScale = tempScale;
  69. var timeSince = new Date().getTime() - latestTapStamp;
  70. // double tap
  71. if(timeSince < 600 && timeSince > 0) {
  72. zoomedinTimeOut = setTimeout(() => {
  73. clearTimeout(zoomedinTimeOut);
  74. detectZoomChanged();
  75. }, doubleTapDelay);
  76. }
  77. latestTapStamp = new Date().getTime();
  78. });
  79. `;
  80. const getBaseScript = ({ style, zoomDisabled, scalesPageToFit, scrollEnabledWithZoomedin }) =>
  81. `
  82. ;
  83. if (!document.getElementById("rnahw-wrapper")) {
  84. var wrapper = document.createElement('div');
  85. wrapper.id = 'rnahw-wrapper';
  86. while (document.body.firstChild instanceof Node) {
  87. wrapper.appendChild(document.body.firstChild);
  88. }
  89. document.body.appendChild(wrapper);
  90. }
  91. ${updateSizeWithMessage('wrapper', scalesPageToFit)}
  92. window.addEventListener('load', updateSize);
  93. window.addEventListener('resize', updateSize);
  94. ${domMutationObserveScript}
  95. ${zoomDisabled ? disableZoom : ''}
  96. ${!zoomDisabled && scrollEnabledWithZoomedin ? detectZoomChanged : ''}
  97. updateSize();
  98. `;
  99. const appendFilesToHead = ({ files, script }) =>
  100. files.reduceRight((combinedScript, file) => {
  101. const { rel, type, href } = file;
  102. return `
  103. var link = document.createElement('link');
  104. link.rel = '${rel}';
  105. link.type = '${type}';
  106. link.href = '${href}';
  107. document.head.appendChild(link);
  108. ${combinedScript}
  109. `;
  110. }, script);
  111. const screenWidth = Dimensions.get('window').width;
  112. const bodyStyle = `
  113. body {
  114. margin: 0;
  115. padding: 0;
  116. }
  117. `;
  118. const appendStylesToHead = ({ style, script }) => {
  119. const currentStyles = style ? bodyStyle + style : bodyStyle;
  120. // Escape any single quotes or newlines in the CSS with .replace()
  121. const escaped = currentStyles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  122. return `
  123. var styleElement = document.createElement('style');
  124. styleElement.innerHTML = '${escaped}';
  125. document.head.appendChild(styleElement);
  126. ${script}
  127. `;
  128. };
  129. const getInjectedSource = ({ html, script }) => `
  130. ${html}
  131. <script>
  132. // prevents code colissions with global scope
  133. (function() {
  134. ${script}
  135. })();
  136. </script>
  137. `;
  138. const getScript = ({
  139. files,
  140. customStyle,
  141. customScript,
  142. style,
  143. zoomDisabled,
  144. scalesPageToFit,
  145. scrollEnabledWithZoomedin
  146. }) => {
  147. let script = getBaseScript({ style, zoomDisabled, scalesPageToFit, scrollEnabledWithZoomedin });
  148. script = files && files.length > 0 ? appendFilesToHead({ files, script }) : script;
  149. script = appendStylesToHead({ style: customStyle, script });
  150. customScript && (script = customScript + script);
  151. return script;
  152. };
  153. export const getWidth = style => {
  154. return style && style.width ? style.width : screenWidth;
  155. };
  156. export const isSizeChanged = ({ height, previousHeight, width, previousWidth }) => {
  157. if (!height || !width) {
  158. return;
  159. }
  160. return height !== previousHeight || width !== previousWidth;
  161. };
  162. export const reduceData = props => {
  163. const { source } = props;
  164. const script = getScript(props);
  165. const { html, baseUrl } = source;
  166. if (html) {
  167. return {
  168. currentSource: { baseUrl, html: getInjectedSource({ html, script }) }
  169. };
  170. } else {
  171. return {
  172. currentSource: source,
  173. script
  174. };
  175. }
  176. };
  177. export const shouldUpdate = ({ prevProps, nextProps }) => {
  178. if (!(prevProps && nextProps)) {
  179. return true;
  180. }
  181. for (const prop in nextProps) {
  182. if (nextProps[prop] !== prevProps[prop]) {
  183. if (typeof nextProps[prop] === 'object' && typeof prevProps[prop] === 'object') {
  184. if (
  185. shouldUpdate({
  186. prevProps: prevProps[prop],
  187. nextProps: nextProps[prop]
  188. })
  189. ) {
  190. return true;
  191. }
  192. } else {
  193. return true;
  194. }
  195. }
  196. }
  197. return false;
  198. };