暫無描述

utils.js 5.1KB

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