// Shared runtime for HTML embeds. // // buildEmbedSrcdoc (src/shared/embed-doc.ts) inlines this file in the // of every embed iframe (editor preview, Embed Studio, published article, // PDF), so `Embed.mount` exists while embed scripts are being parsed. // //
// // // The runtime owns everything that is not the chart itself: finding the // container, loading D3, re-rendering on width / theme / palette changes, // error display, cleanup, lazy mounting, the ready signal and the // accessible description. Data fetching (`ctx.data`) is kept for hosts // that serve files; editor iframes inline their data. // // Source of truth: backend/embed-kit/. Run `npm run gen:embed-kit` in // backend/ after editing. (() => { if (window.Embed && window.Embed.version) return; const VERSION = '1.2.0'; const D3_URL = 'https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js'; const D3_TIMEOUT_MS = 15000; const LAZY_ROOT_MARGIN = '400px 0px'; const LABEL_TINT = 0.4; const FALLBACK_CATEGORICAL = ['#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f', '#edc948', '#b07aa1', '#ff9da7', '#9c755f', '#bab0ac']; const instances = new Set(); const dataCache = new Map(); let d3Promise = null; let removalObserver = null; const domReady = new Promise((resolve) => { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', resolve, { once: true }); else resolve(); }); // Reuses the `#d3-cdn-script` tag so legacy embeds and the runtime never // load D3 twice on the same page. const loadD3 = () => { if (window.d3 && typeof window.d3.select === 'function') return Promise.resolve(window.d3); if (d3Promise) return d3Promise; d3Promise = new Promise((resolve, reject) => { let tag = document.getElementById('d3-cdn-script'); if (!tag) { tag = document.createElement('script'); tag.id = 'd3-cdn-script'; tag.src = Embed.d3Url; document.head.appendChild(tag); } const timer = setTimeout(() => reject(new Error(`D3 did not load within ${D3_TIMEOUT_MS / 1000}s (${tag.src}).`)), D3_TIMEOUT_MS); tag.addEventListener('load', () => { clearTimeout(timer); if (window.d3) resolve(window.d3); else reject(new Error('D3 script loaded but window.d3 is missing.')); }, { once: true }); tag.addEventListener('error', () => { clearTimeout(timer); reject(new Error(`Could not load D3 (${tag.src}).`)); }, { once: true }); }).catch((err) => { d3Promise = null; throw err; }); return d3Promise; }; const DEPENDENCIES = { d3: loadD3 }; // Any CSS color as an opaque d3 rgb, or null. d3.color cannot parse // oklch(), the format of the article's --primary-color, so fall back to // letting a canvas pixel resolve it. let probe = null; const toRgb = (color) => { const d3 = window.d3; if (!d3 || !color) return null; const c = d3.color(color); if (c) return c.rgb(); probe = probe || document.createElement('canvas').getContext('2d', { willReadFrequently: true }); if (!probe) return null; probe.clearRect(0, 0, 1, 1); probe.fillStyle = '#010203'; probe.fillStyle = String(color); if (probe.fillStyle === '#010203') return null; probe.fillRect(0, 0, 1, 1); const p = probe.getImageData(0, 0, 1, 1).data; return d3.rgb(p[0], p[1], p[2]); }; // WCAG relative luminance of an opaque color, or null if it cannot be parsed. const luminance = (color) => { const c = toRgb(color); if (!c) return null; const { r, g, b } = c; const lin = (v) => { const s = v / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }; return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b); }; const currentTheme = () => (document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light'); const parseAttribute = (raw) => { if (!raw || !raw.trim()) return null; try { return JSON.parse(raw); } catch (_) { return raw.trim(); } }; // Bare file names point at the article data folder, like HtmlEmbed's `data` prop. const resolveDataUrl = (file) => (String(file).includes('/') ? String(file) : `${Embed.dataBase}${file}`); const parseData = async (url, text) => { const ext = url.split(/[?#]/)[0].split('.').pop().toLowerCase(); if (ext === 'json') return JSON.parse(text); if (ext === 'ndjson' || ext === 'jsonl') return text.split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l)); if (ext === 'csv' || ext === 'tsv') { const d3 = await loadD3(); return ext === 'csv' ? d3.csvParse(text, d3.autoType) : d3.tsvParse(text, d3.autoType); } return text; }; const fetchData = (url) => { if (!dataCache.has(url)) { const promise = fetch(url) .then((res) => { if (!res.ok) throw new Error(`Could not load ${url} (HTTP ${res.status}).`); return res.text(); }) .then((text) => parseData(url, text)); promise.catch(() => dataCache.delete(url)); dataCache.set(url, promise); } return dataCache.get(url); }; const showError = (root, message) => { let pre = root.querySelector(':scope > .embed-error'); if (!pre) { pre = document.createElement('pre'); pre.className = 'embed-error'; pre.setAttribute('role', 'alert'); Object.assign(pre.style, { margin: '8px 0', padding: '10px 12px', borderRadius: '8px', whiteSpace: 'pre-wrap', fontSize: '12px', color: 'var(--danger-color, #d64545)', border: '1px solid color-mix(in srgb, var(--danger-color, #d64545) 40%, transparent)', }); root.appendChild(pre); } pre.textContent = message; }; const watchRemovals = () => { if (removalObserver || typeof MutationObserver === 'undefined') return; removalObserver = new MutationObserver((records) => { if (!records.some((r) => r.removedNodes.length)) return; instances.forEach((inst) => { if (!inst.root.isConnected) inst.destroy(); }); }); removalObserver.observe(document.documentElement, { childList: true, subtree: true }); }; // Headless browsers (PDF export, screenshots, the embed checker) and print // must see every embed, so lazy mounting only applies to real visitors. const mustMountEagerly = () => navigator.webdriver || typeof IntersectionObserver === 'undefined'; // Resolve the container while the embed script is being parsed: this is the // only moment document.currentScript points at it. const findContainer = (rootClass) => { const script = document.currentScript; const sibling = script && script.parentElement ? script.parentElement.querySelector(`:scope > .${CSS.escape(rootClass)}:not([data-mounted])`) : null; return sibling || Array.from(document.querySelectorAll(`.${CSS.escape(rootClass)}:not([data-mounted])`)).pop() || null; }; // `