Nenhuma descrição

utils.js 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 setViewportContent = content => {
  50. if (!content) {
  51. return '';
  52. }
  53. return `
  54. var meta = document.createElement("meta");
  55. meta.setAttribute("name", "viewport");
  56. meta.setAttribute("content", "${content}");
  57. document.getElementsByTagName("head")[0].appendChild(meta);
  58. `;
  59. };
  60. const detectZoomChanged = `
  61. var zoomedin = false;
  62. var latestTapStamp = 0;
  63. var lastScale = false;
  64. var doubleTapDelay = 400;
  65. function detectZoomChanged() {
  66. var tempZoomedin = (screen.width / window.innerWidth) > 1;
  67. tempZoomedin !== zoomedin && window.ReactNativeWebView.postMessage(JSON.stringify({ zoomedin: tempZoomedin }));
  68. zoomedin = tempZoomedin;
  69. }
  70. window.addEventListener('touchend', event => {
  71. var tempScale = event.scale;
  72. tempScale !== lastScale && detectZoomChanged();
  73. lastScale = tempScale;
  74. var timeSince = new Date().getTime() - latestTapStamp;
  75. // double tap
  76. if(timeSince < 600 && timeSince > 0) {
  77. zoomedinTimeOut = setTimeout(() => {
  78. clearTimeout(zoomedinTimeOut);
  79. detectZoomChanged();
  80. }, doubleTapDelay);
  81. }
  82. latestTapStamp = new Date().getTime();
  83. });
  84. `;
  85. const getBaseScript = ({ style, viewportContent, scalesPageToFit, scrollEnabledWithZoomedin }) =>
  86. `
  87. ;
  88. if (!document.getElementById("rnahw-wrapper")) {
  89. var wrapper = document.createElement('div');
  90. wrapper.id = 'rnahw-wrapper';
  91. while (document.body.firstChild instanceof Node) {
  92. wrapper.appendChild(document.body.firstChild);
  93. }
  94. document.body.appendChild(wrapper);
  95. }
  96. ${updateSizeWithMessage('wrapper', scalesPageToFit)}
  97. window.addEventListener('load', updateSize);
  98. window.addEventListener('resize', updateSize);
  99. ${domMutationObserveScript}
  100. ${setViewportContent(viewportContent)}
  101. ${scrollEnabledWithZoomedin ? detectZoomChanged : ''}
  102. updateSize();
  103. `;
  104. const appendFilesToHead = ({ files, script }) =>
  105. files.reduceRight((combinedScript, file) => {
  106. const { rel, type, href } = file;
  107. return `
  108. var link = document.createElement('link');
  109. link.rel = '${rel}';
  110. link.type = '${type}';
  111. link.href = '${href}';
  112. document.head.appendChild(link);
  113. ${combinedScript}
  114. `;
  115. }, script);
  116. const screenWidth = Dimensions.get('window').width;
  117. const bodyStyle = `
  118. body {
  119. margin: 0;
  120. padding: 0;
  121. }
  122. `;
  123. const appendStylesToHead = ({ style, script }) => {
  124. const currentStyles = style ? bodyStyle + style : bodyStyle;
  125. // Escape any single quotes or newlines in the CSS with .replace()
  126. const escaped = currentStyles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  127. return `
  128. var styleElement = document.createElement('style');
  129. styleElement.innerHTML = '${escaped}';
  130. document.head.appendChild(styleElement);
  131. ${script}
  132. `;
  133. };
  134. const getInjectedSource = ({ html, script }) => `
  135. ${html}
  136. <script>
  137. // prevents code colissions with global scope
  138. (function() {
  139. ${script}
  140. })();
  141. </script>
  142. `;
  143. const getScript = ({
  144. files,
  145. customStyle,
  146. customScript,
  147. style,
  148. viewportContent,
  149. scalesPageToFit,
  150. scrollEnabledWithZoomedin
  151. }) => {
  152. let script = getBaseScript({ style, viewportContent, scalesPageToFit, scrollEnabledWithZoomedin });
  153. script = files && files.length > 0 ? appendFilesToHead({ files, script }) : script;
  154. script = appendStylesToHead({ style: customStyle, script });
  155. customScript && (script = customScript + script);
  156. return script;
  157. };
  158. export const getWidth = style => {
  159. return style && style.width ? style.width : screenWidth;
  160. };
  161. export const isSizeChanged = ({ height, previousHeight, width, previousWidth }) => {
  162. if (!height || !width) {
  163. return;
  164. }
  165. return height !== previousHeight || width !== previousWidth;
  166. };
  167. export const reduceData = props => {
  168. const { source } = props;
  169. const script = getScript(props);
  170. const { html, baseUrl } = source;
  171. if (html) {
  172. return {
  173. currentSource: { baseUrl, html: getInjectedSource({ html, script }) }
  174. };
  175. } else {
  176. return {
  177. currentSource: source,
  178. script
  179. };
  180. }
  181. };
  182. export const shouldUpdate = ({ prevProps, nextProps }) => {
  183. if (!(prevProps && nextProps)) {
  184. return true;
  185. }
  186. for (const prop in nextProps) {
  187. if (nextProps[prop] !== prevProps[prop]) {
  188. if (typeof nextProps[prop] === 'object' && typeof prevProps[prop] === 'object') {
  189. if (
  190. shouldUpdate({
  191. prevProps: prevProps[prop],
  192. nextProps: nextProps[prop]
  193. })
  194. ) {
  195. return true;
  196. }
  197. } else {
  198. return true;
  199. }
  200. }
  201. }
  202. return false;
  203. };