|
| 1 | +// Replace marked ```dm playground code blocks with dm-playground embeds. |
| 2 | +(function(){ |
| 3 | + function utf8ToBase64(str){ |
| 4 | + var bytes = new TextEncoder().encode(str); |
| 5 | + var binary = String.fromCharCode.apply(null, Array.from(bytes)); |
| 6 | + return btoa(binary); |
| 7 | + } |
| 8 | + function makePlaygroundURL(code){ |
| 9 | + return 'https://play.dm-lang.org/?embed&code=' + encodeURIComponent(utf8ToBase64(code)); |
| 10 | + } |
| 11 | + function createIframe(src){ |
| 12 | + var ifr = document.createElement('iframe'); |
| 13 | + ifr.src = src; |
| 14 | + ifr.className = 'dm-playground-iframe'; |
| 15 | + return ifr; |
| 16 | + } |
| 17 | + |
| 18 | + document.addEventListener('DOMContentLoaded', function(){ |
| 19 | + const codeBlocks = Array.from(document.querySelectorAll('pre > code')); |
| 20 | + codeBlocks.forEach(function(code){ |
| 21 | + const cls = code.className || ''; |
| 22 | + const parentCls = code.parentElement && code.parentElement.className ? code.parentElement.className : ''; |
| 23 | + if (cls.indexOf('language-dm') === -1) return; |
| 24 | + if (cls.indexOf('playground') === -1 && parentCls.indexOf('playground') === -1) return; |
| 25 | + |
| 26 | + const codeText = code.textContent || ''; |
| 27 | + var wrapper = document.createElement('div'); |
| 28 | + wrapper.className = 'dm-playground-container'; |
| 29 | + |
| 30 | + try { |
| 31 | + var ifr = createIframe(makePlaygroundURL(codeText)); |
| 32 | + // Auto-height: estimate based on code lines |
| 33 | + const lines = (codeText.match(/\n/g) || []).length + 1; |
| 34 | + const estimated = Math.min(Math.max(lines * 16 + 88, 200), 900); |
| 35 | + wrapper.style.height = estimated + 'px'; |
| 36 | + wrapper.style.minHeight = '200px'; |
| 37 | + wrapper.appendChild(ifr); |
| 38 | + } catch (e) { |
| 39 | + var err = document.createElement('div'); |
| 40 | + wrapper.appendChild(err); |
| 41 | + } |
| 42 | + |
| 43 | + // Replace the <pre> element with the playground wrapper |
| 44 | + var pre = code.parentElement; |
| 45 | + if (pre?.parentElement) { |
| 46 | + try { |
| 47 | + pre.parentElement.replaceChild(wrapper, pre); |
| 48 | + } catch (e) { |
| 49 | + // fallback: append after if replaceChild fails |
| 50 | + pre.parentElement.insertBefore(wrapper, pre.nextSibling); |
| 51 | + } |
| 52 | + } |
| 53 | + }); |
| 54 | + }); |
| 55 | +})(); |
0 commit comments