説明なし

utils.js 6.1KB

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