Açıklama Yok

utils.js 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 }) =>
  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. updateSize();
  101. `;
  102. const appendFilesToHead = ({ files, script }) =>
  103. files.reduceRight((combinedScript, file) => {
  104. const { rel, type, href } = file;
  105. return `
  106. var link = document.createElement('link');
  107. link.rel = '${rel}';
  108. link.type = '${type}';
  109. link.href = '${href}';
  110. document.head.appendChild(link);
  111. ${combinedScript}
  112. `;
  113. }, script);
  114. const screenWidth = Dimensions.get('window').width;
  115. const bodyStyle = `
  116. body {
  117. margin: 0;
  118. padding: 0;
  119. }
  120. `;
  121. const appendStylesToHead = ({ style, script }) => {
  122. const currentStyles = style ? bodyStyle + style : bodyStyle;
  123. // Escape any single quotes or newlines in the CSS with .replace()
  124. const escaped = currentStyles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  125. return `
  126. var styleElement = document.createElement('style');
  127. styleElement.innerHTML = '${escaped}';
  128. document.head.appendChild(styleElement);
  129. ${script}
  130. `;
  131. };
  132. const getInjectedSource = ({ html, script }) => `
  133. ${html}
  134. <script>
  135. // prevents code colissions with global scope
  136. (function() {
  137. ${script}
  138. })();
  139. </script>
  140. `;
  141. const getScript = ({ files, customStyle, customScript, style, zoomable, scalesPageToFit }) => {
  142. let script = getBaseScript({ style, zoomable, scalesPageToFit });
  143. script = files && files.length > 0 ? appendFilesToHead({ files, script }) : script;
  144. script = appendStylesToHead({ style: customStyle, script });
  145. customScript && (script = customScript + script);
  146. return script;
  147. };
  148. export const getWidth = style => {
  149. return style && style.width ? style.width : screenWidth;
  150. };
  151. export const isSizeChanged = ({ height, previousHeight, width, previousWidth }) => {
  152. if (!height || !width) {
  153. return;
  154. }
  155. return height !== previousHeight || width !== previousWidth;
  156. };
  157. export const reduceData = props => {
  158. const { source } = props;
  159. const script = getScript(props);
  160. const { html, baseUrl } = source;
  161. if (html) {
  162. return {
  163. currentSource: { baseUrl, html: getInjectedSource({ html, script }) }
  164. };
  165. } else {
  166. return {
  167. currentSource: source,
  168. script
  169. };
  170. }
  171. };
  172. export const shouldUpdate = ({ prevProps, nextProps }) => {
  173. if (!(prevProps && nextProps)) {
  174. return true;
  175. }
  176. for (const prop in nextProps) {
  177. if (nextProps[prop] !== prevProps[prop]) {
  178. if (typeof nextProps[prop] === 'object' && typeof prevProps[prop] === 'object') {
  179. if (
  180. shouldUpdate({
  181. prevProps: prevProps[prop],
  182. nextProps: nextProps[prop]
  183. })
  184. ) {
  185. return true;
  186. }
  187. } else {
  188. return true;
  189. }
  190. }
  191. }
  192. return false;
  193. };