File size: 18,587 Bytes
4e112fd
 
 
 
4953bfd
4e112fd
4953bfd
1
2
3
4
5
6
7
8
// GENERATED FILE - do not edit by hand.
// Source: backend/embed-kit/embed-runtime.js
// Regenerate with `npm run gen:embed-kit` in backend/.

export const EMBED_RUNTIME_VERSION = "1.2.0";

export const EMBED_RUNTIME_JS = "// Shared runtime for HTML embeds.\n//\n// buildEmbedSrcdoc (src/shared/embed-doc.ts) inlines this file in the <head>\n// of every embed iframe (editor preview, Embed Studio, published article,\n// PDF), so `Embed.mount` exists while embed scripts are being parsed.\n//\n//   <div class=\"d3-my-chart\"></div>\n//   <script>\n//     Embed.mount('d3-my-chart', (ctx) => {\n//       const svg = d3.select(ctx.root).append('svg');\n//       return ({ width, height, theme }) => { /* draw for this size */ };\n//     });\n//   </script>\n//\n// The runtime owns everything that is not the chart itself: finding the\n// container, loading D3, re-rendering on width / theme / palette changes,\n// error display, cleanup, lazy mounting, the ready signal and the\n// accessible description. Data fetching (`ctx.data`) is kept for hosts\n// that serve files; editor iframes inline their data.\n//\n// Source of truth: backend/embed-kit/. Run `npm run gen:embed-kit` in\n// backend/ after editing.\n\n(() => {\n  if (window.Embed && window.Embed.version) return;\n\n  const VERSION = '1.2.0';\n  const D3_URL = 'https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js';\n  const D3_TIMEOUT_MS = 15000;\n  const LAZY_ROOT_MARGIN = '400px 0px';\n  const LABEL_TINT = 0.4;\n  const FALLBACK_CATEGORICAL = ['#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f', '#edc948', '#b07aa1', '#ff9da7', '#9c755f', '#bab0ac'];\n\n  const instances = new Set();\n  const dataCache = new Map();\n  let d3Promise = null;\n  let removalObserver = null;\n\n  const domReady = new Promise((resolve) => {\n    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', resolve, { once: true });\n    else resolve();\n  });\n\n  // Reuses the `#d3-cdn-script` tag so legacy embeds and the runtime never\n  // load D3 twice on the same page.\n  const loadD3 = () => {\n    if (window.d3 && typeof window.d3.select === 'function') return Promise.resolve(window.d3);\n    if (d3Promise) return d3Promise;\n    d3Promise = new Promise((resolve, reject) => {\n      let tag = document.getElementById('d3-cdn-script');\n      if (!tag) {\n        tag = document.createElement('script');\n        tag.id = 'd3-cdn-script';\n        tag.src = Embed.d3Url;\n        document.head.appendChild(tag);\n      }\n      const timer = setTimeout(() => reject(new Error(`D3 did not load within ${D3_TIMEOUT_MS / 1000}s (${tag.src}).`)), D3_TIMEOUT_MS);\n      tag.addEventListener('load', () => {\n        clearTimeout(timer);\n        if (window.d3) resolve(window.d3);\n        else reject(new Error('D3 script loaded but window.d3 is missing.'));\n      }, { once: true });\n      tag.addEventListener('error', () => {\n        clearTimeout(timer);\n        reject(new Error(`Could not load D3 (${tag.src}).`));\n      }, { once: true });\n    }).catch((err) => {\n      d3Promise = null;\n      throw err;\n    });\n    return d3Promise;\n  };\n\n  const DEPENDENCIES = { d3: loadD3 };\n\n  // Any CSS color as an opaque d3 rgb, or null. d3.color cannot parse\n  // oklch(), the format of the article's --primary-color, so fall back to\n  // letting a canvas pixel resolve it.\n  let probe = null;\n  const toRgb = (color) => {\n    const d3 = window.d3;\n    if (!d3 || !color) return null;\n    const c = d3.color(color);\n    if (c) return c.rgb();\n    probe = probe || document.createElement('canvas').getContext('2d', { willReadFrequently: true });\n    if (!probe) return null;\n    probe.clearRect(0, 0, 1, 1);\n    probe.fillStyle = '#010203';\n    probe.fillStyle = String(color);\n    if (probe.fillStyle === '#010203') return null;\n    probe.fillRect(0, 0, 1, 1);\n    const p = probe.getImageData(0, 0, 1, 1).data;\n    return d3.rgb(p[0], p[1], p[2]);\n  };\n\n  // WCAG relative luminance of an opaque color, or null if it cannot be parsed.\n  const luminance = (color) => {\n    const c = toRgb(color);\n    if (!c) return null;\n    const { r, g, b } = c;\n    const lin = (v) => {\n      const s = v / 255;\n      return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n    };\n    return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);\n  };\n\n  const currentTheme = () => (document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light');\n\n  const parseAttribute = (raw) => {\n    if (!raw || !raw.trim()) return null;\n    try { return JSON.parse(raw); } catch (_) { return raw.trim(); }\n  };\n\n  // Bare file names point at the article data folder, like HtmlEmbed's `data` prop.\n  const resolveDataUrl = (file) => (String(file).includes('/') ? String(file) : `${Embed.dataBase}${file}`);\n\n  const parseData = async (url, text) => {\n    const ext = url.split(/[?#]/)[0].split('.').pop().toLowerCase();\n    if (ext === 'json') return JSON.parse(text);\n    if (ext === 'ndjson' || ext === 'jsonl') return text.split('\\n').filter((l) => l.trim()).map((l) => JSON.parse(l));\n    if (ext === 'csv' || ext === 'tsv') {\n      const d3 = await loadD3();\n      return ext === 'csv' ? d3.csvParse(text, d3.autoType) : d3.tsvParse(text, d3.autoType);\n    }\n    return text;\n  };\n\n  const fetchData = (url) => {\n    if (!dataCache.has(url)) {\n      const promise = fetch(url)\n        .then((res) => {\n          if (!res.ok) throw new Error(`Could not load ${url} (HTTP ${res.status}).`);\n          return res.text();\n        })\n        .then((text) => parseData(url, text));\n      promise.catch(() => dataCache.delete(url));\n      dataCache.set(url, promise);\n    }\n    return dataCache.get(url);\n  };\n\n  const showError = (root, message) => {\n    let pre = root.querySelector(':scope > .embed-error');\n    if (!pre) {\n      pre = document.createElement('pre');\n      pre.className = 'embed-error';\n      pre.setAttribute('role', 'alert');\n      Object.assign(pre.style, {\n        margin: '8px 0',\n        padding: '10px 12px',\n        borderRadius: '8px',\n        whiteSpace: 'pre-wrap',\n        fontSize: '12px',\n        color: 'var(--danger-color, #d64545)',\n        border: '1px solid color-mix(in srgb, var(--danger-color, #d64545) 40%, transparent)',\n      });\n      root.appendChild(pre);\n    }\n    pre.textContent = message;\n  };\n\n  const watchRemovals = () => {\n    if (removalObserver || typeof MutationObserver === 'undefined') return;\n    removalObserver = new MutationObserver((records) => {\n      if (!records.some((r) => r.removedNodes.length)) return;\n      instances.forEach((inst) => { if (!inst.root.isConnected) inst.destroy(); });\n    });\n    removalObserver.observe(document.documentElement, { childList: true, subtree: true });\n  };\n\n  // Headless browsers (PDF export, screenshots, the embed checker) and print\n  // must see every embed, so lazy mounting only applies to real visitors.\n  const mustMountEagerly = () => navigator.webdriver || typeof IntersectionObserver === 'undefined';\n\n  // Resolve the container while the embed script is being parsed: this is the\n  // only moment document.currentScript points at it.\n  const findContainer = (rootClass) => {\n    const script = document.currentScript;\n    const sibling = script && script.parentElement\n      ? script.parentElement.querySelector(`:scope > .${CSS.escape(rootClass)}:not([data-mounted])`)\n      : null;\n    return sibling || Array.from(document.querySelectorAll(`.${CSS.escape(rootClass)}:not([data-mounted])`)).pop() || null;\n  };\n\n  // `<script type=\"application/json\" data-embed-config>` sibling of the root:\n  // { key: { type, label, value, ... } }. Returns { key: value }.\n  const declaredConfig = (root) => {\n    const block = root.parentElement\n      ? root.parentElement.querySelector(':scope > script[data-embed-config]')\n      : null;\n    if (!block) return {};\n    try {\n      const fields = JSON.parse(block.textContent || '{}');\n      const values = {};\n      Object.keys(fields || {}).forEach((key) => {\n        const field = fields[key];\n        values[key] = field && typeof field === 'object' && 'value' in field ? field.value : field;\n      });\n      return values;\n    } catch (err) {\n      console.error('[Embed] Invalid data-embed-config JSON:', err);\n      return {};\n    }\n  };\n\n  window.addEventListener('message', (e) => {\n    if (!e.data || e.data.type !== 'embedConfig') return;\n    instances.forEach((inst) => inst.setConfig(e.data.values));\n  });\n\n  function mount(rootClass, setup, options = {}) {\n    const root = options.root || findContainer(rootClass);\n    if (!root) {\n      console.error(`[Embed] No unmounted .${rootClass} element found for this script.`);\n      return null;\n    }\n    root.dataset.mounted = 'true';\n\n    const host = root.closest('[data-config], [data-datafiles]');\n    // Tweakable settings declared next to the root (see \"Tweakable settings\"\n    // in contract.md), overridden by the host's data-config.\n    const hostConfig = parseAttribute(host && host.getAttribute('data-config'));\n    const config = Object.assign(\n      declaredConfig(root),\n      hostConfig && typeof hostConfig === 'object' ? hostConfig : {},\n    );\n    const rawFiles = parseAttribute(host && host.getAttribute('data-datafiles'));\n    const files = (rawFiles == null ? [] : Array.isArray(rawFiles) ? rawFiles : [rawFiles]).map(resolveDataUrl);\n    const deps = options.deps || ['d3'];\n    const resizeMode = options.resize || 'width';\n    const reducedMotion = !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);\n\n    const controller = new AbortController();\n    const cleanups = [];\n    let render = null;\n    let description = null;\n    let pending = false;\n    let lastSize = '';\n    let settled = false;\n    let resolveReady;\n    const ready = new Promise((resolve) => { resolveReady = resolve; });\n\n    const settle = (status, error) => {\n      if (settled) return;\n      settled = true;\n      root.dataset.embedStatus = status;\n      root.dispatchEvent(new CustomEvent(status === 'ready' ? 'embed:ready' : 'embed:error', {\n        bubbles: true,\n        detail: { rootClass, description, error: error ? error.message : null },\n      }));\n      if (typeof window.__embedReady === 'function') {\n        try { window.__embedReady(); } catch (_) {}\n      }\n      resolveReady({ rootClass, status, description, error: error ? error.message : null });\n    };\n\n    const fail = (error) => {\n      const err = error instanceof Error ? error : new Error(String(error));\n      console.error(`[Embed .${rootClass}]`, err);\n      showError(root, err.message);\n      settle('error', err);\n    };\n\n    const applyDescription = () => {\n      if (!description) return;\n      root.dataset.description = description;\n      root.querySelectorAll('svg, canvas').forEach((el) => {\n        if (el.parentElement && el.parentElement.closest('svg')) return;\n        if (!el.hasAttribute('aria-label')) {\n          el.setAttribute('role', 'img');\n          el.setAttribute('aria-label', description);\n        }\n      });\n    };\n\n    const frame = () => ({\n      width: root.clientWidth,\n      height: root.clientHeight,\n      theme: currentTheme(),\n      isDark: currentTheme() === 'dark',\n    });\n\n    const runRender = () => {\n      pending = false;\n      if (!render || controller.signal.aborted) return;\n      try {\n        render(frame());\n        applyDescription();\n        settle('ready');\n      } catch (err) {\n        fail(err);\n      }\n    };\n\n    const schedule = () => {\n      if (pending || !render) return;\n      pending = true;\n      requestAnimationFrame(runRender);\n    };\n\n    const ctx = {\n      root,\n      config,\n      files,\n      reducedMotion,\n      signal: controller.signal,\n      theme: currentTheme,\n      // ctx.data() -> first HtmlEmbed `data` file; ctx.data('x.csv') -> a named\n      // file; ctx.data(true) -> every file. CSV/TSV use d3.autoType.\n      data(which) {\n        if (which === true) return Promise.all(files.map(fetchData));\n        const url = which == null ? files[0] : resolveDataUrl(which);\n        if (!url) return Promise.reject(new Error('This embed expects a data file: pass one with the HtmlEmbed `data` prop.'));\n        return fetchData(url);\n      },\n      colors(kind = 'categorical', count = 8) {\n        const fromPalette = window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function'\n          ? window.ColorPalettes.getColors(kind, count)\n          : null;\n        if (fromPalette && fromPalette.length) return fromPalette;\n        const d3 = window.d3;\n        if (d3 && kind === 'sequential') return d3.quantize(d3.interpolateBlues, count);\n        if (d3 && kind === 'diverging') return d3.quantize(d3.interpolateRdBu, count);\n        return Array.from({ length: count }, (_, i) => FALLBACK_CATEGORICAL[i % FALLBACK_CATEGORICAL.length]);\n      },\n      // Palette colors are tuned for marks; text in that color needs to be\n      // pulled toward the text color to stay readable on both themes.\n      labelColor(color, amount = LABEL_TINT) {\n        const text = getComputedStyle(root).color;\n        const rgb = toRgb(color);\n        return rgb ? window.d3.interpolateRgb(rgb, text)(amount) : color;\n      },\n      // Near-black or white, whichever reads better on a filled mark. Black and\n      // white have equal contrast at luminance ~0.18, not at 0.5.\n      textOn(background) {\n        const l = luminance(background);\n        if (l == null) return 'currentColor';\n        return l > 0.179 ? '#111111' : '#ffffff';\n      },\n      describe(text) {\n        description = String(text);\n        applyDescription();\n      },\n      rerender: schedule,\n      fail,\n      onCleanup(fn) { cleanups.push(fn); },\n      // Animation loop that pauses off-screen and in background tabs, and draws\n      // a single frame when the visitor prefers reduced motion.\n      animate(tick) {\n        let raf = 0;\n        let last = 0;\n        let inView = true;\n        const loop = (t) => {\n          raf = 0;\n          if (controller.signal.aborted) return;\n          const dt = last ? t - last : 16;\n          last = t;\n          try { tick(t, dt); } catch (err) { fail(err); return; }\n          if (!reducedMotion && inView && !document.hidden) raf = requestAnimationFrame(loop);\n        };\n        const start = () => {\n          if (raf || controller.signal.aborted) return;\n          last = 0;\n          raf = requestAnimationFrame(loop);\n        };\n        if (typeof IntersectionObserver !== 'undefined') {\n          const io = new IntersectionObserver(([entry]) => {\n            inView = entry.isIntersecting;\n            if (inView && !reducedMotion) start();\n          });\n          io.observe(root);\n          cleanups.push(() => io.disconnect());\n        }\n        document.addEventListener('visibilitychange', () => { if (!document.hidden && !reducedMotion) start(); }, { signal: controller.signal });\n        cleanups.push(() => cancelAnimationFrame(raf));\n        start();\n      },\n    };\n\n    const instance = {\n      root,\n      rootClass,\n      ready,\n      // Live tweaks from the editor (embedConfig message): same object, so\n      // ctx.config reads the new values on the next render.\n      setConfig(values) {\n        if (!values || typeof values !== 'object') return;\n        Object.assign(config, values);\n        schedule();\n      },\n      destroy() {\n        if (controller.signal.aborted) return;\n        controller.abort();\n        cleanups.splice(0).forEach((fn) => { try { fn(); } catch (_) {} });\n        instances.delete(instance);\n      },\n    };\n    instances.add(instance);\n    watchRemovals();\n\n    const start = async () => {\n      try {\n        await domReady;\n        await Promise.all(deps.map((name) => {\n          if (!DEPENDENCIES[name]) throw new Error(`Unknown embed dependency \"${name}\".`);\n          return DEPENDENCIES[name]();\n        }));\n        const result = await setup(ctx);\n        if (controller.signal.aborted) return;\n        if (typeof result !== 'function') {\n          applyDescription();\n          settle('ready');\n          return;\n        }\n        render = result;\n\n        const observer = new ResizeObserver(() => {\n          const size = resizeMode === 'size' ? `${root.clientWidth}x${root.clientHeight}` : `${root.clientWidth}`;\n          if (size === lastSize) return;\n          lastSize = size;\n          schedule();\n        });\n        observer.observe(root);\n        cleanups.push(() => observer.disconnect());\n        document.addEventListener('palettes:updated', schedule, { signal: controller.signal });\n\n        lastSize = resizeMode === 'size' ? `${root.clientWidth}x${root.clientHeight}` : `${root.clientWidth}`;\n        runRender();\n      } catch (err) {\n        fail(err);\n      }\n    };\n\n    const lazy = options.lazy !== false && !mustMountEagerly();\n    if (!lazy) {\n      start();\n    } else {\n      const io = new IntersectionObserver((entries) => {\n        if (!entries.some((e) => e.isIntersecting)) return;\n        io.disconnect();\n        window.removeEventListener('beforeprint', onPrint);\n        start();\n      }, { rootMargin: LAZY_ROOT_MARGIN });\n      const onPrint = () => {\n        io.disconnect();\n        start();\n      };\n      io.observe(root);\n      window.addEventListener('beforeprint', onPrint, { once: true });\n      cleanups.push(() => {\n        io.disconnect();\n        window.removeEventListener('beforeprint', onPrint);\n      });\n    }\n\n    return instance;\n  }\n\n  // Resolves once every embed mounted so far has rendered or failed.\n  const whenReady = (timeoutMs = 15000) => {\n    const all = Promise.all(Array.from(instances, (inst) => inst.ready));\n    if (!timeoutMs) return all;\n    return Promise.race([\n      all,\n      new Promise((resolve) => setTimeout(() => resolve(Array.from(instances, (inst) => ({\n        rootClass: inst.rootClass,\n        status: inst.root.dataset.embedStatus || 'pending',\n      }))), timeoutMs)),\n    ]);\n  };\n\n  const Embed = {\n    version: VERSION,\n    d3Url: D3_URL,\n    dataBase: '/data/',\n    mount,\n    whenReady,\n    instances: () => Array.from(instances),\n  };\n\n  window.Embed = Embed;\n})();\n";