Download backend/src/shared/embed-doc.ts from HuggingFaceSwarms/scaling-swarms: direct link, hf CLI and curl.
- Browser
- Download file 26.1 kB
-
https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/backend/src/shared/embed-doc.ts
- Command line
-
hf download hf://spaces/HuggingFaceSwarms/scaling-swarms/backend/src/shared/embed-doc.ts
-
curl -L -o embed-doc.ts https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/backend/src/shared/embed-doc.ts
26.1 kB
| // --------------------------------------------------------------------------- | |
| // Shared embed document builder | |
| // | |
| // Single source of truth for the srcdoc injected into every embed iframe, | |
| // used by both the editor (live preview) and the publisher (static HTML). | |
| // | |
| // Exports: | |
| // - buildEmbedSrcdoc(html, opts) – assemble the full HTML doc | |
| // - EMBED_MESSAGE_TYPES – { resize, setTheme, updatePrimaryColor } | |
| // - DEFAULT_EMBED_HEIGHT – fallback pixel height when none stored | |
| // | |
| // Why one shared builder? | |
| // Before, the editor and publisher each had their own COLOR_PALETTES / height | |
| // reporter / theme listener, with subtle divergences (e.g. only the publisher | |
| // supported setTheme hot-swap). Keeping them in sync by hand was a footgun. | |
| // --------------------------------------------------------------------------- | |
| import { EMBED_RUNTIME_JS, EMBED_RUNTIME_VERSION } from "./embed-runtime.generated.js"; | |
| import { oklchFromHue } from "./theme.js"; | |
| export const DEFAULT_EMBED_HEIGHT = 400; | |
| /** Default article primary color (hue 47 in _variables.css of the editor and the template). */ | |
| export const DEFAULT_PRIMARY_COLOR = oklchFromHue(47); | |
| // The runtime source contains `</script>` in comments, which would close the | |
| // inline <script> tag early. | |
| const EMBED_RUNTIME_INLINE = EMBED_RUNTIME_JS.replace(/<\/script/gi, "<\\/script"); | |
| export const EMBED_MESSAGE_TYPES = { | |
| resize: "embedResize", | |
| setTheme: "setTheme", | |
| updatePrimaryColor: "updatePrimaryColor", | |
| ready: "embedReady", | |
| error: "embedError", | |
| status: "embedStatus", | |
| } as const; | |
| /** | |
| * Studio-only error reporter. Installed first in <head> so it also sees | |
| * syntax errors in the fragment's scripts and failed CDN loads, then relays | |
| * every failure (and the first successful render) to the parent frame: | |
| * { type: 'embedError', message, source: 'window' | 'promise' | 'resource' | 'runtime' } | |
| * { type: 'embedStatus', status: 'ready' } | |
| * The parent uses it to show "The chart threw ..." and to send the error | |
| * back to the agent. | |
| */ | |
| const STUDIO_ERROR_REPORTER = ` | |
| (function(){ | |
| function post(msg){ try { window.parent.postMessage(msg, '*'); } catch(e){} } | |
| function text(v){ return v && v.message ? String(v.message) : String(v); } | |
| window.addEventListener('error', function(e){ | |
| var t = e.target; | |
| if (t && t !== window && t.tagName) { | |
| post({ type: 'embedError', source: 'resource', message: 'Failed to load ' + (t.src || t.href || t.tagName.toLowerCase()) }); | |
| return; | |
| } | |
| var where = e.lineno ? ' (line ' + e.lineno + ')' : ''; | |
| post({ type: 'embedError', source: 'window', message: (e.message || text(e.error)) + where }); | |
| }, true); | |
| window.addEventListener('unhandledrejection', function(e){ | |
| post({ type: 'embedError', source: 'promise', message: text(e.reason) }); | |
| }); | |
| document.addEventListener('embed:error', function(e){ | |
| post({ type: 'embedError', source: 'runtime', message: (e.detail && e.detail.error) || 'The embed failed to render' }); | |
| }); | |
| document.addEventListener('embed:ready', function(){ | |
| post({ type: 'embedStatus', status: 'ready' }); | |
| }); | |
| })(); | |
| `.trim(); | |
| /** | |
| * Studio-only point-and-click inspector. Off until the parent posts | |
| * { type: 'embedInspect', on: true }; then hovering outlines an element and | |
| * a click posts { type: 'embedPick', pick } (tag, text, classes, selector, | |
| * bound datum) instead of reaching the chart. Escape turns it off and posts | |
| * { type: 'embedInspectExit' }. | |
| */ | |
| const STUDIO_INSPECTOR = ` | |
| (function(){ | |
| var on = false, box = null, hover = null; | |
| function post(msg){ try { window.parent.postMessage(msg, '*'); } catch(e){} } | |
| function ensureBox(){ | |
| if (box) return box; | |
| box = document.createElement('div'); | |
| box.setAttribute('data-embed-inspector', ''); | |
| box.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483647;display:none;border:2px solid #4c6ef5;background:rgba(76,110,245,.12);border-radius:3px;'; | |
| document.documentElement.appendChild(box); | |
| return box; | |
| } | |
| function hide(){ if (box) box.style.display = 'none'; hover = null; } | |
| function pathOf(el){ | |
| var parts = []; | |
| while (el && el.nodeType === 1 && el !== document.body && parts.length < 5) { | |
| var s = el.tagName.toLowerCase(); | |
| var cls = el.getAttribute('class'); | |
| if (cls) s += '.' + cls.trim().split(/\\s+/).slice(0, 2).join('.'); | |
| var p = el.parentElement; | |
| if (p) { | |
| var same = Array.prototype.filter.call(p.children, function(c){ return c.tagName === el.tagName; }); | |
| if (same.length > 1) s += ':nth-of-type(' + (same.indexOf(el) + 1) + ')'; | |
| } | |
| parts.unshift(s); | |
| el = p; | |
| } | |
| return parts.join(' > '); | |
| } | |
| function datum(el){ | |
| var d = el && el.__data__; | |
| if (d === undefined || d === null) return null; | |
| try { return JSON.stringify(d).slice(0, 240); } catch(e) { return null; } | |
| } | |
| function describe(el){ | |
| var text = (el.textContent || '').replace(/\\s+/g, ' ').trim(); | |
| var r = el.getBoundingClientRect(); | |
| return { | |
| tag: el.tagName.toLowerCase(), | |
| text: text.slice(0, 160), | |
| ownText: el.children.length === 0, | |
| classes: (el.getAttribute('class') || '').trim(), | |
| selector: pathOf(el), | |
| fill: el.getAttribute('fill') || (el.style && el.style.fill) || null, | |
| datum: datum(el), | |
| bbox: { x: Math.round(r.left), y: Math.round(r.top), width: Math.round(r.width), height: Math.round(r.height) } | |
| }; | |
| } | |
| window.addEventListener('message', function(e){ | |
| if (!e.data || e.data.type !== 'embedInspect') return; | |
| on = !!e.data.on; | |
| document.documentElement.style.cursor = on ? 'crosshair' : ''; | |
| if (!on) hide(); | |
| }); | |
| document.addEventListener('pointermove', function(e){ | |
| if (!on) return; | |
| var t = e.target; | |
| if (!t || t === box || t === document.documentElement || t === document.body) { hide(); return; } | |
| hover = t; | |
| var r = t.getBoundingClientRect(), b = ensureBox(); | |
| b.style.display = 'block'; | |
| b.style.left = (r.left - 2) + 'px'; | |
| b.style.top = (r.top - 2) + 'px'; | |
| b.style.width = (r.width + 4) + 'px'; | |
| b.style.height = (r.height + 4) + 'px'; | |
| }, true); | |
| document.addEventListener('click', function(e){ | |
| if (!on) return; | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| var t = hover || e.target; | |
| if (!t || t === document.documentElement || t === document.body) return; | |
| on = false; | |
| document.documentElement.style.cursor = ''; | |
| hide(); | |
| post({ type: 'embedPick', pick: describe(t) }); | |
| }, true); | |
| document.addEventListener('keydown', function(e){ | |
| if (on && e.key === 'Escape') { | |
| on = false; | |
| document.documentElement.style.cursor = ''; | |
| hide(); | |
| post({ type: 'embedInspectExit' }); | |
| } | |
| }, true); | |
| })(); | |
| `.trim(); | |
| /** | |
| * ColorPalettes polyfill. Same API and same generators as the | |
| * research-article-template (public/scripts/color-palettes.js): every palette | |
| * is derived from --primary-color in OKLCH, and the diverging midpoint follows | |
| * the theme, so the editor preview matches the published article. | |
| */ | |
| const COLOR_PALETTES_POLYFILL = ` | |
| (function(){ | |
| function rgb(hex){ | |
| var v = parseInt(String(hex).replace('#', ''), 16); | |
| return [(v >> 16) & 255, (v >> 8) & 255, v & 255]; | |
| } | |
| function toLinear(u){ return u <= 0.04045 ? u / 12.92 : Math.pow((u + 0.055) / 1.055, 2.4); } | |
| function fromLinear(u){ return u <= 0.0031308 ? 12.92 * u : 1.055 * Math.pow(Math.max(0, u), 1 / 2.4) - 0.055; } | |
| function rgbToOklch(r, g, b){ | |
| r = toLinear(r); g = toLinear(g); b = toLinear(b); | |
| var l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); | |
| var m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); | |
| var s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); | |
| var L = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s; | |
| var A = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s; | |
| var B = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s; | |
| var h = Math.atan2(B, A) * 180 / Math.PI; | |
| return { L: L, C: Math.sqrt(A * A + B * B), h: h < 0 ? h + 360 : h }; | |
| } | |
| function oklabToRgb(L, a, b){ | |
| var l = L + 0.3963377774 * a + 0.2158037573 * b; | |
| var m = L - 0.1055613458 * a - 0.0638541728 * b; | |
| var s = L - 0.0894841775 * a - 1.2914855480 * b; | |
| l = l * l * l; m = m * m * m; s = s * s * s; | |
| return [ | |
| fromLinear(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s), | |
| fromLinear(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s), | |
| fromLinear(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s) | |
| ]; | |
| } | |
| function toHex(c){ | |
| return '#' + c.map(function(x){ return ('0' + Math.round(Math.min(1, Math.max(0, x)) * 255).toString(16)).slice(-2); }).join(''); | |
| } | |
| function lab(L, C, h){ var r = h * Math.PI / 180; return { L: L, a: C * Math.cos(r), b: C * Math.sin(r) }; } | |
| function labHex(p){ return toHex(oklabToRgb(p.L, p.a, p.b)); } | |
| // Reduce chroma until the color fits in sRGB, as the template does. | |
| function oklchHex(L, C, h){ | |
| for (var i = 0; i < 12; i++) { | |
| var p = lab(L, C, h), c = oklabToRgb(p.L, p.a, p.b); | |
| if (c.every(function(v){ return v >= 0 && v <= 1; })) return toHex(c); | |
| C = Math.max(0, C - 0.02); | |
| } | |
| return toHex(oklabToRgb(L, 0, 0)); | |
| } | |
| function primaryOklch(){ | |
| var css = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim(); | |
| return parseOklch(css) || parseOklch('${DEFAULT_PRIMARY_COLOR}'); | |
| } | |
| function parseOklch(css){ | |
| if (!css) return null; | |
| var ok = css.match(/oklch\\(([^)]+)\\)/i); | |
| if (ok) { | |
| var v = ok[1].trim().split(/[\\s,\\/]+/).map(parseFloat); | |
| if (v.length >= 3 && v.every(isFinite)) return { L: v[0] > 1 ? v[0] / 100 : v[0], C: v[1], h: v[2] }; | |
| } | |
| var c = /^#[0-9a-f]{6}$/i.test(css) ? rgb(css) : null; | |
| if (!c && document.body) { | |
| var el = document.createElement('span'); | |
| el.style.color = css; | |
| document.body.appendChild(el); | |
| var m = getComputedStyle(el).color.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/i); | |
| document.body.removeChild(el); | |
| if (m) c = [+m[1], +m[2], +m[3]]; | |
| } | |
| return c ? rgbToOklch(c[0] / 255, c[1] / 255, c[2] / 255) : null; | |
| } | |
| function isDark(){ return document.documentElement.getAttribute('data-theme') === 'dark'; } | |
| var generators = { | |
| categorical: function(p, n){ | |
| var L0 = Math.min(0.85, Math.max(0.4, p.L)), C0 = Math.min(0.35, Math.max(0.1, p.C || 0.2)); | |
| var out = []; | |
| for (var i = 0; i < n; i++) { | |
| out.push(oklchHex(Math.max(0.4, Math.min(0.85, L0 + ((i % 3) - 1) * 0.04)), C0, (p.h + i * 360 / n) % 360)); | |
| } | |
| return out; | |
| }, | |
| sequential: function(p, n){ | |
| var startL = Math.max(0.25, p.L - 0.18), endL = Math.min(0.92, p.L + 0.18); | |
| var cBase = Math.min(0.33, Math.max(0.08, p.C * 0.9 + 0.06)); | |
| var out = []; | |
| for (var i = 0; i < n; i++) { | |
| var t = n === 1 ? 0 : i / (n - 1); | |
| out.push(oklchHex(startL * (1 - t) + endL * t, cBase * (0.85 + 0.15 * (1 - Math.abs(0.5 - t) * 2)), p.h)); | |
| } | |
| return out; | |
| }, | |
| // Primary on the left, its complement on the right, and a neutral midpoint | |
| // close to the page background so "no change" reads as empty in both themes. | |
| diverging: function(p, n){ | |
| var left = lab(p.L, p.C, p.h); | |
| var right = lab(p.L, Math.min(0.35, Math.max(0.08, p.C)), (p.h + 180) % 360); | |
| var mid = { L: isDark() ? 0.3 : 0.98, a: 0, b: 0 }; | |
| function mix(A, B, t){ return labHex({ L: A.L + (B.L - A.L) * t, a: A.a + (B.a - A.a) * t, b: A.b + (B.b - A.b) * t }); } | |
| var side = n >> 1, out = [], i, t; | |
| for (i = 0; i < side; i++) { t = side <= 1 ? 0 : i / (side - 1); out.push(mix(left, mid, t * 0.9)); } | |
| if (n % 2) out.push(labHex(mid)); | |
| for (i = 0; i < side; i++) { t = side <= 1 ? 1 : (i + 1) / side; out.push(mix(mid, right, Math.max(0.1, t))); } | |
| if (out.length > 1) { out[0] = labHex(left); out[out.length - 1] = labHex(right); } | |
| return out; | |
| } | |
| }; | |
| function luminance(css){ | |
| var m = String(css || '').match(/rgba?\\(([^)]+)\\)/); | |
| var c = m ? m[1].split(',').map(parseFloat) : (/^#[0-9a-f]{6}$/i.test(css) ? rgb(css) : null); | |
| if (!c) return null; | |
| var lin = c.slice(0, 3).map(function(v){ v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }); | |
| return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2]; | |
| } | |
| window.ColorPalettes = { | |
| getColors: function(type, n) { | |
| var gen = generators[type]; | |
| if (!gen) return []; | |
| return gen(primaryOklch(), Math.max(1, Math.min(12, Number(n) || 6))); | |
| }, | |
| getTheme: function() { return isDark() ? 'dark' : 'light'; }, | |
| getPrimary: function() { | |
| return getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '${DEFAULT_PRIMARY_COLOR}'; | |
| }, | |
| refresh: function() {}, | |
| getTextStyleForBackground: function(bg) { | |
| var l = luminance(bg); | |
| return { fill: l != null && l > 0.179 ? '#111111' : '#ffffff' }; | |
| } | |
| }; | |
| })(); | |
| `.trim(); | |
| /** | |
| * Height reporter: | |
| * - Observes documentElement + body (ResizeObserver) to catch all reflows | |
| * - Observes body's subtree (MutationObserver) to catch async chart mounts | |
| * - Throttles via requestAnimationFrame and only posts when delta >= 1px | |
| * - Safety retries at load, +300ms, +1000ms, +3000ms for slow async charts | |
| * - Exposes window.__embedReady(optionalHeight) so charts can opt-in to a | |
| * deterministic "I'm done" signal (useful for CSV fetches > 3s) | |
| */ | |
| const HEIGHT_REPORTER = ` | |
| (function(){ | |
| var lastH = 0; | |
| var scheduled = false; | |
| // IMPORTANT: only measure <body>. document.documentElement.scrollHeight is | |
| // clamped to at least the iframe's viewport height, so it would never allow | |
| // the iframe to shrink (it would always report >= current iframe height). | |
| // body.scrollHeight reflects the actual content height plus body padding. | |
| function measure(){ | |
| var b = document.body; | |
| if (!b) return 0; | |
| // getBoundingClientRect().bottom accounts for padding/margin precisely; | |
| // fall back to scrollHeight if the rect reports 0 (detached layout). | |
| var rectBottom = Math.ceil(b.getBoundingClientRect().bottom); | |
| var scroll = Math.ceil(b.scrollHeight); | |
| // body margin may push the rect down; scrollHeight ignores it. Take the | |
| // max so we never under-report. | |
| return Math.max(rectBottom, scroll); | |
| } | |
| function post(h){ | |
| try { | |
| window.parent.postMessage({ type: 'embedResize', height: h }, '*'); | |
| } catch(e){} | |
| } | |
| function schedule(){ | |
| if (scheduled) return; | |
| scheduled = true; | |
| requestAnimationFrame(function(){ | |
| scheduled = false; | |
| var h = measure(); | |
| if (h > 0 && Math.abs(h - lastH) >= 1) { | |
| lastH = h; | |
| post(h); | |
| } | |
| }); | |
| } | |
| if (typeof ResizeObserver !== 'undefined') { | |
| var ro = new ResizeObserver(schedule); | |
| ro.observe(document.documentElement); | |
| if (document.body) ro.observe(document.body); | |
| } | |
| if (typeof MutationObserver !== 'undefined' && document.body) { | |
| var mo = new MutationObserver(schedule); | |
| mo.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true }); | |
| } | |
| window.addEventListener('load', function(){ | |
| schedule(); | |
| setTimeout(schedule, 300); | |
| setTimeout(schedule, 1000); | |
| setTimeout(schedule, 3000); | |
| }); | |
| // Opt-in explicit ready signal for async charts | |
| window.__embedReady = function(){ | |
| schedule(); | |
| try { window.parent.postMessage({ type: 'embedReady' }, '*'); } catch(e){} | |
| }; | |
| })(); | |
| `.trim(); | |
| /** | |
| * Synchronous pre-paint theme bootstrap. | |
| * | |
| * Runs BEFORE the iframe's own <style> applies, so the first paint already | |
| * uses the correct theme + primary color and the banner/chart never flashes | |
| * from the default (light / DEFAULT_PRIMARY_COLOR) to the user-selected theme. | |
| * | |
| * Strategy (tried in order, first hit wins): | |
| * 1. parent.documentElement[data-theme] + parent's computed --primary-color | |
| * → works in published articles, the editor, and any embed sharing | |
| * origin with its host (we rely on `allow-same-origin` being set). | |
| * 2. localStorage.theme (same origin as parent). | |
| * 3. matchMedia('(prefers-color-scheme: dark)'). | |
| * | |
| * All accesses are wrapped in try/catch: if the iframe is cross-origin or | |
| * sandboxed, we silently fall back to the server-provided defaults baked | |
| * into the srcdoc (`data-theme`, `--primary-color`) and the postMessage | |
| * setTheme path still works as a safety net. | |
| */ | |
| const THEME_BOOTSTRAP = ` | |
| (function(){ | |
| try { | |
| var theme = null; | |
| var primary = null; | |
| // Studio previews pick their own theme (light/dark toggle in the preview | |
| // toolbar), independent of the editor's. | |
| var locked = document.documentElement.hasAttribute('data-theme-locked'); | |
| if (locked) theme = document.documentElement.getAttribute('data-theme'); | |
| try { | |
| var parentDoc = window.parent && window.parent.document; | |
| if (parentDoc) { | |
| if (!locked) theme = parentDoc.documentElement.getAttribute('data-theme') || null; | |
| var pc = getComputedStyle(parentDoc.documentElement).getPropertyValue('--primary-color'); | |
| if (pc) primary = pc.trim(); | |
| } | |
| } catch(e) {} | |
| if (!theme) { | |
| try { theme = window.localStorage && window.localStorage.getItem('theme'); } catch(e) {} | |
| } | |
| // Respect the srcdoc-provided data-theme before falling back to the | |
| // OS preference. Without this, a cross-origin sandbox iframe (e.g. | |
| // an embed-studio preview with sandbox="allow-scripts" but no | |
| // allow-same-origin) can't read the parent and the bootstrap would | |
| // otherwise clobber the explicitly-set initial theme with | |
| // matchMedia's guess. | |
| if (!theme) { | |
| theme = document.documentElement.getAttribute('data-theme') || null; | |
| } | |
| if (!theme) { | |
| theme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; | |
| } | |
| document.documentElement.setAttribute('data-theme', theme); | |
| document.documentElement.style.colorScheme = theme === 'dark' ? 'dark' : 'light'; | |
| if (primary) document.documentElement.style.setProperty('--primary-color', primary); | |
| } catch(e) {} | |
| })(); | |
| `.trim(); | |
| /** | |
| * Theme listener: swap CSS variables via [data-theme] without reloading. | |
| * Dispatches `palettes:updated` (the research-article-template event that | |
| * Embed.mount listens to) and still calls the legacy window.__chartRerender | |
| * hook for charts written before the runtime. | |
| */ | |
| const THEME_LISTENER = ` | |
| (function(){ | |
| function notify(){ | |
| var root = document.documentElement; | |
| try { | |
| document.dispatchEvent(new CustomEvent('palettes:updated', { detail: { | |
| primary: getComputedStyle(root).getPropertyValue('--primary-color').trim(), | |
| theme: root.getAttribute('data-theme') === 'dark' ? 'dark' : 'light' | |
| } })); | |
| } catch(err){} | |
| if (window.__chartRerender) try { window.__chartRerender(); } catch(err){} | |
| } | |
| window.addEventListener('message', function(e){ | |
| if (!e.data) return; | |
| if (e.data.type === 'setTheme') { | |
| document.documentElement.setAttribute('data-theme', e.data.theme); | |
| document.documentElement.style.colorScheme = e.data.theme === 'dark' ? 'dark' : 'light'; | |
| if (e.data.primaryColor) { | |
| document.documentElement.style.setProperty('--primary-color', e.data.primaryColor); | |
| } | |
| notify(); | |
| } else if (e.data.type === 'updatePrimaryColor') { | |
| document.documentElement.style.setProperty('--primary-color', e.data.color); | |
| notify(); | |
| } | |
| }); | |
| })(); | |
| `.trim(); | |
| const BASE_STYLES = ` | |
| :root, [data-theme='light'] { | |
| color-scheme: light; | |
| --text-color: rgba(0,0,0,.85); | |
| --surface-bg: #f9f9f9; | |
| --page-bg: #fff; | |
| --border-color: rgba(0,0,0,.1); | |
| --muted-color: rgba(0,0,0,.6); | |
| --axis-color: rgba(0,0,0,.6); | |
| --tick-color: rgba(0,0,0,.85); | |
| --grid-color: rgba(0,0,0,.08); | |
| } | |
| [data-theme='dark'] { | |
| color-scheme: dark; | |
| --text-color: rgba(255,255,255,.9); | |
| --surface-bg: #07080a; | |
| --page-bg: #0f1115; | |
| --border-color: rgba(255,255,255,.15); | |
| --muted-color: rgba(255,255,255,.7); | |
| --axis-color: rgba(255,255,255,.7); | |
| --tick-color: rgba(255,255,255,.7); | |
| --grid-color: rgba(255,255,255,.10); | |
| } | |
| *, *::before, *::after { box-sizing: border-box; } | |
| /* IMPORTANT: do NOT set min-height:100% on <body>. Doing so creates a | |
| lower bound on scrollHeight equal to the iframe's rendered height, so | |
| the reporter can never signal a smaller height and the iframe can only | |
| ever grow (never shrink when the chart re-renders narrower on resize). */ | |
| html, body { margin: 0; padding: 0; background: transparent; } | |
| body { | |
| color: var(--text-color); | |
| font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', sans-serif; | |
| font-size: 13px; | |
| padding: 16px; | |
| /* overflow: clip clips runaway horizontal content without creating a | |
| scroll container that would trap scroll events or inflate scrollHeight. */ | |
| overflow: clip; | |
| } | |
| /* SVG quirk: text/line/path do not inherit CSS color the way HTML does. | |
| Their default fill/stroke is "black", not "currentColor". A chart | |
| that only sets body color via var(--text-color) would still render | |
| black axes/labels in dark mode. Default everything without its own | |
| fill/stroke to currentColor so the cascaded body color drives the | |
| look. Charts that want a specific colour just set the attribute or | |
| inline style and win by specificity. */ | |
| svg text:not([fill]) { fill: currentColor; } | |
| svg .axis path:not([stroke]), | |
| svg .axis line:not([stroke]), | |
| svg .domain:not([stroke]) { stroke: currentColor; } | |
| svg .grid line:not([stroke]) { stroke: currentColor; opacity: 0.12; } | |
| `.trim(); | |
| /** | |
| * Escape stray `</script>` inside script bodies (e.g. in a JS string) so the | |
| * HTML parser does not end the script early. Each script keeps its own real | |
| * closing tag: the last `</script>` before the next `<script` opening tag. | |
| * Fragments often have several scripts (the `data-embed-config` JSON block | |
| * and the chart script), so only escaping up to the very last closing tag | |
| * would swallow everything after the first one. | |
| */ | |
| export function escapeScriptTags(html: string): string { | |
| const opens = Array.from(html.matchAll(/<script\b[^>]*>/gi)); | |
| if (!opens.length) return html; | |
| let out = html.slice(0, opens[0].index); | |
| opens.forEach((open, k) => { | |
| const bodyStart = open.index! + open[0].length; | |
| const regionEnd = k + 1 < opens.length ? opens[k + 1].index! : html.length; | |
| const region = html.slice(bodyStart, regionEnd); | |
| const close = region.toLowerCase().lastIndexOf("</script>"); | |
| out += open[0]; | |
| if (close === -1) { | |
| out += region; | |
| return; | |
| } | |
| out += region.slice(0, close).replace(/<\/script>/gi, "<\\/script>") + region.slice(close); | |
| }); | |
| return out; | |
| } | |
| export interface BuildEmbedSrcdocOptions { | |
| /** Initial theme, before any setTheme postMessage is received. */ | |
| isDark?: boolean; | |
| /** Initial primary color (CSS color), defaults to DEFAULT_PRIMARY_COLOR. */ | |
| primaryColor?: string; | |
| /** | |
| * Edge-to-edge mode (used for article banners): | |
| * - html/body fill 100% of the iframe viewport | |
| * - no body padding (chart bleeds to the edges) | |
| * - height reporter is skipped (iframe is size-driven by its parent's | |
| * aspect-ratio, not by the chart's scrollHeight) | |
| */ | |
| fullBleed?: boolean; | |
| /** | |
| * Embed Studio preview: relay runtime errors, uncaught exceptions and the | |
| * ready signal to the parent frame (see STUDIO_ERROR_REPORTER). Off for | |
| * published articles. | |
| */ | |
| studio?: boolean; | |
| } | |
| /** | |
| * Stylesheet override applied when `fullBleed` is true. Replaces the | |
| * default body padding and establishes a proper 100%-height chain so | |
| * charts declaring `height: 100%` actually get a measurable height. | |
| */ | |
| const FULL_BLEED_STYLES = ` | |
| html, body { height: 100%; width: 100%; } | |
| body { padding: 0 !important; overflow: hidden; } | |
| body > :first-child { width: 100%; height: 100%; } | |
| `.trim(); | |
| /** | |
| * Build a self-contained HTML document suitable for iframe `srcdoc=`. | |
| * Theme changes after load should be driven via postMessage (`setTheme`) | |
| * rather than rebuilding the srcdoc – otherwise the iframe reloads and loses | |
| * chart state. | |
| */ | |
| export function buildEmbedSrcdoc(htmlFragment: string, opts: BuildEmbedSrcdocOptions = {}): string { | |
| const isDark = !!opts.isDark; | |
| const primaryColor = opts.primaryColor || DEFAULT_PRIMARY_COLOR; | |
| const themeAttr = isDark ? "dark" : "light"; | |
| const inlinePrimary = `:root{--primary-color:${primaryColor};}`; | |
| const fullBleed = !!opts.fullBleed; | |
| const extraStyles = fullBleed ? FULL_BLEED_STYLES : ""; | |
| const parts: string[] = [ | |
| "<!DOCTYPE html>", | |
| `<html data-theme="${themeAttr}"${opts.studio ? " data-theme-locked" : ""}>`, | |
| "<head>", | |
| '<meta charset="UTF-8">', | |
| ...(opts.studio ? [`<script>${STUDIO_ERROR_REPORTER}<\/script>`] : []), | |
| // Pre-paint theme bootstrap MUST come before the <style> block so the | |
| // correct [data-theme] attribute is in place when the default tokens | |
| // cascade applies. Otherwise the iframe flashes from server-default to | |
| // client theme once the postMessage listener kicks in post-load. | |
| `<script>${THEME_BOOTSTRAP}<\/script>`, | |
| `<style>${BASE_STYLES}${inlinePrimary}${extraStyles}</style>`, | |
| `<script>${COLOR_PALETTES_POLYFILL}<\/script>`, | |
| // Classic script in <head> so `Embed.mount` exists while the fragment's | |
| // scripts are parsed. | |
| `<script data-embed-runtime="${EMBED_RUNTIME_VERSION}">${EMBED_RUNTIME_INLINE}<\/script>`, | |
| "</head>", | |
| "<body>", | |
| escapeScriptTags(htmlFragment), | |
| ]; | |
| // Skip the height reporter in fullBleed mode: the iframe is size-driven | |
| // by its parent's aspect-ratio (e.g. the banner 5:2 box) and must not | |
| // try to resize itself based on chart scrollHeight. | |
| if (!fullBleed) { | |
| parts.push(`<script>${HEIGHT_REPORTER}<\/script>`); | |
| } | |
| parts.push(`<script>${THEME_LISTENER}<\/script>`); | |
| if (opts.studio) parts.push(`<script>${STUDIO_INSPECTOR}<\/script>`); | |
| parts.push("</body></html>"); | |
| return parts.join("\n"); | |
| } | |