demo.html 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. {{ $uniq := .Inner | htmlEscape | md5 | lower }}
  2. <div class="demo-container">
  3. {{ if .Get "caption" }}
  4. <figure role="group" aria-labelledby="caption-{{ $uniq }}">
  5. {{ end }}
  6. <div class="demo-inner">
  7. <div class="demo" id="js-demo-{{ $uniq }}"></div>
  8. <button data-launch="js-demo-{{ $uniq }}">Launch in separate window</button>
  9. </div>
  10. {{ if .Get "caption" }}
  11. <figcaption id="caption-{{ $uniq }}">{{ .Get "caption" | markdownify }}</figcaption>
  12. {{ end }}
  13. {{ if .Get "caption" }}
  14. </figure>
  15. {{ end }}
  16. <template id="template-{{ $uniq }}">
  17. {{ .Inner }}
  18. </template>
  19. <script>
  20. (function() {
  21. var root = document.getElementById('js-demo-{{ $uniq }}');
  22. var template = document.getElementById('template-{{ $uniq }}');
  23. var script = template.content.querySelector('script');
  24. if (script) {
  25. var standaloneScript = '(function() { document.getElementsByTagName(\'html\')[0].setAttribute(\'lang\', \'en\'); var demo = document; ' + script.textContent + ' })()';
  26. var wrappedScript = '(function() { var demo = document.getElementById(\'js-demo-{{ $uniq }}\').shadowRoot;' + script.textContent + '})()';
  27. script.textContent = wrappedScript;
  28. }
  29. if (document.head.attachShadow) {
  30. root.attachShadow({mode: 'open'});
  31. root.shadowRoot.appendChild(document.importNode(template.content, true));
  32. } else {
  33. root.innerHTML = '<p class="site-error"><strong style="font-weight:bold">Site error:</strong> A browser supporting Shadow DOM is needed to run encapsulated demos. You can launch the demo in a separate window ↓</p>';
  34. }
  35. var launchButton = document.querySelector('[data-launch="js-demo-{{ $uniq }}"]');
  36. launchButton.addEventListener('click', function () {
  37. var demoContent = template.content;
  38. var standalone = window.open();
  39. script.textContent = standaloneScript;
  40. standalone.document.body.appendChild(document.importNode(template.content, true));
  41. standalone.document.title = 'demo ' + {{ $uniq }}
  42. });
  43. })();
  44. </script>
  45. </div>