File size: 19,892 Bytes
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c24ea90
b9e7b9b
 
c24ea90
b9e7b9b
 
 
 
 
c24ea90
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c24ea90
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
c24ea90
b9e7b9b
 
 
 
c24ea90
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
941cf22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9e7b9b
 
 
 
 
 
c59bbe1
 
 
 
 
 
b9e7b9b
c59bbe1
 
 
 
 
 
b9e7b9b
 
 
 
 
 
 
 
c59bbe1
cb92d91
c59bbe1
b9e7b9b
 
c59bbe1
 
cb92d91
b9e7b9b
c59bbe1
 
 
 
 
 
 
 
 
 
 
 
 
cb92d91
 
b9e7b9b
c59bbe1
cb92d91
b9e7b9b
 
 
 
 
 
 
 
 
 
 
03cd478
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
 
 
 
 
 
 
 
 
b6281fd
 
b9e7b9b
 
 
 
 
 
 
03cd478
 
c59bbe1
 
 
03cd478
 
 
 
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
 
b9e7b9b
d61f156
 
b6281fd
 
d61f156
b6281fd
d61f156
 
b6281fd
cb92d91
b9e7b9b
 
 
d61f156
b9e7b9b
 
 
 
 
 
 
 
 
 
 
b6281fd
 
 
 
 
 
 
 
 
 
 
 
d61f156
 
 
 
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
b9e7b9b
 
 
cb92d91
b9e7b9b
 
c59bbe1
b9e7b9b
 
 
 
c59bbe1
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
b9e7b9b
 
c59bbe1
 
 
 
 
0e04b08
 
 
c59bbe1
 
0e04b08
 
 
 
 
 
 
c59bbe1
 
 
b6281fd
 
 
 
 
 
 
c59bbe1
 
 
 
0e04b08
 
 
 
 
 
 
b6281fd
0e04b08
c59bbe1
03cd478
c59bbe1
 
03cd478
c59bbe1
 
 
03cd478
c59bbe1
 
73c8635
 
03cd478
c59bbe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03cd478
0e04b08
03cd478
 
c59bbe1
 
 
 
 
 
 
b9e7b9b
 
c59bbe1
 
 
 
 
 
 
 
 
73c8635
c59bbe1
 
 
 
 
 
 
b9e7b9b
c59bbe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9e7b9b
 
 
 
 
 
 
 
 
1
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
<div class="d3-line" style="width:100%;margin:10px 0;"></div>
<style>
  .d3-line .d3-line__controls select {
    font-size: 12px;
    padding: 8px 28px 8px 10px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background-color: var(--surface-bg);
    color: var(--text-color);
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%230f1115' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 8px center;
    background-size: 12px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    cursor: pointer;
    transition: border-color .15s ease, box-shadow .15s ease;
  }
  [data-theme="dark"] .d3-line .d3-line__controls select {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
  }
  .d3-line .d3-line__controls select:hover {
    border-color: var(--primary-color);
  }
  .d3-line .d3-line__controls select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(232,137,171,.25);
    outline: none;
  }
  .d3-line .d3-line__controls label { gap: 8px; }

  /* Range slider themed with --primary-color */
  .d3-line .d3-line__controls input[type="range"] { 
    -webkit-appearance: none; 
    appearance: none; 
    width: 100%; 
    height: 6px; 
    border-radius: 999px; 
    background: var(--border-color);
    outline: none;
  }
  .d3-line .d3-line__controls input[type="range"]::-webkit-slider-runnable-track {
    height: 6px; 
    background: transparent; 
    border-radius: 999px;
  }
  .d3-line .d3-line__controls input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none; 
    appearance: none; 
    width: 16px; 
    height: 16px; 
    border-radius: 50%; 
    background: var(--primary-color); 
    border: 2px solid var(--on-primary);
    margin-top: -5px; 
    cursor: pointer;
  }
  .d3-line .d3-line__controls input[type="range"]::-moz-range-track {
    height: 6px; 
    background: transparent; 
    border-radius: 999px;
  }
  .d3-line .d3-line__controls input[type="range"]::-moz-range-thumb {
    width: 16px; 
    height: 16px; 
    border-radius: 50%; 
    background: var(--primary-color); 
    border: 2px solid var(--on-primary);
    cursor: pointer;
  }
  /* Improved line color via CSS */
  .d3-line .lines path.improved { stroke: var(--primary-color); }
