Brak opisu

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. 'use strict';
  2. import { Dimensions } 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 usingScale = 0;
  15. var scaling = false;
  16. var zoomedin = false;
  17. var lastHeight = 0;
  18. var heightTheSameTimes = 0;
  19. var maxHeightTheSameTimes = 5;
  20. var forceRefreshDelay = 1000;
  21. var forceRefreshTimeout;
  22. var checkPostMessageTimeout;
  23. function updateSize() {
  24. if (zoomedin || scaling) {
  25. return;
  26. }
  27. if (
  28. !window.hasOwnProperty('ReactNativeWebView') ||
  29. !window.ReactNativeWebView.hasOwnProperty('postMessage')
  30. ) {
  31. checkPostMessageTimeout = setTimeout(updateSize, 200);
  32. return;
  33. }
  34. clearTimeout(checkPostMessageTimeout);
  35. height = ${element}.offsetHeight || document.documentElement.offsetHeight;
  36. width = ${element}.offsetWidth || document.documentElement.offsetWidth;
  37. if(!usingScale && window.innerWidth) {
  38. usingScale = ${scalesPageToFit ? 'screen.width / window.innerWidth' : '1'};
  39. }
  40. window.ReactNativeWebView.postMessage(JSON.stringify({ width: Math.min(width, screen.width), height: height * usingScale }));
  41. // Make additional height checks (required to fix issues wit twitter embeds)
  42. clearTimeout(forceRefreshTimeout);
  43. if (lastHeight !== height) {
  44. heightTheSameTimes = 1;
  45. } else {
  46. heightTheSameTimes++;
  47. }
  48. lastHeight = height;
  49. if (heightTheSameTimes <= maxHeightTheSameTimes) {
  50. forceRefreshTimeout = setTimeout(
  51. updateSize,
  52. heightTheSameTimes * forceRefreshDelay
  53. );
  54. }
  55. }
  56. `;
  57. const setViewportContent = content => {
  58. if (!content) {
  59. return '';
  60. }
  61. return `
  62. var meta = document.createElement("meta");
  63. meta.setAttribute("name", "viewport");
  64. meta.setAttribute("content", "${content}");
  65. document.getElementsByTagName("head")[0].appendChild(meta);
  66. `;
  67. };
  68. const detectZoomChanged = `
  69. var latestTapStamp = 0;
  70. var lastScale = 1.0;
  71. var doubleTapDelay = 400;
  72. function detectZoomChanged() {
  73. var tempZoomedin = (screen.width / window.innerWidth) > (usingScale || 1);
  74. tempZoomedin !== zoomedin && window.ReactNativeWebView.postMessage(JSON.stringify({ zoomedin: tempZoomedin }));
  75. zoomedin = tempZoomedin;
  76. }
  77. window.addEventListener('ontouchstart', event => {
  78. if (event.touches.length === 2) {
  79. scaling = true;
  80. }
  81. })
  82. window.addEventListener('touchend', event => {
  83. if(scaling) {
  84. scaleing = false;
  85. }
  86. var tempScale = event.scale;
  87. tempScale !== lastScale && detectZoomChanged();
  88. lastScale = tempScale;
  89. var timeSince = new Date().getTime() - latestTapStamp;
  90. // double tap
  91. if(timeSince < 600 && timeSince > 0) {
  92. zoomedinTimeOut = setTimeout(() => {
  93. clearTimeout(zoomedinTimeOut);
  94. detectZoomChanged();
  95. }, doubleTapDelay);
  96. }
  97. latestTapStamp = new Date().getTime();
  98. });
  99. `;
  100. const getBaseScript = ({ viewportContent, scalesPageToFit, scrollEnabledWithZoomedin }) =>
  101. `
  102. ;
  103. if (!document.getElementById("rnahw-wrapper")) {
  104. var wrapper = document.createElement('div');
  105. wrapper.id = 'rnahw-wrapper';
  106. while (document.body.firstChild instanceof Node) {
  107. wrapper.appendChild(document.body.firstChild);
  108. }
  109. document.body.appendChild(wrapper);
  110. }
  111. ${updateSizeWithMessage('wrapper', scalesPageToFit)}
  112. window.addEventListener('load', updateSize);
  113. window.addEventListener('resize', updateSize);
  114. ${domMutationObserveScript}
  115. ${setViewportContent(viewportContent)}
  116. ${scrollEnabledWithZoomedin ? detectZoomChanged : ''}
  117. updateSize();
  118. `;
  119. const appendFilesToHead = ({ files, script }) =>
  120. files.reduceRight((combinedScript, file) => {
  121. const { rel, type, href } = file;
  122. return `
  123. var link = document.createElement('link');
  124. link.rel = '${rel}';
  125. link.type = '${type}';
  126. link.href = '${href}';
  127. document.head.appendChild(link);
  128. ${combinedScript}
  129. `;
  130. }, script);
  131. const screenWidth = Dimensions.get('window').width;
  132. const bodyStyle = `
  133. body {
  134. margin: 0;
  135. padding: 0;
  136. }
  137. `;
  138. const appendStylesToHead = ({ style, script }) => {
  139. const currentStyles = style ? bodyStyle + style : bodyStyle;
  140. // Escape any single quotes or newlines in the CSS with .replace()
  141. const escaped = currentStyles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  142. return `
  143. var styleElement = document.createElement('style');
  144. styleElement.innerHTML = '${escaped}';
  145. document.head.appendChild(styleElement);
  146. ${script}
  147. `;
  148. };
  149. const getInjectedSource = ({ html, script }) => `
  150. ${html}
  151. <script>
  152. // prevents code colissions with global scope
  153. (function() {
  154. ${script}
  155. })();
  156. </script>
  157. `;
  158. const getScript = ({
  159. files,
  160. customStyle,
  161. customScript,
  162. style,
  163. viewportContent,
  164. scalesPageToFit,
  165. scrollEnabledWithZoomedin
  166. }) => {
  167. let script = getBaseScript({ viewportContent, scalesPageToFit, scrollEnabledWithZoomedin });
  168. script = files && files.length > 0 ? appendFilesToHead({ files, script }) : script;
  169. script = appendStylesToHead({ style: customStyle, script });
  170. customScript && (script = customScript + script);
  171. return script;
  172. };
  173. export const getWidth = style => {
  174. return style && style.width ? style.width : screenWidth;
  175. };
  176. export const isSizeChanged = ({ height, previousHeight, width, previousWidth }) => {
  177. if (!height || !width) {
  178. return;
  179. }
  180. return height !== previousHeight || width !== previousWidth;
  181. };
  182. export const reduceData = props => {
  183. const { source } = props;
  184. const script = getScript(props);
  185. const { html, baseUrl } = source;
  186. if (html) {
  187. return {
  188. currentSource: { baseUrl, html: getInjectedSource({ html, script }) }
  189. };
  190. } else {
  191. return {
  192. currentSource: source,
  193. script
  194. };
  195. }
  196. };
  197. export const shouldUpdate = ({ prevProps, nextProps }) => {
  198. if (!(prevProps && nextProps)) {
  199. return true;
  200. }
  201. for (const prop in nextProps) {
  202. if (nextProps[prop] !== prevProps[prop]) {
  203. if (typeof nextProps[prop] === 'object' && typeof prevProps[prop] === 'object') {
  204. if (
  205. shouldUpdate({
  206. prevProps: prevProps[prop],
  207. nextProps: nextProps[prop]
  208. })
  209. ) {
  210. return true;
  211. }
  212. } else {
  213. return true;
  214. }
  215. }
  216. }
  217. return false;
  218. };