Açıklama Yok

common.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. function appendFilesToHead(files, script) {
  3. if (!files) {
  4. return script;
  5. }
  6. return files.reduceRight((file, combinedScript) => {
  7. const { rel, type, href } = file;
  8. return `
  9. var link = document.createElement('link');
  10. link.rel = '${rel}';
  11. link.type = '${type}';
  12. link.href = '${href}';
  13. document.head.appendChild(link);
  14. ${combinedScript}
  15. `;
  16. }, script);
  17. }
  18. function appendStylesToHead(styles, script, shouldResizeWidth) {
  19. var bodyStyle;
  20. if (shouldResizeWidth) {
  21. bodyStyle = `
  22. body {
  23. display: flex;
  24. justify-content: center;
  25. align-items: center;
  26. }`;
  27. }
  28. else {
  29. bodyStyle = '';
  30. }
  31. if (!styles) {
  32. styles = bodyStyle;
  33. }
  34. else {
  35. styles += bodyStyle;
  36. }
  37. // Escape any single quotes or newlines in the CSS with .replace()
  38. const escaped = styles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  39. return `
  40. var styleElement = document.createElement('style');
  41. var styleText = document.createTextNode('${escaped}');
  42. styleElement.appendChild(styleText);
  43. document.head.appendChild(styleElement);
  44. ${script}
  45. `;
  46. }
  47. function getScript(props, baseScript, iframeBaseScript) {
  48. const { hasIframe, files, customStyle, shouldResizeWidth } = props;
  49. let script = hasIframe ? iframeBaseScript : baseScript;
  50. script = files ? appendFilesToHead(files, baseScript) : baseScript;
  51. script = appendStylesToHead(customStyle, script, shouldResizeWidth);
  52. return script;
  53. }
  54. function onHeightUpdated(height, props) {
  55. props.onHeightUpdated && props.onHeightUpdated(height);
  56. }
  57. function onWidthUpdated(width, props) {
  58. props.onWidthUpdated && props.onWidthUpdated(width);
  59. }
  60. function onHeightWidthUpdated(height, width, props) {
  61. onHeightUpdated(height, props);
  62. onWidthUpdated(width, props);
  63. props.onHeightWidthUpdated && props.onHeightWidthUpdated(height, width);
  64. }
  65. const domMutationObserveScript =
  66. `
  67. var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  68. var observer = new MutationObserver(updateHeight);
  69. observer.observe(document, {
  70. subtree: true,
  71. attributes: true
  72. });
  73. `;
  74. export { getScript, onHeightUpdated, onWidthUpdated, onHeightWidthUpdated, domMutationObserveScript };