Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.19 KB | None | 0 0
  1. <!doctype html>
  2. <html lang=en>
  3. <head>
  4. <meta charset=utf-8>
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <script>
  7. const el = h('div', {className: 'shadow-demos'}, [
  8. h('style', `
  9. .shadow-demos {
  10. width: 300px;
  11. border: 1px solid lightgrey;
  12. margin: 1em;
  13. }
  14. hr { margin: 3em 0; }
  15. p { text-align: center; }
  16. `),
  17.  
  18. h('p', [
  19. 'Global styles: ',
  20. h('br'),
  21. 'black, uppercase, and centered.',
  22. ]),
  23.  
  24. h('hr'),
  25.  
  26. h('#div', [
  27. h('p', 'Sandboxed. No styles.'),
  28. ]),
  29.  
  30. h('hr'),
  31.  
  32. h('#div', [
  33. h('p', 'Different sandbox.'),
  34. h('style', `
  35. p { text-transform: uppercase; color: blue; }
  36. `),
  37. ]),
  38.  
  39. h('hr'),
  40.  
  41. h('#div', [
  42. h('p', ['Nested sandboxes.', h('br'), 'Outer']),
  43. h('style', `
  44. p { text-transform: uppercase; color: green; }
  45. `),
  46.  
  47. h('#div', [
  48. h('p', 'Inner.'),
  49. h('style', `
  50. p { color: red; }
  51. `),
  52. ]),
  53. ]),
  54. ])
  55.  
  56. ready(() => {
  57. render(document.querySelector('#container'))(el)
  58. })
  59.  
  60. // ----------------------------------------------------------------------------
  61.  
  62. function render(el) {
  63. return (content) => {
  64. el.innerHTML = '';
  65. el.appendChild(content);
  66. }
  67. }
  68.  
  69. function ready(fn) {
  70. if (document.readyState != 'loading') {
  71. fn();
  72. } else {
  73. document.addEventListener('DOMContentLoaded', fn);
  74. }
  75. }
  76.  
  77. function h(tag, a, b) {
  78. let el, _el
  79. if (tag.startsWith('#')) {
  80. _el = document.createElement(tag.slice(1))
  81. el = _el.attachShadow({mode: 'open'})
  82. } else {
  83. el = document.createElement(tag);
  84. }
  85.  
  86. // const el = document.createElement(tag);
  87. let attrs, children;
  88.  
  89. if (Array.isArray(a) || typeof a === 'string' || a instanceof Element) {
  90. attrs = {};
  91. children = a;
  92. } else {
  93. attrs = a === undefined ? {} : a;
  94. children = b === undefined ? [] : b;
  95. }
  96.  
  97. Object.entries(attrs).forEach(([key, val]) => {
  98. if (key === 'style' && val.constructor === Object) {
  99. Object.entries(val).forEach(([k, v]) => el.style.setProperty(k, v))
  100. } else {
  101. el[key] = val;
  102. }
  103. });
  104.  
  105. [].concat(children).forEach(child =>
  106. el.appendChild(typeof child === 'string'
  107. ? document.createTextNode(child)
  108. : child));
  109.  
  110. return _el || el;
  111. }
  112. </script>
  113. </head>
  114. <body>
  115. <div id="container"></div>
  116. </body>
  117. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement