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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Shared runtime for HTML embeds.
//
// buildEmbedSrcdoc (src/shared/embed-doc.ts) inlines this file in the <head>
// of every embed iframe (editor preview, Embed Studio, published article,
// PDF), so `Embed.mount` exists while embed scripts are being parsed.
//
//   <div class="d3-my-chart"></div>
//   <script>
//     Embed.mount('d3-my-chart', (ctx) => {
//       const svg = d3.select(ctx.root).append('svg');
//       return ({ width, height, theme }) => { /* draw for this size */ };
//     });
//   </script>
//
// 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;
  };

  // `<script type="application/json" data-embed-config>` sibling of the root:
  // { key: { type, label, value, ... } }. Returns { key: value }.
  const declaredConfig = (root) => {
    const block = root.parentElement
      ? root.parentElement.querySelector(':scope > script[data-embed-config]')
      : null;
    if (!block) return {};
    try {
      const fields = JSON.parse(block.textContent || '{}');
      const values = {};
      Object.keys(fields || {}).forEach((key) => {
        const field = fields[key];
        values[key] = field && typeof field === 'object' && 'value' in field ? field.value : field;
      });
      return values;
    } catch (err) {
      console.error('[Embed] Invalid data-embed-config JSON:', err);
      return {};
    }
  };

  window.addEventListener('message', (e) => {
    if (!e.data || e.data.type !== 'embedConfig') return;
    instances.forEach((inst) => inst.setConfig(e.data.values));
  });

  function mount(rootClass, setup, options = {}) {
    const root = options.root || findContainer(rootClass);
    if (!root) {
      console.error(`[Embed] No unmounted .${rootClass} element found for this script.`);
      return null;
    }
    root.dataset.mounted = 'true';

    const host = root.closest('[data-config], [data-datafiles]');
    // Tweakable settings declared next to the root (see "Tweakable settings"
    // in contract.md), overridden by the host's data-config.
    const hostConfig = parseAttribute(host && host.getAttribute('data-config'));
    const config = Object.assign(
      declaredConfig(root),
      hostConfig && typeof hostConfig === 'object' ? hostConfig : {},
    );
    const rawFiles = parseAttribute(host && host.getAttribute('data-datafiles'));
    const files = (rawFiles == null ? [] : Array.isArray(rawFiles) ? rawFiles : [rawFiles]).map(resolveDataUrl);
    const deps = options.deps || ['d3'];
    const resizeMode = options.resize || 'width';
    const reducedMotion = !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);

    const controller = new AbortController();
    const cleanups = [];
    let render = null;
    let description = null;
    let pending = false;
    let lastSize = '';
    let settled = false;
    let resolveReady;
    const ready = new Promise((resolve) => { resolveReady = resolve; });

    const settle = (status, error) => {
      if (settled) return;
      settled = true;
      root.dataset.embedStatus = status;
      root.dispatchEvent(new CustomEvent(status === 'ready' ? 'embed:ready' : 'embed:error', {
        bubbles: true,
        detail: { rootClass, description, error: error ? error.message : null },
      }));
      if (typeof window.__embedReady === 'function') {
        try { window.__embedReady(); } catch (_) {}
      }
      resolveReady({ rootClass, status, description, error: error ? error.message : null });
    };

    const fail = (error) => {
      const err = error instanceof Error ? error : new Error(String(error));
      console.error(`[Embed .${rootClass}]`, err);
      showError(root, err.message);
      settle('error', err);
    };

    const applyDescription = () => {
      if (!description) return;
      root.dataset.description = description;
      root.querySelectorAll('svg, canvas').forEach((el) => {
        if (el.parentElement && el.parentElement.closest('svg')) return;
        if (!el.hasAttribute('aria-label')) {
          el.setAttribute('role', 'img');
          el.setAttribute('aria-label', description);
        }
      });
    };

    const frame = () => ({
      width: root.clientWidth,
      height: root.clientHeight,
      theme: currentTheme(),
      isDark: currentTheme() === 'dark',
    });

    const runRender = () => {
      pending = false;
      if (!render || controller.signal.aborted) return;
      try {
        render(frame());
        applyDescription();
        settle('ready');
      } catch (err) {
        fail(err);
      }
    };

    const schedule = () => {
      if (pending || !render) return;
      pending = true;
      requestAnimationFrame(runRender);
    };

    const ctx = {
      root,
      config,
      files,
      reducedMotion,
      signal: controller.signal,
      theme: currentTheme,
      // ctx.data() -> first HtmlEmbed `data` file; ctx.data('x.csv') -> a named
      // file; ctx.data(true) -> every file. CSV/TSV use d3.autoType.
      data(which) {
        if (which === true) return Promise.all(files.map(fetchData));
        const url = which == null ? files[0] : resolveDataUrl(which);
        if (!url) return Promise.reject(new Error('This embed expects a data file: pass one with the HtmlEmbed `data` prop.'));
        return fetchData(url);
      },
      colors(kind = 'categorical', count = 8) {
        const fromPalette = window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function'
          ? window.ColorPalettes.getColors(kind, count)
          : null;
        if (fromPalette && fromPalette.length) return fromPalette;
        const d3 = window.d3;
        if (d3 && kind === 'sequential') return d3.quantize(d3.interpolateBlues, count);
        if (d3 && kind === 'diverging') return d3.quantize(d3.interpolateRdBu, count);
        return Array.from({ length: count }, (_, i) => FALLBACK_CATEGORICAL[i % FALLBACK_CATEGORICAL.length]);
      },
      // Palette colors are tuned for marks; text in that color needs to be
      // pulled toward the text color to stay readable on both themes.
      labelColor(color, amount = LABEL_TINT) {
        const text = getComputedStyle(root).color;
        const rgb = toRgb(color);
        return rgb ? window.d3.interpolateRgb(rgb, text)(amount) : color;
      },
      // Near-black or white, whichever reads better on a filled mark. Black and
      // white have equal contrast at luminance ~0.18, not at 0.5.
      textOn(background) {
        const l = luminance(background);
        if (l == null) return 'currentColor';
        return l > 0.179 ? '#111111' : '#ffffff';
      },
      describe(text) {
        description = String(text);
        applyDescription();
      },
      rerender: schedule,
      fail,
      onCleanup(fn) { cleanups.push(fn); },
      // Animation loop that pauses off-screen and in background tabs, and draws
      // a single frame when the visitor prefers reduced motion.
      animate(tick) {
        let raf = 0;
        let last = 0;
        let inView = true;
        const loop = (t) => {
          raf = 0;
          if (controller.signal.aborted) return;
          const dt = last ? t - last : 16;
          last = t;
          try { tick(t, dt); } catch (err) { fail(err); return; }
          if (!reducedMotion && inView && !document.hidden) raf = requestAnimationFrame(loop);
        };
        const start = () => {
          if (raf || controller.signal.aborted) return;
          last = 0;
          raf = requestAnimationFrame(loop);
        };
        if (typeof IntersectionObserver !== 'undefined') {
          const io = new IntersectionObserver(([entry]) => {
            inView = entry.isIntersecting;
            if (inView && !reducedMotion) start();
          });
          io.observe(root);
          cleanups.push(() => io.disconnect());
        }
        document.addEventListener('visibilitychange', () => { if (!document.hidden && !reducedMotion) start(); }, { signal: controller.signal });
        cleanups.push(() => cancelAnimationFrame(raf));
        start();
      },
    };

    const instance = {
      root,
      rootClass,
      ready,
      // Live tweaks from the editor (embedConfig message): same object, so
      // ctx.config reads the new values on the next render.
      setConfig(values) {
        if (!values || typeof values !== 'object') return;
        Object.assign(config, values);
        schedule();
      },
      destroy() {
        if (controller.signal.aborted) return;
        controller.abort();
        cleanups.splice(0).forEach((fn) => { try { fn(); } catch (_) {} });
        instances.delete(instance);
      },
    };
    instances.add(instance);
    watchRemovals();

    const start = async () => {
      try {
        await domReady;
        await Promise.all(deps.map((name) => {
          if (!DEPENDENCIES[name]) throw new Error(`Unknown embed dependency "${name}".`);
          return DEPENDENCIES[name]();
        }));
        const result = await setup(ctx);
        if (controller.signal.aborted) return;
        if (typeof result !== 'function') {
          applyDescription();
          settle('ready');
          return;
        }
        render = result;

        const observer = new ResizeObserver(() => {
          const size = resizeMode === 'size' ? `${root.clientWidth}x${root.clientHeight}` : `${root.clientWidth}`;
          if (size === lastSize) return;
          lastSize = size;
          schedule();
        });
        observer.observe(root);
        cleanups.push(() => observer.disconnect());
        document.addEventListener('palettes:updated', schedule, { signal: controller.signal });

        lastSize = resizeMode === 'size' ? `${root.clientWidth}x${root.clientHeight}` : `${root.clientWidth}`;
        runRender();
      } catch (err) {
        fail(err);
      }
    };

    const lazy = options.lazy !== false && !mustMountEagerly();
    if (!lazy) {
      start();
    } else {
      const io = new IntersectionObserver((entries) => {
        if (!entries.some((e) => e.isIntersecting)) return;
        io.disconnect();
        window.removeEventListener('beforeprint', onPrint);
        start();
      }, { rootMargin: LAZY_ROOT_MARGIN });
      const onPrint = () => {
        io.disconnect();
        start();
      };
      io.observe(root);
      window.addEventListener('beforeprint', onPrint, { once: true });
      cleanups.push(() => {
        io.disconnect();
        window.removeEventListener('beforeprint', onPrint);
      });
    }

    return instance;
  }

  // Resolves once every embed mounted so far has rendered or failed.
  const whenReady = (timeoutMs = 15000) => {
    const all = Promise.all(Array.from(instances, (inst) => inst.ready));
    if (!timeoutMs) return all;
    return Promise.race([
      all,
      new Promise((resolve) => setTimeout(() => resolve(Array.from(instances, (inst) => ({
        rootClass: inst.rootClass,
        status: inst.root.dataset.embedStatus || 'pending',
      }))), timeoutMs)),
    ]);
  };

  const Embed = {
    version: VERSION,
    d3Url: D3_URL,
    dataBase: '/data/',
    mount,
    whenReady,
    instances: () => Array.from(instances),
  };

  window.Embed = Embed;
})();