</style>
<script>
  (() => {
    const ensureD3 = (cb) => {
      if (window.d3 && typeof window.d3.select === 'function') return cb();
      let s = document.getElementById('d3-cdn-script');
      if (!s) {
        s = document.createElement('script');
        s.id = 'd3-cdn-script';
        s.src = 'https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js';
        document.head.appendChild(s);
      }
      const onReady = () => { if (window.d3 && typeof window.d3.select === 'function') cb(); };
      s.addEventListener('load', onReady, { once: true });
      if (window.d3) onReady();
    };

    const bootstrap = () => {
      const scriptEl = document.currentScript;
      let container = null;

      // Prefer the closest previous sibling with class .d3-line (local instance)
      if (scriptEl) {
        let el = scriptEl.previousElementSibling;
        while (el && !(el.classList && el.classList.contains('d3-line'))) {
          el = el.previousElementSibling;
        }
        if (el) container = el;
      }

      // Fallback: pick the last unmounted .d3-line in the document
      if (!container) {
        const candidates = Array.from(document.querySelectorAll('.d3-line'))
          .filter((el) => !(el.dataset && el.dataset.mounted === 'true'));
        container = candidates[candidates.length - 1] || null;
      }

      if (!container) return;
      if (container.dataset) {
        if (container.dataset.mounted === 'true') return;
        container.dataset.mounted = 'true';
      }

      // CSV: prefer public path, fallback to relative
      const CSV_PATHS = [
        '/data/against_baselines.csv',
        './assets/data/against_baselines.csv',
        '../assets/data/against_baselines.csv',
        '../../assets/data/against_baselines.csv'
      ];
      const fetchFirstAvailable = async (paths) => {
        for (const p of paths) {
          try { const r = await fetch(p, { cache: 'no-cache' }); if (r.ok) return await r.text(); } catch(e) {}
        }
        throw new Error('CSV not found: against_baselines.csv');
      };

      // Controls UI
      const controls = document.createElement('div');
      controls.className = 'd3-line__controls';
      Object.assign(controls.style, {
        marginTop: '12px',
        display: 'flex',
        gap: '16px',
        alignItems: 'center',
        justifyContent: 'space-between',
        width: '100%'
      });

      const labelMetric = document.createElement('label');
      Object.assign(labelMetric.style, {
        fontSize: '12px', color: 'var(--muted-color)', display: 'flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap', padding: '6px 10px', marginLeft: 'auto'
      });
      labelMetric.textContent = 'Metric';
      const selectMetric = document.createElement('select');
      Object.assign(selectMetric.style, { fontSize: '12px' });
      labelMetric.appendChild(selectMetric);

      // Inline legend on the right of the select
      const legendInline = document.createElement('div');
      legendInline.className = 'controls__legend';
      Object.assign(legendInline.style, {
        display: 'flex',
        gap: '8px',
        alignItems: 'center',
        flexWrap: 'nowrap',
        fontSize: '11px',
        marginLeft: '8px'
      });
      controls.appendChild(legendInline);
      controls.appendChild(labelMetric);

      // Create SVG
      const svg = d3.select(container).append('svg')
        .attr('width', '100%')
        .style('display', 'block');

      // Groups
      const gRoot = svg.append('g');
      const gGrid = gRoot.append('g').attr('class', 'grid');
      const gAxes = gRoot.append('g').attr('class', 'axes');
      const gLines = gRoot.append('g').attr('class', 'lines');
      const gPoints = gRoot.append('g').attr('class', 'points');
      const gHover = gRoot.append('g').attr('class', 'hover');
      const gLegend = gRoot.append('foreignObject').attr('class', 'legend');

      // Tooltip
      container.style.position = container.style.position || 'relative';
      let tip = container.querySelector('.d3-tooltip');
      let tipInner;
      if (!tip) {
        tip = document.createElement('div');
        tip.className = 'd3-tooltip';
        Object.assign(tip.style, {
          position: 'absolute', top: '0px', left: '0px', transform: 'translate(-9999px, -9999px)', pointerEvents: 'none',
          padding: '8px 10px', borderRadius: '8px', fontSize: '12px', lineHeight: '1.35', border: '1px solid var(--border-color)',
          background: 'var(--surface-bg)', color: 'var(--text-color)', boxShadow: '0 4px 24px rgba(0,0,0,.18)', opacity: '0',
          transition: 'opacity .12s ease'
        });
        tipInner = document.createElement('div');
        tipInner.className = 'd3-tooltip__inner';
        tipInner.style.textAlign = 'left';
        tip.appendChild(tipInner);
        container.appendChild(tip);
      } else {
        tipInner = tip.querySelector('.d3-tooltip__inner') || tip;
      }

      // Colors per run
      const primary = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#E889AB';
      const pool = [primary, '#4EA5B7', '#E38A42', '#CEC0FA', ...(d3.schemeTableau10||[])];

      // State and data
      let metricList = [];
      let runList = [];
      let runOrder = [];
      const dataByMetric = new Map(); // metric => { run => [{step,value}] }
      let isRankStrictFlag = false;
      let rankTickMax = 1;

      // Scales and layout
      let width = 800, height = 360;
      let margin = { top: 16, right: 28, bottom: 56, left: 64 };
      let xScale = d3.scaleLinear();
      let yScale = d3.scaleLinear();

      // Line generators
      const lineGenSmooth = d3.line()
        .curve(d3.curveCatmullRom.alpha(0.05))
        .x((d) => xScale(d.step))
        .y((d) => yScale(d.value));
      const lineGenStep = d3.line()
        .curve(d3.curveStepAfter)
        .x((d) => xScale(d.step))
        .y((d) => yScale(d.value));

      // Hover elements
      const hoverLine = gHover.append('line').attr('stroke-width', 1);

      const overlay = gHover.append('rect').attr('fill', 'transparent').style('cursor', 'crosshair');

      function updateScales() {
        const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
        const axisColor = isDark ? 'rgba(255,255,255,0.25)' : 'rgba(0,0,0,0.25)';
        const tickColor = isDark ? 'rgba(255,255,255,0.70)' : 'rgba(0,0,0,0.55)';
        const gridColor = isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)';

        width = container.clientWidth || 800;
        height = Math.max(260, Math.round(width / 3));
        svg.attr('width', width).attr('height', height);

        const innerWidth = width - margin.left - margin.right;
        const innerHeight = height - margin.top - margin.bottom;
        gRoot.attr('transform', `translate(${margin.left},${margin.top})`);

        xScale.range([0, innerWidth]);
        yScale.range([innerHeight, 0]);

        // Compute Y ticks
        let yTicks = [];
        if (isRankStrictFlag) {
          const maxR = Math.max(1, Math.round(rankTickMax));
          for (let v = 1; v <= maxR; v += 1) yTicks.push(v);
        } else {
          // Use D3's tick generator to produce nice floating-point ticks
          yTicks = yScale.ticks(6);
        }

        // Grid (horizontal)
        gGrid.selectAll('*').remove();
        gGrid.selectAll('line')
          .data(yTicks)
          .join('line')
          .attr('x1', 0)
          .attr('x2', innerWidth)
          .attr('y1', (d) => yScale(d))
          .attr('y2', (d) => yScale(d))
          .attr('stroke', gridColor)
          .attr('stroke-width', 1)
          .attr('shape-rendering', 'crispEdges');

        // Axes
        gAxes.selectAll('*').remove();
        let xAxis = d3.axisBottom(xScale).tickSizeOuter(0);
        if (isRankStrictFlag) {
          const [dx0, dx1] = xScale.domain();
          const start = Math.ceil(dx0 / 1000) * 1000;
          const end = Math.floor(dx1 / 1000) * 1000;
          const xTicks = [];
          for (let v = start; v <= end; v += 1000) xTicks.push(v);
          if (xTicks.length === 0) xTicks.push(Math.round(dx0));
          xAxis = xAxis.tickValues(xTicks).tickFormat(d3.format('d'));
        } else {
          xAxis = xAxis.ticks(8);
        }
        const yAxis = d3.axisLeft(yScale)
          .tickValues(yTicks)
          .tickSizeOuter(0)
          .tickFormat(isRankStrictFlag ? d3.format('d') : d3.format('.2f'));
        gAxes.append('g')
          .attr('transform', `translate(0,${innerHeight})`)
          .call(xAxis)
          .call((g) => {
            g.selectAll('path, line').attr('stroke', axisColor);
            g.selectAll('text').attr('fill', tickColor).style('font-size', '12px');
          });
        gAxes.append('g')
          .call(yAxis)
          .call((g) => {
            g.selectAll('path, line').attr('stroke', axisColor);
            g.selectAll('text').attr('fill', tickColor).style('font-size', '12px');
          });

        // Axis labels (X and Y)
        gAxes.append('text')
          .attr('class', 'axis-label axis-label--x')
          .attr('x', innerWidth / 2)
          .attr('y', innerHeight + 44)
          .attr('text-anchor', 'middle')
          .style('font-size', '12px')
          .style('fill', tickColor)
          .text('Step');
        gAxes.append('text')
          .attr('class', 'axis-label axis-label--y')
          .attr('text-anchor', 'middle')
          .attr('transform', `translate(${-44},${innerHeight/2}) rotate(-90)`) 
          .style('font-size', '12px')
          .style('fill', tickColor)
          .text('Value');

        overlay.attr('x', 0).attr('y', 0).attr('width', innerWidth).attr('height', innerHeight);
        hoverLine.attr('y1', 0).attr('y2', innerHeight).attr('stroke', axisColor);

        // Legend placeholder; actual content set in renderMetric
        const legendWidth = Math.min(180, Math.max(120, Math.round(innerWidth * 0.22)));
        const legendHeight = 64;
        gLegend
          .attr('x', innerWidth - legendWidth + 42)
          .attr('y', innerHeight - legendHeight - 12)
          .attr('width', legendWidth)
          .attr('height', legendHeight);
        const legendRoot = gLegend.selectAll('div').data([0]).join('xhtml:div');
        Object.assign(legendRoot.node().style, {
          background: 'transparent',
          border: 'none',
          borderRadius: '0',
          padding: '0',
          fontSize: '12px',
          lineHeight: '1.35',
          color: 'var(--text-color)'
        });

        return { innerWidth, innerHeight };
      }

      function renderMetric(metricKey){
        const map = dataByMetric.get(metricKey) || {};
        const runs = runOrder;
        // Domain
        let minStep = Infinity, maxStep = -Infinity, maxVal = 0, minVal = Infinity;
        const isRank = /rank/i.test(metricKey);
        const isAverage = /average/i.test(metricKey);
        const isRankStrict = isRank && !isAverage;
        runs.forEach(r => {
          const arr = map[r] || [];
          arr.forEach(pt => {
            const val = isRankStrict ? Math.round(pt.value) : pt.value;
            minStep = Math.min(minStep, pt.step);
            maxStep = Math.max(maxStep, pt.step);
            maxVal = Math.max(maxVal, val);
            minVal = Math.min(minVal, val);
          });
        });
        if (!isFinite(minStep) || !isFinite(maxStep)) { return; }
        xScale.domain([minStep, maxStep]);
        if (isRank) {
          rankTickMax = Math.max(1, Math.round(maxVal));
          yScale.domain([rankTickMax, 1]);
        } else {
          yScale.domain([0, Math.max(1, maxVal)]).nice();
        }
        isRankStrictFlag = isRankStrict;

        const { innerWidth, innerHeight } = updateScales();

        // Bind lines
        const series = runs.map((r, i) => ({
          run: r,
          color: pool[i % pool.length],
          values: (map[r]||[])
            .slice()
            .sort((a,b)=>a.step-b.step)
            .map(pt => isRankStrict ? { step: pt.step, value: Math.round(pt.value) } : pt)
            .filter(pt => !isRankStrict || (pt.step % 1000 === 0))
        }));
        const paths = gLines.selectAll('path.run-line').data(series, d=>d.run);
        const gen = isRank ? lineGenStep : lineGenSmooth;
        paths.enter().append('path').attr('class','run-line').attr('fill','none').attr('stroke-width',2)
          .attr('stroke', d=>d.color).attr('opacity',0.9)
          .attr('d', d=>gen(d.values))
          .merge(paths)
          .transition().duration(200)
          .attr('stroke', d=>d.color)
          .attr('d', d=>gen(d.values));
        paths.exit().remove();

        // No point markers for rank metrics (and none for others)
        gPoints.selectAll('*').remove();

        // Inline legend content (row, right side) compact
        legendInline.innerHTML = series.map(s => `<span style="display:inline-flex;align-items:center;gap:6px;white-space:nowrap;"><span style="width:18px;height:10px;background:${s.color};border-radius:3px;display:inline-block"></span><span>${s.run}</span></span>`).join('');

        // Hover
        const stepSet = new Set(); series.forEach(s=>s.values.forEach(v=>stepSet.add(v.step)));
        const steps = Array.from(stepSet).sort((a,b)=>a-b);
        function onMove(event){
          const [mx, my] = d3.pointer(event, overlay.node());
          const sx = Math.max(steps[0], Math.min(steps[steps.length-1], Math.round(xScale.invert(mx)/1)*1));
          const nearest = steps.reduce((best, s)=> Math.abs(s - xScale.invert(mx)) < Math.abs(best - xScale.invert(mx)) ? s : best, steps[0]);
          const xpx = xScale(nearest);
          hoverLine.attr('x1', xpx).attr('x2', xpx).style('display', null).attr('stroke', 'rgba(0,0,0,0.25)');
          // Tooltip content
          let html = `<div><strong>${metricKey}</strong></div><div><strong>step</strong> ${nearest}</div>`;
          series.forEach(s=>{
            const m = new Map(s.values.map(v=>[v.step, v.value]));
            const val = m.has(nearest) ? m.get(nearest) : null;
            if (val != null) {
              const formatVal = (vv) => (isRankStrict ? d3.format('d')(vv) : (+vv).toFixed(4));
              html += `<div><span style=\"display:inline-block;width:10px;height:10px;background:${s.color};border-radius:50%;margin-right:6px;\"></span><strong>${s.run}</strong> ${formatVal(val)}</div>`;
            }
          });
          tipInner.innerHTML = html;
          const offsetX = 12, offsetY = 12;
          tip.style.opacity = '1'; tip.style.transform = `translate(${Math.round(mx + offsetX + margin.left)}px, ${Math.round(my + offsetY + margin.top)}px)`;
        }
        function onLeave(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; hoverLine.style('display','none'); }
        overlay.on('mousemove', onMove).on('mouseleave', onLeave);
      }

      // (old hover removed; hover is attached in renderMetric)

      // Load CSV and wire controls
      (async () => {
        try {
          const text = await fetchFirstAvailable(CSV_PATHS);
          const rows = d3.csvParse(text, d => ({ run: (d.run||'').trim(), step: +d.step, metric: (d.metric||'').trim(), value: +d.value }));
          metricList = Array.from(new Set(rows.map(r=>r.metric))).sort();
          runList = Array.from(new Set(rows.map(r=>r.run))).sort();
          runOrder = runList;
          // Build dataByMetric
          metricList.forEach(m => {
            const map = {};
            runList.forEach(r => { map[r] = []; });
            rows.filter(r=>r.metric===m).forEach(r => { if (!isNaN(r.step) && !isNaN(r.value)) map[r.run].push({ step:r.step, value:r.value }); });
            dataByMetric.set(m, map);
          });

          // Populate metric select (default to average_rank if present)
          metricList.forEach((m)=>{ const o=document.createElement('option'); o.value=m; o.textContent=m; selectMetric.appendChild(o); });
          const def = metricList.find(m => /average_rank/i.test(m)) || metricList[0];
          if (def) selectMetric.value = def;

          container.appendChild(controls);
          updateScales();
          renderMetric(selectMetric.value);

          selectMetric.addEventListener('change', ()=>{ renderMetric(selectMetric.value); });

          const rerender = () => { renderMetric(selectMetric.value); };
          if (window.ResizeObserver) { const ro = new ResizeObserver(()=>rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); }
        } catch (e) {
          const pre = document.createElement('pre'); pre.textContent = 'CSV load error: ' + (e && e.message ? e.message : e);
          pre.style.color = 'var(--danger, #b00020)'; pre.style.fontSize = '12px'; pre.style.whiteSpace = 'pre-wrap';
          container.appendChild(pre);
        }
      })();
    };

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true });
    } else { ensureD3(bootstrap); }
  })();
</script>