Nenhuma descrição

utils.js 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 scale = ${scalesPageToFit ? 'screen.width / window.innerWidth' : '1'};
  15. var lastHeight = 0;
  16. var heightTheSameTimes = 0;
  17. var maxHeightTheSameTimes = 5;
  18. var forceRefreshDelay = 1000;
  19. var forceRefreshTimeout;
  20. var checkPostMessageTimeout;
  21. function updateSize(event) {
  22. if (
  23. !window.hasOwnProperty('ReactNativeWebView') ||
  24. !window.ReactNativeWebView.hasOwnProperty('postMessage')
  25. ) {
  26. checkPostMessageTimeout = setTimeout(updateSize, 200);
  27. return;
  28. }
  29. clearTimeout(checkPostMessageTimeout);
  30. height = ${element}.offsetHeight || document.documentElement.offsetHeight;
  31. width = ${element}.offsetWidth || document.documentElement.offsetWidth;
  32. var needScale = width > screen.width;
  33. window.ReactNativeWebView.postMessage(JSON.stringify({ width: needScale ? width * scale : width, height: needScale ? height * scale : height }));
  34. // Make additional height checks (required to fix issues wit twitter embeds)
  35. clearTimeout(forceRefreshTimeout);
  36. if (lastHeight !== height) {
  37. heightTheSameTimes = 1;
  38. } else {
  39. heightTheSameTimes++;
  40. }
  41. lastHeight = height;
  42. if (heightTheSameTimes <= maxHeightTheSameTimes) {
  43. forceRefreshTimeout = setTimeout(
  44. updateSize,
  45. heightTheSameTimes * forceRefreshDelay
  46. );
  47. }
  48. }
  49. `;
  50. // add viewport setting to meta
  51. const makeScalePageToFit = (zoomable, scalesPageToFit) =>
  52. scalesPageToFit || Platform.OS === 'android'
  53. ? ''
  54. : `
  55. var meta = document.createElement("meta");
  56. meta.setAttribute("name", "viewport");
  57. meta.setAttribute("content", "width=device-width, user-scalable=${zoomable ? 'yes' : 'no'}");
  58. document.getElementsByTagName("head")[0].appendChild(meta);
  59. `;
  60. const getBaseScript = ({ style, zoomable, scalesPageToFit }) =>
  61. `
  62. ;
  63. if (!document.getElementById("rnahw-wrapper")) {
  64. var wrapper = document.createElement('div');
  65. wrapper.id = 'rnahw-wrapper';
  66. while (document.body.firstChild instanceof Node) {
  67. wrapper.appendChild(document.body.firstChild);
  68. }
  69. document.body.appendChild(wrapper);
  70. }
  71. ${updateSizeWithMessage('wrapper', scalesPageToFit)}
  72. window.addEventListener('load', updateSize);
  73. window.addEventListener('resize', updateSize);
  74. ${domMutationObserveScript}
  75. ${makeScalePageToFit(zoomable, scalesPageToFit)}
  76. updateSize();
  77. `;
  78. const appendFilesToHead = ({ files, script }) =>
  79. files.reduceRight((combinedScript, file) => {
  80. const { rel, type, href } = file;
  81. return `
  82. var link = document.createElement('link');
  83. link.rel = '${rel}';
  84. link.type = '${type}';
  85. link.href = '${href}';
  86. document.head.appendChild(link);
  87. ${combinedScript}
  88. `;
  89. }, script);
  90. const screenWidth = Dimensions.get('window').width;
  91. const bodyStyle = `
  92. body {
  93. margin: 0;
  94. padding: 0;
  95. }
  96. `;
  97. const appendStylesToHead = ({ style, script }) => {
  98. const currentStyles = style ? bodyStyle + style : bodyStyle;
  99. // Escape any single quotes or newlines in the CSS with .replace()
  100. const escaped = currentStyles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  101. return `
  102. var styleElement = document.createElement('style');
  103. styleElement.innerHTML = '${escaped}';
  104. document.head.appendChild(styleElement);
  105. ${script}
  106. `;
  107. };
  108. const getInjectedSource = ({ html, script }) => `
  109. ${html}
  110. <script>
  111. // prevents code colissions with global scope
  112. (function() {
  113. ${script}
  114. })();
  115. </script>
  116. `;
  117. const getScript = ({ files, customStyle, customScript, style, zoomable, scalesPageToFit }) => {
  118. let script = getBaseScript({ style, zoomable, scalesPageToFit });
  119. script = files && files.length > 0 ? appendFilesToHead({ files, script }) : script;
  120. script = appendStylesToHead({ style: customStyle, script });
  121. customScript && (script = customScript + script);
  122. return script;
  123. };
  124. export const getWidth = style => {
  125. return style && style.width ? style.width : screenWidth;
  126. };
  127. export const isSizeChanged = ({ height, previousHeight, width, previousWidth }) => {
  128. if (!height || !width) {
  129. return;
  130. }
  131. return height !== previousHeight || width !== previousWidth;
  132. };
  133. export const reduceData = props => {
  134. const { source } = props;
  135. const script = getScript(props);
  136. const { html, baseUrl } = source;
  137. if (html) {
  138. return {
  139. currentSource: { baseUrl, html: getInjectedSource({ html, script }) }
  140. };
  141. } else {
  142. return {
  143. currentSource: source,
  144. script
  145. };
  146. }
  147. };
  148. export const shouldUpdate = ({ prevProps, nextProps }) => {
  149. if (!(prevProps && nextProps)) {
  150. return true;
  151. }
  152. for (const prop in nextProps) {
  153. if (nextProps[prop] !== prevProps[prop]) {
  154. if (typeof nextProps[prop] === 'object' && typeof prevProps[prop] === 'object') {
  155. if (
  156. shouldUpdate({
  157. prevProps: prevProps[prop],
  158. nextProps: nextProps[prop]
  159. })
  160. ) {
  161. return true;
  162. }
  163. } else {
  164. return true;
  165. }
  166. }
  167. }
  168. return false;
  169. };