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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
## Resources
|
| 20 |
|
| 21 |
-
- [Hugging Face Spaces Documentation](https://huggingface.co/docs/hub/spaces)
|
| 22 |
-
- [HTML Basics](https://developer.mozilla.org/en-US/docs/Web/HTML)
|
| 23 |
-
- [CSS Basics](https://developer.mozilla.org/en-US/docs/Web/CSS)
|
| 24 |
-
```
|
|
|
|
| 1 |
+
## Embed Chart Authoring Guidelines
|
| 2 |
+
|
| 3 |
+
### Quickstart (TL;DR)
|
| 4 |
+
- Create a single self-contained HTML fragment: root div + scoped style + IIFE script.
|
| 5 |
+
- Draw marks/axes in SVG; render UI (legend and controls) in HTML.
|
| 6 |
+
- Place legend and controls BELOW the chart (header appended after the chart). Include a legend title "Legend" and a select labeled "Metric" when relevant.
|
| 7 |
+
- Load data from public `/data` first, then fall back to `assets/data`.
|
| 8 |
+
- Use `window.ColorPalettes` for colors; stick to CSS variables for theming.
|
| 9 |
+
|
| 10 |
+
Minimal header markup:
|
| 11 |
+
```html
|
| 12 |
+
<div class="legend">
|
| 13 |
+
<div class="legend-title">Legend</div>
|
| 14 |
+
<div class="items"></div>
|
| 15 |
+
<!-- items populated by JS: <span class="item"><span class="swatch"></span><span>Name</span></span> -->
|
| 16 |
+
</div>
|
| 17 |
+
<div class="controls">
|
| 18 |
+
<div class="control-group">
|
| 19 |
+
<label for="metric-select-<id>">Metric</label>
|
| 20 |
+
<select id="metric-select-<id>"></select>
|
| 21 |
+
</div>
|
| 22 |
+
<!-- optional: other controls -->
|
| 23 |
+
</div>
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
See also: `d3-line-simple.html`, `d3-line-quad.html`, `d3-benchmark.html`.
|
| 27 |
+
|
| 28 |
+
Authoring rules for creating a new interactive chart as a single self-contained `.html` file under `src/content/embeds/`. These conventions are derived from `d3-bar.html`, `d3-comparison.html`, `d3-neural.html`, `d3-line.html`, and `d3-pie.html`.
|
| 29 |
+
|
| 30 |
+
### A) Colors & palettes (MANDATORY)
|
| 31 |
+
- Always obtain color arrays from `window.ColorPalettes`; do not hardcode palettes.
|
| 32 |
+
- Use the categorical/sequential/diverging helpers and the current primary color.
|
| 33 |
+
- If you change `--primary-color` dynamically, call `window.ColorPalettes.refresh()` so listeners update.
|
| 34 |
+
|
| 35 |
+
Usage:
|
| 36 |
+
```js
|
| 37 |
+
// Usage (with explicit counts)
|
| 38 |
+
const cat = window.ColorPalettes.getColors('categorical', 8);
|
| 39 |
+
const seq = window.ColorPalettes.getColors('sequential', 8);
|
| 40 |
+
const div = window.ColorPalettes.getColors('diverging', 7);
|
| 41 |
+
|
| 42 |
+
// For current primary color string
|
| 43 |
+
const primaryHex = window.ColorPalettes.getPrimary();
|
| 44 |
+
|
| 45 |
+
// If you change --primary-color dynamically, call refresh to notify listeners
|
| 46 |
+
document.documentElement.style.setProperty('--primary-color', '#6D4AFF');
|
| 47 |
+
window.ColorPalettes.refresh();
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Notes:
|
| 51 |
+
- Keep chart accents (lines, markers, selection) aligned with `--primary-color`.
|
| 52 |
+
- Prefer CSS variables for fills/strokes when possible; derive series colors via `ColorPalettes`.
|
| 53 |
+
- Provide a graceful fallback to CSS variables if `window.ColorPalettes` is unavailable.
|
| 54 |
+
|
| 55 |
+
### B) Layout & form elements (HTML-only)
|
| 56 |
+
- All UI controls (labels, selects, sliders, buttons, toggles) must be plain HTML inside the root container.
|
| 57 |
+
- Do not draw controls with SVG; style them consistently (rounded 8px, custom caret, focus ring).
|
| 58 |
+
- Use `<label>` wrapping inputs for accessibility and concise text (e.g., "Metric", "Model Size").
|
| 59 |
+
- Manage layout with CSS inside the scoped `<style>` for the root class; avoid global rules.
|
| 60 |
+
|
| 61 |
+
### C) SVG scope: charts only; UI in HTML
|
| 62 |
+
- SVG is for chart primitives (marks, axes, gridlines) only.
|
| 63 |
+
- Put legends and controls in HTML (adjacent DOM is preferred; `foreignObject` only if necessary).
|
| 64 |
+
- Tooltips are HTML positioned absolutely inside the root container.
|
| 65 |
+
- Details: see sections 4 (controls), 5 (tooltips), 8 (legends).
|
| 66 |
+
|
| 67 |
+
### 1) File, naming, and structure
|
| 68 |
+
- Name files with a clear prefix and purpose: `d3-<type>.html` (e.g., `d3-scatter.html`).
|
| 69 |
+
- Wrap everything in a single `<div class="<root-class>">`, a `<style>` block scoped to that root class, and a `<script>` IIFE.
|
| 70 |
+
- Do not leak globals; do not attach anything to `window`.
|
| 71 |
+
- Use a unique, descriptive root class (e.g., `.d3-scatter`).
|
| 72 |
+
|
| 73 |
+
Minimal skeleton:
|
| 74 |
+
```html
|
| 75 |
+
<div class="d3-yourchart"></div>
|
| 76 |
+
<style>
|
| 77 |
+
.d3-yourchart {/* all styles scoped to the root */}
|
| 78 |
+
</style>
|
| 79 |
+
<script>
|
| 80 |
+
(() => {
|
| 81 |
+
// Optional dependency loader (e.g., D3)
|
| 82 |
+
const ensureD3 = (cb) => {
|
| 83 |
+
if (window.d3 && typeof window.d3.select === 'function') return cb();
|
| 84 |
+
let s = document.getElementById('d3-cdn-script');
|
| 85 |
+
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); }
|
| 86 |
+
const onReady = () => { if (window.d3 && typeof window.d3.select === 'function') cb(); };
|
| 87 |
+
s.addEventListener('load', onReady, { once: true });
|
| 88 |
+
if (window.d3) onReady();
|
| 89 |
+
};
|
| 90 |
+
|
| 91 |
+
const bootstrap = () => {
|
| 92 |
+
const scriptEl = document.currentScript;
|
| 93 |
+
// Prefer the closest previous sibling with the root class
|
| 94 |
+
let container = scriptEl ? scriptEl.previousElementSibling : null;
|
| 95 |
+
if (!(container && container.classList && container.classList.contains('d3-yourchart'))) {
|
| 96 |
+
// Fallback: pick the last unmounted instance in the page
|
| 97 |
+
const candidates = Array.from(document.querySelectorAll('.d3-yourchart'))
|
| 98 |
+
.filter((el) => !(el.dataset && el.dataset.mounted === 'true'));
|
| 99 |
+
container = candidates[candidates.length - 1] || null;
|
| 100 |
+
}
|
| 101 |
+
if (!container) return;
|
| 102 |
+
if (container.dataset) {
|
| 103 |
+
if (container.dataset.mounted === 'true') return;
|
| 104 |
+
container.dataset.mounted = 'true';
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// Tooltip (optional)
|
| 108 |
+
container.style.position = container.style.position || 'relative';
|
| 109 |
+
let tip = container.querySelector('.d3-tooltip'); let tipInner;
|
| 110 |
+
if (!tip) {
|
| 111 |
+
tip = document.createElement('div'); tip.className = 'd3-tooltip';
|
| 112 |
+
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' });
|
| 113 |
+
tipInner = document.createElement('div'); tipInner.className = 'd3-tooltip__inner'; tipInner.style.textAlign='left'; tip.appendChild(tipInner); container.appendChild(tip);
|
| 114 |
+
} else { tipInner = tip.querySelector('.d3-tooltip__inner') || tip; }
|
| 115 |
+
|
| 116 |
+
// SVG scaffolding (if using D3)
|
| 117 |
+
const svg = d3.select(container).append('svg').attr('width','100%').style('display','block');
|
| 118 |
+
const gRoot = svg.append('g');
|
| 119 |
+
|
| 120 |
+
// State & layout
|
| 121 |
+
let width = 800, height = 360; const margin = { top: 16, right: 28, bottom: 56, left: 64 };
|
| 122 |
+
function updateSize(){
|
| 123 |
+
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
| 124 |
+
width = container.clientWidth || 800;
|
| 125 |
+
height = Math.max(260, Math.round(width / 3));
|
| 126 |
+
svg.attr('width', width).attr('height', height);
|
| 127 |
+
gRoot.attr('transform', `translate(${margin.left},${margin.top})`);
|
| 128 |
+
return { innerWidth: width - margin.left - margin.right, innerHeight: height - margin.top - margin.bottom, isDark };
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
function render(){
|
| 132 |
+
const { innerWidth, innerHeight } = updateSize();
|
| 133 |
+
// ... draw/update your chart here using data joins
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
// Initial render + resize handling
|
| 137 |
+
render();
|
| 138 |
+
const rerender = () => render();
|
| 139 |
+
if (window.ResizeObserver) { const ro = new ResizeObserver(() => rerender()); ro.observe(container); }
|
| 140 |
+
else { window.addEventListener('resize', rerender); }
|
| 141 |
+
};
|
| 142 |
+
|
| 143 |
+
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); }
|
| 144 |
+
else { ensureD3(bootstrap); }
|
| 145 |
+
})();
|
| 146 |
+
</script>
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
### 2) Mounting and re-entrancy
|
| 150 |
+
- Select the closest previous sibling with the root class; fallback to the last unmounted matching element in the document.
|
| 151 |
+
- Gate with `data-mounted` to avoid double-initialization when the fragment re-runs.
|
| 152 |
+
- Assume the chart can appear multiple times on the same page.
|
| 153 |
+
|
| 154 |
+
### 3) Styling and theming
|
| 155 |
+
- Scope all rules under the root class; do not style `body`, `svg` globally.
|
| 156 |
+
- Use CSS variables for theme alignment: `--primary-color`, `--text-color`, `--muted-color`, `--surface-bg`, `--border-color`.
|
| 157 |
+
- Derive palette colors from `window.ColorPalettes` (categorical, sequential, diverging); do not hardcode arrays.
|
| 158 |
+
- For dark mode–aware strokes/ticks, either:
|
| 159 |
+
- Read `document.documentElement.getAttribute('data-theme') === 'dark'`, or
|
| 160 |
+
- Prefer CSS-only where possible.
|
| 161 |
+
- Keep backgrounds light and borders subtle; the outer card frame is handled by `HtmlEmbed.astro`.
|
| 162 |
+
|
| 163 |
+
Standard axis/tick/grid colors (global variables from `_variables.css`):
|
| 164 |
+
|
| 165 |
+
```css
|
| 166 |
+
/* Provided globally */
|
| 167 |
+
:root {
|
| 168 |
+
--axis-color: var(--text-color);
|
| 169 |
+
--tick-color: var(--muted-color);
|
| 170 |
+
--grid-color: rgba(0,0,0,.08);
|
| 171 |
+
}
|
| 172 |
+
[data-theme="dark"] {
|
| 173 |
+
--axis-color: var(--text-color);
|
| 174 |
+
--tick-color: var(--muted-color);
|
| 175 |
+
--grid-color: rgba(255,255,255,.10);
|
| 176 |
+
}
|
| 177 |
+
/* Apply inside charts */
|
| 178 |
+
.your-root-class .axes path,
|
| 179 |
+
.your-root-class .axes line { stroke: var(--axis-color); }
|
| 180 |
+
.your-root-class .axes text { fill: var(--tick-color); }
|
| 181 |
+
.your-root-class .grid line { stroke: var(--grid-color); }
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
#### 3.1) Text on fixed-colored backgrounds
|
| 185 |
+
|
| 186 |
+
- When rendering text over cells/areas with fixed background colors (that do not change with theme), compute a readable text style once from the actual background color.
|
| 187 |
+
- Use `window.ColorPalettes.getTextStyleForBackground(bgCss, { blend: 0.6 })` when available; avoid tying text color to dark mode toggles since the background is constant.
|
| 188 |
+
- Do not re-evaluate on theme toggle unless the background color itself changes.
|
| 189 |
+
|
| 190 |
+
Example:
|
| 191 |
+
```js
|
| 192 |
+
const bg = getComputedStyle(cellRect).fill; // e.g., 'rgb(12, 34, 56)'
|
| 193 |
+
const style = window.ColorPalettes?.getTextStyleForBackground
|
| 194 |
+
? window.ColorPalettes.getTextStyleForBackground(bg, { blend: 0.6 })
|
| 195 |
+
: { fill: 'var(--text-color)' };
|
| 196 |
+
textSel.style('fill', style.fill);
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
### 4) Controls (labels, selects, sliders)
|
| 200 |
+
- Compose controls as plain HTML elements appended inside the root container (no SVG UI).
|
| 201 |
+
- Style selects like in `d3-line.html`/`d3-bar.html` for consistency (rounded 8px, custom caret via data-URI, focus ring).
|
| 202 |
+
- Use `<label>` wrapping the input for accessibility; set concise text (e.g., "Metric", "Model Size").
|
| 203 |
+
|
| 204 |
+
#### 4.1) Required select label: "Metric"
|
| 205 |
+
- When a select is used to switch metrics, include a visible label above the select with the exact text "Metric".
|
| 206 |
+
- Preferred markup (grouped for easy vertical stacking):
|
| 207 |
+
|
| 208 |
+
```html
|
| 209 |
+
<div class="controls">
|
| 210 |
+
<div class="control-group">
|
| 211 |
+
<label for="metric-select-<unique>">Metric</label>
|
| 212 |
+
<select id="metric-select-<unique>"></select>
|
| 213 |
+
</div>
|
| 214 |
+
</div>
|
| 215 |
+
```
|
| 216 |
+
|
| 217 |
+
Minimal CSS (match project styles):
|
| 218 |
|
| 219 |
+
```css
|
| 220 |
+
.controls { display:flex; gap:16px; align-items:center; justify-content:flex-end; flex-wrap:wrap; }
|
| 221 |
+
.controls .control-group { display:flex; flex-direction:column; align-items:flex-start; gap:6px; }
|
| 222 |
+
.controls label { font-size:12px; font-weight:700; color: var(--text-color); }
|
| 223 |
+
.controls select { font-size:12px; padding:8px 28px 8px 10px; border:1px solid var(--border-color); border-radius:8px; background: var(--surface-bg); color: var(--text-color); }
|
| 224 |
+
```
|
| 225 |
|
| 226 |
+
### 5) Tooltip pattern
|
| 227 |
+
- Create a single `.d3-tooltip` absolutely positioned inside the container.
|
| 228 |
+
- Show on hover, hide on leave; position using `d3.pointer(event, container)` plus a small offset.
|
| 229 |
+
- Keep content in a `.d3-tooltip__inner` node; avoid large inner HTML.
|
| 230 |
+
|
| 231 |
+
### 6) Data loading
|
| 232 |
+
- Prefer public assets first, then fall back to content assets:
|
| 233 |
+
- Example CSV paths: `/data/<file>.csv`, then `./assets/data/<file>.csv`, `../assets/data/<file>.csv`, etc.
|
| 234 |
+
- Implement `fetchFirstAvailable(paths)`; try in order with `cache:'no-cache'`; handle errors gracefully with a red `<pre>` message.
|
| 235 |
+
- For images or JSON models, mirror the same approach (see `d3-comparison.html`, `d3-neural.html`).
|
| 236 |
+
|
| 237 |
+
#### 6.1) Data props (HtmlEmbed → embed)
|
| 238 |
+
|
| 239 |
+
- HtmlEmbed accepts an optional `data` prop that can be a string (single file) or an array of strings (multiple files).
|
| 240 |
+
- This prop is passed to the fragment via the `data-datafiles` HTML attribute.
|
| 241 |
+
- In the embed script, read this attribute from the closest ancestor that carries it (the `HtmlEmbed` wrapper), not necessarily the chart’s direct container.
|
| 242 |
+
- Recommended normalization: if a value contains no slash, automatically prefix it with `/data/` to target the public data folder.
|
| 243 |
+
- If `data` is not provided, keep the usual fallback (public, then `assets/data`).
|
| 244 |
+
|
| 245 |
+
Optional configuration (e.g., default metric):
|
| 246 |
+
|
| 247 |
+
```js
|
| 248 |
+
// In HtmlEmbed usage (MDX):
|
| 249 |
+
<HtmlEmbed src="d3-line-simple.html" data="internal_deduplication.csv" config={{ defaultMetric: 'average_rank' }} />
|
| 250 |
+
|
| 251 |
+
// In the embed script (read from closest ancestor):
|
| 252 |
+
let mountEl = container;
|
| 253 |
+
while (mountEl && !mountEl.getAttribute?.('data-datafiles') && !mountEl.getAttribute?.('data-config')) {
|
| 254 |
+
mountEl = mountEl.parentElement;
|
| 255 |
+
}
|
| 256 |
+
let providedConfig = null;
|
| 257 |
+
try {
|
| 258 |
+
const cfg = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-config') : null;
|
| 259 |
+
if (cfg && cfg.trim()) providedConfig = cfg.trim().startsWith('{') ? JSON.parse(cfg) : cfg;
|
| 260 |
+
} catch(_) {}
|
| 261 |
+
// Example: selecting initial metric if present
|
| 262 |
+
const desired = providedConfig && providedConfig.defaultMetric ? String(providedConfig.defaultMetric) : null;
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
Examples (MDX):
|
| 266 |
+
|
| 267 |
+
```mdx
|
| 268 |
+
<HtmlEmbed src="d3-line-simple.html" title="Run A" data="formatting_filters.csv" />
|
| 269 |
+
<HtmlEmbed src="d3-line-simple.html" title="Run B" data="relevance_filters.csv" />
|
| 270 |
+
|
| 271 |
+
<HtmlEmbed
|
| 272 |
+
src="d3-line-simple.html"
|
| 273 |
+
title="Comparison A vs B"
|
| 274 |
+
data={[ 'formatting_filters.csv', 'relevance_filters.csv' ]}
|
| 275 |
+
/>
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
Reading on the embed side (JS):
|
| 279 |
+
|
| 280 |
+
```js
|
| 281 |
+
// Find the closest ancestor that carries the attribute
|
| 282 |
+
let mountEl = container;
|
| 283 |
+
while (mountEl && !mountEl.getAttribute?.('data-datafiles')) {
|
| 284 |
+
mountEl = mountEl.parentElement;
|
| 285 |
+
}
|
| 286 |
+
let providedData = null;
|
| 287 |
+
try {
|
| 288 |
+
const attr = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-datafiles') : null;
|
| 289 |
+
if (attr && attr.trim()) {
|
| 290 |
+
providedData = attr.trim().startsWith('[') ? JSON.parse(attr) : attr.trim();
|
| 291 |
+
}
|
| 292 |
+
} catch(_) {}
|
| 293 |
+
|
| 294 |
+
const DEFAULT_CSV = '/data/formatting_filters.csv';
|
| 295 |
+
const ensureDataPrefix = (p) => (typeof p === 'string' && p && !p.includes('/')) ? `/data/${p}` : p;
|
| 296 |
+
const normalizeInput = (inp) => Array.isArray(inp)
|
| 297 |
+
? inp.map(ensureDataPrefix)
|
| 298 |
+
: (typeof inp === 'string' ? [ ensureDataPrefix(inp) ] : null);
|
| 299 |
+
|
| 300 |
+
const CSV_PATHS = Array.isArray(providedData)
|
| 301 |
+
? normalizeInput(providedData)
|
| 302 |
+
: (typeof providedData === 'string' ? normalizeInput(providedData) || [DEFAULT_CSV] : [
|
| 303 |
+
DEFAULT_CSV,
|
| 304 |
+
'./assets/data/formatting_filters.csv',
|
| 305 |
+
'../assets/data/formatting_filters.csv',
|
| 306 |
+
'../../assets/data/formatting_filters.csv'
|
| 307 |
+
]);
|
| 308 |
+
|
| 309 |
+
const fetchFirstAvailable = async (paths) => {
|
| 310 |
+
for (const p of paths) {
|
| 311 |
+
try {
|
| 312 |
+
const r = await fetch(p, { cache: 'no-cache' });
|
| 313 |
+
if (r.ok) return await r.text();
|
| 314 |
+
} catch(_){}
|
| 315 |
+
}
|
| 316 |
+
throw new Error('CSV not found');
|
| 317 |
+
};
|
| 318 |
+
```
|
| 319 |
+
|
| 320 |
+
### 7) Responsiveness and layout
|
| 321 |
+
- Compute `width = container.clientWidth`, and a height derived from width (e.g., `width / 3`), with a sensible minimum height.
|
| 322 |
+
- Maintain a `margin` object and derive `innerWidth/innerHeight` for plots.
|
| 323 |
+
- Use a `ResizeObserver` on the container; fallback to `window.resize`.
|
| 324 |
+
- Recompute scales/axes/grid on every render.
|
| 325 |
+
|
| 326 |
+
### 8) Legends and labels
|
| 327 |
+
- Prefer HTML for legends for wrapping and accessibility; avoid SVG-based legends.
|
| 328 |
+
- Always add axis labels when applicable (e.g., `Step`, `Value`).
|
| 329 |
+
- Standardize legend swatch size: 14×14px, border-radius 3px, 1px border `var(--border-color)`.
|
| 330 |
+
|
| 331 |
+
#### 8.1) Required legend title: "Legend"
|
| 332 |
+
- Always render a visible title above legend items with the exact text "Legend".
|
| 333 |
+
- Canonical markup:
|
| 334 |
+
|
| 335 |
+
```html
|
| 336 |
+
<div class="legend">
|
| 337 |
+
<div class="legend-title">Legend</div>
|
| 338 |
+
<div class="items">
|
| 339 |
+
<!-- <span class="item"><span class="swatch"></span><span>Series A</span></span> ... -->
|
| 340 |
+
</div>
|
| 341 |
+
</div>
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
Minimal CSS (match project styles):
|
| 345 |
+
|
| 346 |
+
```css
|
| 347 |
+
.legend { display:flex; flex-direction:column; align-items:flex-start; gap:6px; }
|
| 348 |
+
.legend-title { font-size:12px; font-weight:700; color: var(--text-color); }
|
| 349 |
+
.legend .items { display:flex; flex-wrap:wrap; gap:8px 14px; }
|
| 350 |
+
.legend .item { display:inline-flex; align-items:center; gap:6px; white-space:nowrap; font-size:12px; color: var(--text-color); }
|
| 351 |
+
.legend .swatch { width:14px; height:14px; border-radius:3px; border:1px solid var(--border-color); }
|
| 352 |
+
```
|
| 353 |
+
|
| 354 |
+
Recommended JS pattern to (re)build the legend:
|
| 355 |
+
|
| 356 |
+
```js
|
| 357 |
+
function makeLegend(seriesNames, colorFor) {
|
| 358 |
+
let legend = container.querySelector('.legend');
|
| 359 |
+
if (!legend) { legend = document.createElement('div'); legend.className = 'legend'; container.appendChild(legend); }
|
| 360 |
+
let title = legend.querySelector('.legend-title'); if (!title) { title = document.createElement('div'); title.className = 'legend-title'; title.textContent = 'Legend'; legend.appendChild(title); }
|
| 361 |
+
let items = legend.querySelector('.items'); if (!items) { items = document.createElement('div'); items.className = 'items'; legend.appendChild(items); }
|
| 362 |
+
items.innerHTML = '';
|
| 363 |
+
seriesNames.forEach(name => {
|
| 364 |
+
const el = document.createElement('span'); el.className = 'item';
|
| 365 |
+
const sw = document.createElement('span'); sw.className = 'swatch'; sw.style.background = colorFor(name);
|
| 366 |
+
const txt = document.createElement('span'); txt.textContent = name;
|
| 367 |
+
el.appendChild(sw); el.appendChild(txt); items.appendChild(el);
|
| 368 |
+
});
|
| 369 |
+
}
|
| 370 |
+
```
|
| 371 |
+
|
| 372 |
+
### 9) Accessibility
|
| 373 |
+
- Provide `alt` attributes on `<img>` (see `d3-comparison.html`).
|
| 374 |
+
- Provide `aria-label` on interactive buttons (e.g., the erase button in `d3-neural.html`).
|
| 375 |
+
- Ensure focus-visible styles for interactive controls; avoid relying on color alone to encode meaning.
|
| 376 |
+
|
| 377 |
+
### 10) Performance and updates
|
| 378 |
+
- Use D3 data joins (`.data().join()` or explicit enter/merge/exit) and keep transitions short (≤200ms).
|
| 379 |
+
- Recompute only what is necessary on each render; avoid repeated DOM clears if not needed.
|
| 380 |
+
- Debounce or gate expensive computations, especially on `mousemove`.
|
| 381 |
+
|
| 382 |
+
### 11) External dependencies
|
| 383 |
+
- Load D3 (and optional TFJS) via CDN only once using an element id (e.g., `d3-cdn-script`, `tfjs-cdn-script`).
|
| 384 |
+
- After `.load`, verify the expected API (e.g., `window.d3.select`).
|
| 385 |
+
- Prefer pure D3 and built-ins; do not introduce new runtime dependencies unless necessary.
|
| 386 |
+
|
| 387 |
+
### 12) Error handling and fallbacks
|
| 388 |
+
- Fail gracefully: append a small `<pre>` with a readable message inside the container.
|
| 389 |
+
- For optional models (e.g., TFJS), attempt multiple URLs and fall back to a heuristic if load fails.
|
| 390 |
+
|
| 391 |
+
### 13) Printing
|
| 392 |
+
- Favor vector (`svg`) or simple shapes; avoid large bitmap backgrounds.
|
| 393 |
+
- Let `HtmlEmbed.astro` handle most print constraints; ensure the chart scales with width 100% and auto height.
|
| 394 |
+
|
| 395 |
+
### 14) Conventions checklist (before committing)
|
| 396 |
+
- Root class is unique and matches file name (`d3-<type>`).
|
| 397 |
+
- No globals added; script wrapped in an IIFE.
|
| 398 |
+
- `data-mounted` guard is present to avoid double-mount.
|
| 399 |
+
- Colors come from `window.ColorPalettes` (no hardcoded arrays); `--primary-color` respected.
|
| 400 |
+
- Uses CSS variables for colors; dark-mode friendly.
|
| 401 |
+
- Responsive: recomputes layout on resize; uses `ResizeObserver`.
|
| 402 |
+
- Controls are HTML-only, accessible, and consistently styled.
|
| 403 |
+
- Legends and tooltips are HTML, not SVG.
|
| 404 |
+
- Data loading includes public-path-first strategy and graceful error.
|
| 405 |
+
- Axes/labels are legible at small widths.
|
| 406 |
+
- Code is easy to skim: clear naming, early returns, short functions.
|
| 407 |
+
|
| 408 |
+
### 14.1) Agent Checklist (operational)
|
| 409 |
+
- Ensure root: one `<div .d3-xyz>` + scoped `<style>` + IIFE `<script>`
|
| 410 |
+
- Gate mount with `data-mounted` and select closest previous sibling instance
|
| 411 |
+
- Load D3 once via `#d3-cdn-script`; verify `window.d3.select`
|
| 412 |
+
- Colors from `window.ColorPalettes` with CSS variable fallbacks
|
| 413 |
+
- Legend present with visible title “Legend”; HTML-based, not SVG
|
| 414 |
+
- Controls in HTML only; if metric select exists, label text must be “Metric”
|
| 415 |
+
- Tooltip is a single absolute `.d3-tooltip` within the container
|
| 416 |
+
- Data load public-first; implement `fetchFirstAvailable([...])` with `cache:'no-cache'`
|
| 417 |
+
- Read optional HtmlEmbed `data-datafiles` and `data-config` per section 6.1
|
| 418 |
+
- Responsiveness: width from container; `ResizeObserver` fallback to `window.resize`
|
| 419 |
+
- Axis/tick/grid use CSS variables (`--axis-color`, `--tick-color`, `--grid-color`)
|
| 420 |
+
- SVG for marks only; UI/legend/controls in HTML
|
| 421 |
+
- No globals leaked; no external runtime deps besides D3/TFJS when necessary
|
| 422 |
+
- Error path: append small red `<pre>` with a readable message inside container
|
| 423 |
+
- Print-friendly: `svg` width 100%, height responsive, avoid heavy bitmaps
|
| 424 |
+
|
| 425 |
+
### 14.2) Definition of Done (DoD)
|
| 426 |
+
- Implements root structure and mounting guard
|
| 427 |
+
- Uses `ColorPalettes` (with safe fallback) and CSS variables for theming
|
| 428 |
+
- Legend with title “Legend” and consistent swatch style (14×14, r=3, 1px border)
|
| 429 |
+
- Metric select labelled “Metric” when present; accessible markup (`<label for>`)
|
| 430 |
+
- Tooltip works (show on hover, hide on leave, positioned via `d3.pointer`)
|
| 431 |
+
- Public-first data loading + HtmlEmbed prop support when applicable
|
| 432 |
+
- Responsive: resizes smoothly; axes and grid legible at small widths
|
| 433 |
+
- No console errors; graceful error message on load failures
|
| 434 |
+
- File is self‑contained; no globals; lints pass
|
| 435 |
+
|
| 436 |
+
### 14.3) Prompt modèle (for the agent)
|
| 437 |
+
```markdown
|
| 438 |
+
You are implementing a self-contained D3 embed fragment.
|
| 439 |
+
Name: d3-<type>.html (root class .d3-<type>)
|
| 440 |
+
Requirements:
|
| 441 |
+
- One root div + scoped style + IIFE script; no globals
|
| 442 |
+
- UI in HTML (legend+controls), chart primitives in SVG
|
| 443 |
+
- Legend title text exactly “Legend”; swatch 14×14, r=3, 1px border
|
| 444 |
+
- If a select toggles metrics, visible label text exactly “Metric”
|
| 445 |
+
- Colors via window.ColorPalettes (categorical/sequential/diverging), fallback to CSS variables or Tableau10
|
| 446 |
+
- Tooltip: single .d3-tooltip inside container, HTML, positioned via d3.pointer
|
| 447 |
+
- Data loading: try `/data/<file>` first, then `./assets/data/<file>`, `../assets/data/<file>`; implement fetchFirstAvailable(paths)
|
| 448 |
+
- Read optional HtmlEmbed attributes `data-datafiles` and `data-config` if present (see section 6.1)
|
| 449 |
+
- Responsiveness: compute width from container, use ResizeObserver; axis/tick/grid via CSS vars
|
| 450 |
+
- Error handling: append small red <pre> inside container on failure
|
| 451 |
+
Deliver one .html file with only the required elements.
|
| 452 |
+
```
|
| 453 |
|
| 454 |
+
### 15) Example: small bar chart (structure only)
|
| 455 |
+
```html
|
| 456 |
+
<div class="d3-mini-bar"></div>
|
| 457 |
+
<style>
|
| 458 |
+
.d3-mini-bar .bar { stroke: none; }
|
| 459 |
+
</style>
|
| 460 |
+
<script>
|
| 461 |
+
(() => {
|
| 462 |
+
const ensureD3 = (cb) => {
|
| 463 |
+
if (window.d3 && d3.select) return cb();
|
| 464 |
+
let s = document.getElementById('d3-cdn-script');
|
| 465 |
+
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); }
|
| 466 |
+
const onReady = () => { if (window.d3 && d3.select) cb(); };
|
| 467 |
+
s.addEventListener('load', onReady, { once:true }); if (window.d3) onReady();
|
| 468 |
+
};
|
| 469 |
+
const bootstrap = () => {
|
| 470 |
+
const scriptEl = document.currentScript;
|
| 471 |
+
let container = scriptEl ? scriptEl.previousElementSibling : null;
|
| 472 |
+
if (!(container && container.classList && container.classList.contains('d3-mini-bar'))){
|
| 473 |
+
const cs = Array.from(document.querySelectorAll('.d3-mini-bar')).filter(el => !(el.dataset && el.dataset.mounted==='true'));
|
| 474 |
+
container = cs[cs.length-1] || null;
|
| 475 |
+
}
|
| 476 |
+
if (!container) return;
|
| 477 |
+
if (container.dataset){ if (container.dataset.mounted==='true') return; container.dataset.mounted='true'; }
|
| 478 |
|
| 479 |
+
const svg = d3.select(container).append('svg').attr('width','100%').style('display','block');
|
| 480 |
+
const g = svg.append('g');
|
| 481 |
+
let width=800,height=280; const margin={top:16,right:16,bottom:40,left:40};
|
| 482 |
+
const x=d3.scaleBand().padding(0.2), y=d3.scaleLinear();
|
| 483 |
+
const data=[{k:'A',v:3},{k:'B',v:7},{k:'C',v:5}];
|
| 484 |
|
| 485 |
+
function render(){
|
| 486 |
+
width = container.clientWidth || 800; height = Math.max(220, Math.round(width/3.2));
|
| 487 |
+
svg.attr('width', width).attr('height', height);
|
| 488 |
+
g.attr('transform',`translate(${margin.left},${margin.top})`);
|
| 489 |
+
const iw=width-margin.left-margin.right, ih=height-margin.top-margin.bottom;
|
| 490 |
+
x.domain(data.map(d=>d.k)).range([0,iw]); y.domain([0, d3.max(data,d=>d.v)||1]).range([ih,0]).nice();
|
| 491 |
+
const bars=g.selectAll('rect.bar').data(data);
|
| 492 |
+
bars.join('rect').attr('class','bar').attr('x',d=>x(d.k)).attr('y',d=>y(d.v)).attr('width',x.bandwidth()).attr('height',d=>Math.max(0.5, ih - y(d.v))).attr('fill','var(--primary-color)');
|
| 493 |
+
g.selectAll('.x').data([0]).join('g').attr('class','x').attr('transform',`translate(0,${ih})`).call(d3.axisBottom(x));
|
| 494 |
+
g.selectAll('.y').data([0]).join('g').attr('class','y').call(d3.axisLeft(y).ticks(5));
|
| 495 |
+
}
|
| 496 |
+
render();
|
| 497 |
+
const ro = window.ResizeObserver ? new ResizeObserver(() => render()) : null; if (ro) ro.observe(container); else window.addEventListener('resize', render);
|
| 498 |
+
};
|
| 499 |
+
if (document.readyState==='loading'){ document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once:true }); } else { ensureD3(bootstrap); }
|
| 500 |
+
})();
|
| 501 |
+
</script>
|
| 502 |
+
```
|
| 503 |
|
|
|
|
| 504 |
|
|
|
|
|
|
|
|
|
|
|
|