No Description

common.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. import { Dimensions } from 'react-native';
  3. function appendFilesToHead(files, script) {
  4. if (!files) {
  5. return script;
  6. }
  7. return files.reduceRight((file, combinedScript) => {
  8. const { rel, type, href } = file;
  9. return `
  10. var link = document.createElement('link');
  11. link.rel = '${rel}';
  12. link.type = '${type}';
  13. link.href = '${href}';
  14. document.head.appendChild(link);
  15. ${combinedScript}
  16. `;
  17. }, script);
  18. }
  19. const screenWidth = Dimensions.get('window').width;
  20. function getWidth(style) {
  21. return style && style.width ? style.width : screenWidth;
  22. }
  23. const bodyStyle = `
  24. body {
  25. margin: 0;
  26. padding: 0;
  27. }
  28. `;
  29. function appendStylesToHead(styles, script) {
  30. const currentStyles = bodyStyle + styles;
  31. // Escape any single quotes or newlines in the CSS with .replace()
  32. const escaped = currentStyles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  33. return `
  34. var styleElement = document.createElement('style');
  35. var styleText = document.createTextNode('${escaped}');
  36. styleElement.appendChild(styleText);
  37. document.head.appendChild(styleElement);
  38. ${script}
  39. `;
  40. }
  41. function getScript(props, getBaseScript, getIframeBaseScript) {
  42. const { hasIframe, files, customStyle } = props;
  43. const baseScript = getBaseScript(props.style);
  44. let script = hasIframe ? baseScript : getIframeBaseScript(props.style);
  45. script = files ? appendFilesToHead(files, baseScript) : baseScript;
  46. script = appendStylesToHead(customStyle, script);
  47. return script;
  48. }
  49. function handleSizeUpdated(height, width, onSizeUpdated) {
  50. onSizeUpdated &&
  51. onSizeUpdated({
  52. height,
  53. width
  54. });
  55. }
  56. const domMutationObserveScript = `
  57. var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  58. var observer = new MutationObserver(updateSize);
  59. observer.observe(document, {
  60. subtree: true,
  61. attributes: true
  62. });
  63. `;
  64. export { getWidth, getScript, handleSizeUpdated, domMutationObserveScript };