thibaud frere commited on
Commit ·
52307d3
1
Parent(s): db576f5
update
Browse filesFiles changed (17)
- Dockerfile+4
- app/.astro/astro/content.d.ts+206
- app/scripts/export-pdf.mjs+17-7
- app/src/components/HtmlEmbed.astro+9
- app/src/content/article.mdx+8-17
- app/src/content/assets/data/finevision.csv → app/src/content/assets/data/vision.csvRenamed
- app/src/content/assets/images/placeholder-wide.pngAdded
- app/src/content/chapters/getting-started.mdx+3-4
- app/src/content/chapters/writing-your-content.mdx+6-14
- app/src/content/embeds/d3-line-old.htmlDeleted
- app/src/content/embeds/d3-pie.html+2-2
- app/src/content/embeds/d3-scatter.htmlDeleted-160
- app/src/content/embeds/original_embeds/d3js/banner.htmlDeleted-244
- app/src/content/embeds/original_embeds/d3js/line.htmlDeleted-356
- app/src/content/embeds/palettes.html-2
- app/src/env.d.tsAdded+1
- app/src/pages/index.astro+2-2
13 unmodified lines14151617181913 unmodified lines# Copy the rest of the application codeCOPY app/ .# Build the applicationRUN npm run build13 unmodified lines1415161718192021222313 unmodified lines# Copy the rest of the application codeCOPY app/ .# Ensure public/data exists inside the container (symlinks won't resolve at build time)RUN mkdir -p public/data && \cp -a src/content/assets/data/. public/data/# Build the applicationRUN npm run build
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206declare module 'astro:content' {interface Render {'.mdx': Promise<{Content: import('astro').MarkdownInstance<{}>['Content'];headings: import('astro').MarkdownHeading[];remarkPluginFrontmatter: Record<string, any>;components: import('astro').MDXInstance<{}>['components'];}>;}}declare module 'astro:content' {interface RenderResult {Content: import('astro/runtime/server/index.js').AstroComponentFactory;headings: import('astro').MarkdownHeading[];remarkPluginFrontmatter: Record<string, any>;}interface Render {'.md': Promise<RenderResult>;}export interface RenderedContent {html: string;metadata?: {imagePaths: Array<string>;[key: string]: unknown;};}}declare module 'astro:content' {type Flatten<T> = T extends { [K: string]: infer U } ? U : never;export type CollectionKey = keyof AnyEntryMap;export type CollectionEntry<C extends CollectionKey> = Flatten<AnyEntryMap[C]>;export type ContentCollectionKey = keyof ContentEntryMap;export type DataCollectionKey = keyof DataEntryMap;type AllValuesOf<T> = T extends any ? T[keyof T] : never;type ValidContentEntrySlug<C extends keyof ContentEntryMap> = AllValuesOf<ContentEntryMap[C]>['slug'];/** @deprecated Use `getEntry` instead. */export function getEntryBySlug<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(collection: C,// Note that this has to accept a regular string too, for SSRentrySlug: E,): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;/** @deprecated Use `getEntry` instead. */export function getDataEntryById<C extends keyof DataEntryMap, E extends keyof DataEntryMap[C]>(collection: C,entryId: E,): Promise<CollectionEntry<C>>;export function getCollection<C extends keyof AnyEntryMap, E extends CollectionEntry<C>>(collection: C,filter?: (entry: CollectionEntry<C>) => entry is E,): Promise<E[]>;export function getCollection<C extends keyof AnyEntryMap>(collection: C,filter?: (entry: CollectionEntry<C>) => unknown,): Promise<CollectionEntry<C>[]>;export function getEntry<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(entry: {collection: C;slug: E;}): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof DataEntryMap,E extends keyof DataEntryMap[C] | (string & {}),>(entry: {collection: C;id: E;}): E extends keyof DataEntryMap[C]? Promise<DataEntryMap[C][E]>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(collection: C,slug: E,): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof DataEntryMap,E extends keyof DataEntryMap[C] | (string & {}),>(collection: C,id: E,): E extends keyof DataEntryMap[C]? Promise<DataEntryMap[C][E]>: Promise<CollectionEntry<C> | undefined>;/** Resolve an array of entry references from the same collection */export function getEntries<C extends keyof ContentEntryMap>(entries: {collection: C;slug: ValidContentEntrySlug<C>;}[],): Promise<CollectionEntry<C>[]>;export function getEntries<C extends keyof DataEntryMap>(entries: {collection: C;id: keyof DataEntryMap[C];}[],): Promise<CollectionEntry<C>[]>;export function render<C extends keyof AnyEntryMap>(entry: AnyEntryMap[C][string],): Promise<RenderResult>;export function reference<C extends keyof AnyEntryMap>(collection: C,): import('astro/zod').ZodEffects<import('astro/zod').ZodString,C extends keyof ContentEntryMap? {collection: C;slug: ValidContentEntrySlug<C>;}: {collection: C;id: keyof DataEntryMap[C];}>;// Allow generic `string` to avoid excessive type errors in the config// if `dev` is not running to update as you edit.// Invalid collection names will be caught at build time.export function reference<C extends string>(collection: C,): import('astro/zod').ZodEffects<import('astro/zod').ZodString, never>;type ReturnTypeOrOriginal<T> = T extends (...args: any[]) => infer R ? R : T;type InferEntrySchema<C extends keyof AnyEntryMap> = import('astro/zod').infer<ReturnTypeOrOriginal<Required<ContentConfig['collections'][C]>['schema']>>;type ContentEntryMap = {"chapters": {"available-blocks.mdx": {id: "available-blocks.mdx";slug: "available-blocks";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"best-pratices.mdx": {id: "best-pratices.mdx";slug: "best-pratices";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"getting-started.mdx": {id: "getting-started.mdx";slug: "getting-started";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"writing-your-content.mdx": {id: "writing-your-content.mdx";slug: "writing-your-content";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };};};type DataEntryMap = {"assets": {"data/mnist-variant-model": {id: "data/mnist-variant-model";collection: "assets";data: any};};"embeds": Record<string, {id: string;collection: "embeds";data: any;}>;};type AnyEntryMap = ContentEntryMap & DataEntryMap;export type ContentConfig = never;}
164 unmodified lines16516616716816917017132 unmodified lines204205206207208209210211212213214215216217164 unmodified linesconst margin = parseMargin(args.margin);const wait = (args.wait || 'full'); // 'networkidle' | 'images' | 'plotly' | 'full'// filename can be provided, else computed from page title laterlet outFileBase = (args.filename && String(args.filename).replace(/\.pdf$/i, '')) || 'article';console.log('> Building Astro site…');32 unmodified lines// Give time for CDN scripts (Plotly/D3) to attach and for our fragment hooks to runtry { await page.waitForFunction(() => !!window.Plotly, { timeout: 8000 }); } catch {}try { await page.waitForFunction(() => !!window.d3, { timeout: 8000 }); } catch {}// Compute slug from title if neededif (!args.filename) {const title = await page.evaluate(() => {const h1 = document.querySelector('h1.hero-title');const t = h1 ? h1.textContent : document.title;return (t || '').replace(/\s+/g, ' ').trim();});outFileBase = slugify(title);}// Wait for render readiness164 unmodified lines16516616716816917017132 unmodified lines204205206207208209210211212213214215216217218219220221222223224225226227164 unmodified linesconst margin = parseMargin(args.margin);const wait = (args.wait || 'full'); // 'networkidle' | 'images' | 'plotly' | 'full'// filename can be provided, else computed from DOM (button) or page title laterlet outFileBase = (args.filename && String(args.filename).replace(/\.pdf$/i, '')) || 'article';console.log('> Building Astro site…');32 unmodified lines// Give time for CDN scripts (Plotly/D3) to attach and for our fragment hooks to runtry { await page.waitForFunction(() => !!window.Plotly, { timeout: 8000 }); } catch {}try { await page.waitForFunction(() => !!window.d3, { timeout: 8000 }); } catch {}// Prefer explicit filename from the download button if presentif (!args.filename) {const fromBtn = await page.evaluate(() => {const btn = document.getElementById('download-pdf-btn');const f = btn ? btn.getAttribute('data-pdf-filename') : null;return f || '';});if (fromBtn) {outFileBase = String(fromBtn).replace(/\.pdf$/i, '');} else {// Fallback: compute slug from hero title or document.titleconst title = await page.evaluate(() => {const h1 = document.querySelector('h1.hero-title');const t = h1 ? h1.textContent : document.title;return (t || '').replace(/\s+/g, ' ').trim();});outFileBase = slugify(title);}}// Wait for render readiness
91 unmodified lines92939495969791 unmodified lines@media (prefers-color-scheme: dark) {[data-theme="dark"] .html-embed__card:not(.is-frameless) { background: #12151b; border-color: rgba(255,255,255,.15); }}@media print {.html-embed, .html-embed__card { break-inside: avoid; page-break-inside: avoid; }}91 unmodified lines929394959697989910010110210310410510691 unmodified lines@media (prefers-color-scheme: dark) {[data-theme="dark"] .html-embed__card:not(.is-frameless) { background: #12151b; border-color: rgba(255,255,255,.15); }}@media print {.html-embed, .html-embed__card { max-width: 100% !important; width: 100% !important; margin-left: 0 !important; margin-right: 0 !important; }.html-embed__card { padding: 6px; }.html-embed__card.is-frameless { padding: 0; }.html-embed__card svg,.html-embed__card canvas,.html-embed__card img { max-width: 100% !important; height: auto !important; }.html-embed__card > div[id^="frag-"] { width: 100% !important; }}@media print {.html-embed, .html-embed__card { break-inside: avoid; page-break-inside: avoid; }}
29 unmodified lines30313233343536373839404142434427 unmodified lines72737475767778798081828384858616 unmodified lines10310410510610710810911029 unmodified linesimport GettingStarted from "./chapters/getting-started.mdx";<Sidenote>Welcome to this single-page research article template.It’s designed to help you write clear, modern, and **interactive** technical articles with **minimal setup**.Whether you cover machine learning, data science, physics, or software topics, this template keeps the authoring flow simple while offering robust features out of the box.<Fragment slot="aside">Reading time: 20–25 minutes.</Fragment>In this guide, you’ll learn how to install the template,write content (math, citations, images, code, sidenotes, interactive fragments),customize styles and behavior, and follow a few **best practices** for publishing.</Sidenote>27 unmodified lines</Sidenote>## IntroductionThe web enables forms of explanation that static PDFs cannot: **reactive diagrams**, progressive notation, and **exploratory views** that reveal how ideas behave. Use **interactive fragments** to let readers hover, scrub, and inspect—building **intuition**, not just reading results.Careful notation, **well‑chosen visual encodings**, and **small interactive experiments** deepen understanding. By making these artifacts **first‑class**—alongside text, math, and code—this template helps your audience grasp mechanisms, limits, and trade‑offs.Clear, **inspectable examples** make methods safer and more comprehensible. Embed live widgets, reveal **intermediate states**, and link to sources so readers can verify claims and **reproduce results**.Not every contribution fits a PDF. Treat demos, visualizations, and interactive write‑ups as **real scholarship**: cite them, version them, and ship them together.This project is heavely inspired by [**Distill**](https://distill.pub) (2016–2021), which championed clear, web‑native scholarship.{/* ### Notable examples of excellent scientific articles16 unmodified lines<BestPractices />## ConclusionThis template provides a **practical baseline** for writing and sharing technical articles with **math**, **citations**, and **interactive figures**. **Start simple**, **iterate** on structure and style, and keep content **maintainable** for future readers and collaborators.29 unmodified lines3031323334353637383940414227 unmodified lines7071727374757677787980818216 unmodified lines9910010129 unmodified linesimport GettingStarted from "./chapters/getting-started.mdx";<Sidenote>Welcome to this single‑page research article template. It helps you publish **clear**, **modern**, and **interactive** technical writing with **minimal setup**. Grounded in **web‑native scholarship**, it favors **interactive explanations**, careful notation, and **inspectable examples** over static snapshots.It offers a **ready‑to‑publish, all‑in‑one workflow** so you can **focus on ideas** rather than infrastructure.<Fragment slot="aside">Reading time: 20–25 minutes.</Fragment>Use it as a **practical baseline**: **start simple**, **iterate** on structure and style, and keep content **maintainable** for future readers and collaborators.</Sidenote>27 unmodified lines</Sidenote>## IntroductionThe web enables explanations that static PDFs cannot: **reactive diagrams**, **progressive notation**, and **exploratory views** that show how ideas behave. Use **interactive fragments** so readers can **hover**, **scrub**, and **inspect**—building **intuition**, not just reading results.Careful notation, **thoughtful visual encodings**, and **small, manipulable experiments** deepen understanding. By making these artifacts **first‑class** alongside **text, math, and code**, this template helps readers grasp **mechanisms, limits, and trade‑offs**.Not every contribution fits a PDF. Treat demos, visualizations, and interactive write‑ups as **scholarship**: **cite** them, **version** them, and **ship** them with clear, **inspectable examples** that expose **intermediate states** and link to sources so readers can **verify** claims and **reproduce** results.This project is heavily inspired by [**Distill**](https://distill.pub) (2016–2021), which championed clear, web‑native scholarship.{/* ### Notable examples of excellent scientific articles16 unmodified lines<BestPractices />
11 unmodified lines121314151617189 unmodified lines28293031323334353611 unmodified linesnpm install```<Fragment slot="aside">You can also use yarn.</Fragment></Sidenote>9 unmodified lines```bashnpm run build```Serving the `dist/` directory on any static host is enough to deliver the site.A [slug-title].pdf and thumb.jpg are also generated at build time. You can find them in the public folder.### Deploy11 unmodified lines121314151617189 unmodified lines282930313233343511 unmodified linesnpm install```<Fragment slot="aside">Alternatively, you can use **Yarn** as your package manager.</Fragment></Sidenote>9 unmodified lines```bashnpm run build```<small className="muted">Serving the `dist/` directory on any static host is enough to deliver the site.</small><br/><br/>A [slug-title].pdf and thumb.jpg are also generated at build time. You can find them in the public folder.### Deploy
35 unmodified lines3637383940414278 unmodified lines12112212312412512612712812913013113213313413513613713813935 unmodified linestags:- research- templateogImage: "https://example.com/your-og-image.png"---{/* IMPORTS */}78 unmodified linesHere is a suggestion of **color palettes** for your **data visualizations** that align with your **brand identity**. These palettes are generated from your `--primary-color`.<HtmlEmbed frameless src="palettes.html" />### EmbedsUse HTML fragments to embed interactive charts and widgets. Place your fragments under `app/src/content/embeds/` and reference them via the `HtmlEmbed` component.<small className="muted">Example</small>```mdximport HtmlEmbed from '../components/HtmlEmbed.astro'<HtmlEmbed src="d3-line.html" title="D3 Line" desc="Simple time series" />```### Placement35 unmodified lines363738394041424378 unmodified lines12212312412512612712812913013135 unmodified linestags:- research- template{/* Optional override of the default Open Graph image */}ogImage: "https://override-example.com/your-og-image.png"---{/* IMPORTS */}78 unmodified linesHere is a suggestion of **color palettes** for your **data visualizations** that align with your **brand identity**. These palettes are generated from your `--primary-color`.<HtmlEmbed frameless src="palettes.html" /><br/>**Use color with care.**Color should rarely be the only channel of meaning.Always pair it with text, icons, shape or position. The simulation helps you spot palettes and states that become indistinguishable for people with color‑vision deficiencies.### Placement
53 unmodified lines545556575859603 unmodified lines6465666768697053 unmodified lines// CSV: load from public pathconst CSV_PATHS = ['/data/finevision.csv'];const fetchFirstAvailable = async (paths) => {3 unmodified linesif (res.ok) { return await res.text(); }} catch (_) { /* try next */ }}throw new Error('CSV not found: finevision.csv');};const parseCsv = (text) => d3.csvParse(text, (d) => ({53 unmodified lines545556575859603 unmodified lines6465666768697053 unmodified lines// CSV: load from public pathconst CSV_PATHS = ['/data/vision.csv'];const fetchFirstAvailable = async (paths) => {3 unmodified linesif (res.ok) { return await res.text(); }} catch (_) { /* try next */ }}throw new Error('CSV not found: vision.csv');};const parseCsv = (text) => d3.csvParse(text, (d) => ({
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160<div class="d3-scatter" style="width:100%;margin:10px 0;"></div><style> .d3-scatter .controls { margin-top: 12px; display: flex; gap: 16px; align-items: center; flex-wrap: wrap; } .d3-scatter .controls label { font-size: 12px; color: var(--muted-color); display: flex; align-items: center; gap: 8px; white-space: nowrap; padding: 6px 10px; } .d3-scatter .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-scatter .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-scatter .point { opacity: .9; } .d3-scatter .point:hover { opacity: 1; }</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 mount = document.currentScript ? document.currentScript.previousElementSibling : null; const container = (mount && mount.querySelector && mount.querySelector('.d3-scatter')) || document.querySelector('.d3-scatter'); if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// Try multiple paths: prefer public path then relative copies under content assets const JSON_PATHS = [ '/data/data.json', './assets/data/data.json', '../assets/data/data.json', '../../assets/data/data.json' ]; const fetchFirstAvailable = async (paths) => { for (const p of paths) { try { const r = await fetch(p, { cache: 'no-cache' }); if (r.ok) return await r.json(); } catch(e) {} } throw new Error('JSON not found: data.json'); };
// SVG scaffolding const svg = d3.select(container).append('svg').attr('width','100%').style('display','block'); const gRoot = svg.append('g'); const gGrid = gRoot.append('g').attr('class','grid'); const gAxes = gRoot.append('g').attr('class','axes'); const gPoints = gRoot.append('g').attr('class','points'); const gHover = gRoot.append('g').attr('class','hover');
// 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; }
// Layout & scales let width=800, height=360; const margin = { top: 16, right: 28, bottom: 56, left: 64 }; const x = d3.scaleLinear(); const y = d3.scaleLinear(); const color = d3.scaleOrdinal(d3.schemeTableau10);
const overlay = gHover.append('rect').attr('fill', 'transparent').style('cursor', 'crosshair');
function updateScales(domainX, domainY){ 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})`);
x.domain(domainX).range([0, innerWidth]).nice(); y.domain(domainY).range([innerHeight, 0]).nice();
// Grid gGrid.selectAll('*').remove(); gGrid.selectAll('line').data(y.ticks(6)).join('line') .attr('x1', 0).attr('x2', innerWidth).attr('y1', (d)=>y(d)).attr('y2', (d)=>y(d)) .attr('stroke', gridColor).attr('stroke-width', 1).attr('shape-rendering', 'crispEdges');
// Axes gAxes.selectAll('*').remove(); gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(x).ticks(8)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); }); gAxes.append('g').call(d3.axisLeft(y).ticks(6)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); });
// Axis labels 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('x'); gAxes.append('text').attr('class','axis-label axis-label--y').attr('text-anchor','middle').attr('transform', `translate(${-36},${innerHeight/2}) rotate(-90)`).style('font-size','12px').style('fill', tickColor).text('y');
overlay.attr('x', 0).attr('y', 0).attr('width', innerWidth).attr('height', innerHeight);
return { innerWidth, innerHeight }; }
function normalizeData(raw){ // Accepts: [{x,y,label?}] or [[x,y,label?]] or objects with other keys (will try first two numeric fields) const out = []; if (Array.isArray(raw)) { raw.forEach((row) => { if (row == null) return; if (Array.isArray(row)) { const x = +row[0]; const y = +row[1]; const label = row.length > 2 ? row[2] : undefined; if (Number.isFinite(x) && Number.isFinite(y)) out.push({ x, y, label }); } else if (typeof row === 'object') { if ('x' in row && 'y' in row) { const x = +row.x; const y = +row.y; const label = row.label; if (Number.isFinite(x) && Number.isFinite(y)) out.push({ x, y, label }); } else { const vals = Object.values(row).filter(v => typeof v === 'number' || (typeof v === 'string' && v.trim() !== '')); const nums = vals.map(v => +v).filter(Number.isFinite); if (nums.length >= 2) { out.push({ x: nums[0], y: nums[1], label: vals.length > 2 ? vals[2] : undefined }); } } } }); } return out; }
function render(points){ if (!points || points.length === 0) { gPoints.selectAll('*').remove(); return; } const xExtent = d3.extent(points, d=>d.x); const yExtent = d3.extent(points, d=>d.y); updateScales(xExtent, yExtent);
const sel = gPoints.selectAll('circle.point').data(points); sel.enter().append('circle').attr('class','point') .attr('r', 3) .attr('cx', d=>x(d.x)) .attr('cy', d=>y(d.y)) .attr('fill', d=> d.label != null ? color(d.label) : 'var(--primary-color)') .on('mouseenter', function(ev, d){ tipInner.innerHTML = `<div><strong>x</strong> ${(+d.x).toFixed(4)}</div><div><strong>y</strong> ${(+d.y).toFixed(4)}</div>${d.label!=null?`<div><strong>label</strong> ${d.label}</div>`:''}`; tip.style.opacity = '1'; }) .on('mousemove', function(ev){ const [mx,my] = d3.pointer(ev, container); const offsetX=12, offsetY=12; tip.style.transform = `translate(${Math.round(mx+offsetX)}px, ${Math.round(my+offsetY)}px)`; }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; }) .merge(sel) .attr('cx', d=>x(d.x)) .attr('cy', d=>y(d.y)) .attr('fill', d=> d.label != null ? color(d.label) : 'var(--primary-color)'); sel.exit().remove(); }
(async () => { try { const raw = await fetchFirstAvailable(JSON_PATHS); const points = normalizeData(raw); render(points); const rerender = () => { render(points); }; 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 = 'JSON 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>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244<div class="d3-galaxy" style="width:100%;margin:10px 0;"></div><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 mount = document.currentScript ? document.currentScript.previousElementSibling : null; const container = (mount && mount.querySelector && mount.querySelector('.d3-galaxy')) || document.querySelector('.d3-galaxy'); if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; } // Scene params (match previous Plotly ranges) const cx = 1.5, cy = 0.5; const a = 1.3, b = 0.45; const numPoints = 3000; const numArms = 3; const numTurns = 2.1; const angleJitter = 0.12; const posNoise = 0.015;
// Generate spiral + bulge const twoPi = Math.PI * 2; const t = Float64Array.from({ length: numPoints }, () => Math.random() * (twoPi * numTurns)); const armIndices = Int16Array.from({ length: numPoints }, () => Math.floor(Math.random() * numArms)); const armOffsets = Float64Array.from(armIndices, (k) => k * (twoPi / numArms)); const theta = Float64Array.from(t, (tv, i) => tv + armOffsets[i] + d3.randomNormal.source(Math.random)(0, angleJitter)()); const rNorm = Float64Array.from(t, (tv) => Math.pow(tv / (twoPi * numTurns), 0.9)); const noiseScale = (rn) => posNoise * (0.8 + 0.6 * rn); const noiseX = Float64Array.from(rNorm, (rn) => d3.randomNormal.source(Math.random)(0, noiseScale(rn))()); const noiseY = Float64Array.from(rNorm, (rn) => d3.randomNormal.source(Math.random)(0, noiseScale(rn))());
const xSpiral = Float64Array.from(theta, (th, i) => cx + a * rNorm[i] * Math.cos(th) + noiseX[i]); const ySpiral = Float64Array.from(theta, (th, i) => cy + b * rNorm[i] * Math.sin(th) + noiseY[i]);
const bulgePoints = Math.floor(0.18 * numPoints); const phiB = Float64Array.from({ length: bulgePoints }, () => twoPi * Math.random()); const rB = Float64Array.from({ length: bulgePoints }, () => Math.pow(Math.random(), 2.2) * 0.22); const noiseXB = Float64Array.from({ length: bulgePoints }, () => d3.randomNormal.source(Math.random)(0, posNoise * 0.6)()); const noiseYB = Float64Array.from({ length: bulgePoints }, () => d3.randomNormal.source(Math.random)(0, posNoise * 0.6)()); const xBulge = Float64Array.from(phiB, (ph, i) => cx + a * rB[i] * Math.cos(ph) + noiseXB[i]); const yBulge = Float64Array.from(phiB, (ph, i) => cy + b * rB[i] * Math.sin(ph) + noiseYB[i]);
// Concatenate const X = Array.from(xSpiral).concat(Array.from(xBulge)); const Y = Array.from(ySpiral).concat(Array.from(yBulge)); const lenSpiral = xSpiral.length;
const zSpiral = Array.from(rNorm, (rn) => 1 - rn); const maxRB = rB && rB.length ? (window.d3 && d3.max ? d3.max(rB) : Math.max.apply(null, Array.from(rB))) : 1; const zBulge = Array.from(rB, (rb) => 1 - (maxRB ? rb / maxRB : 0)); const Zraw = zSpiral.concat(zBulge); const sizesPx = Zraw.map((z) => (z + 1) * 5); // 5..10 px (diameter)
// Labels (same categories as Python version) const labelOf = (i) => { const z = Zraw[i]; if (z < 0.25) return 'smol dot'; if (z < 0.5) return 'ok-ish dot'; if (z < 0.75) return 'a dot'; return 'biiig dot'; };
// Sort by size ascending for z-index: small first, big last const idx = d3.range(X.length).sort((i, j) => sizesPx[i] - sizesPx[j]);
// Colors: piecewise gradient [0 -> 0.5 -> 1] const c0 = d3.rgb(78, 165, 183); // rgb(78, 165, 183) const c1 = d3.rgb(206, 192, 250); // rgb(206, 192, 250) const c2 = d3.rgb(232, 137, 171); // rgb(232, 137, 171) const interp01 = d3.interpolateRgb(c0, c1); const interp12 = d3.interpolateRgb(c1, c2); const colorFor = (v) => { const t = Math.max(0, Math.min(1, v)); return t <= 0.5 ? interp01(t / 0.5) : interp12((t - 0.5) / 0.5); };
// Create SVG const svg = d3.select(container).append('svg') .attr('width', '100%') .style('display', 'block');
const render = () => { const width = container.clientWidth || 800; const height = Math.max(260, Math.round(width / 3)); // keep ~3:1, min height svg.attr('width', width).attr('height', height);
const xScale = d3.scaleLinear().domain([0, 3]).range([0, width]); const yScale = d3.scaleLinear().domain([0, 1]).range([height, 0]);
// Subtle stroke color depending on theme const isDark = document.documentElement.getAttribute('data-theme') === 'dark'; const strokeColor = isDark ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.12)';
// Background rect using gradient const bg = svg.selectAll('rect.d3-bg').data([0]); bg.join('rect') .attr('class', 'd3-bg') .attr('x', 0) .attr('y', 0) .attr('width', width) .attr('height', height) .attr('fill', 'url(#spaceBg)');
// Group with blend mode so points softly accumulate light const g = svg.selectAll('g.points').data([0]).join('g').attr('class', 'points').style('mix-blend-mode', 'screen');
// Ensure container can host an absolute 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; }
// Final filter: remove small dots very close to the galaxy center (after placement) const centerHoleRadius = 0.48; // elliptical radius threshold const smallSizeThreshold = 7.5; // same notion as Python size cut const rTotal = idx.map((i) => Math.sqrt(((X[i] - cx) / a) ** 2 + ((Y[i] - cy) / b) ** 2)); const idxFiltered = idx.filter((i, k) => !(rTotal[k] <= centerHoleRadius && sizesPx[i] < smallSizeThreshold));
const sel = g.selectAll('circle').data(idxFiltered, (i) => i); sel.join( (enter) => enter.append('circle') .attr('cx', (i) => xScale(X[i])) .attr('cy', (i) => yScale(Y[i])) .attr('r', (i) => sizesPx[i] / 2) .attr('fill', (i) => colorFor(Zraw[i])) .attr('fill-opacity', 0.9) .attr('stroke', strokeColor) .attr('stroke-width', 0.4) .on('mouseenter', function(ev, i) { d3.select(this).raise() .attr('stroke', isDark ? 'rgba(255,255,255,0.85)' : 'rgba(0,0,0,0.85)') .attr('stroke-width', 1.2); const r = Math.sqrt(((X[i] - cx) / a) ** 2 + ((Y[i] - cy) / b) ** 2); const type = i < lenSpiral ? 'spiral' : 'bulge'; const arm = i < lenSpiral ? (armIndices[i] + 1) : null; tipInner.innerHTML = `<div><strong>${labelOf(i)}</strong></div>` + `<div><strong>Type</strong> ${type}${arm ? ` (arm ${arm})` : ''}</div>` + `<div><strong>Size</strong> ${sizesPx[i].toFixed(1)} px</div>` + `<div><strong>X</strong> ${X[i].toFixed(2)} · <strong>Y</strong> ${Y[i].toFixed(2)}</div>` + `<div><strong>r</strong> ${r.toFixed(3)} · <strong>z</strong> ${Zraw[i].toFixed(3)}</div>`; tip.style.opacity = '1'; }) .on('mousemove', (ev, i) => { const [mx, my] = d3.pointer(ev, container); const offsetX = 10, offsetY = 12; tip.style.transform = `translate(${Math.round(mx + offsetX)}px, ${Math.round(my + offsetY)}px)`; }) .on('mouseleave', function() { tip.style.opacity = '0'; tip.style.transform = 'translate(-9999px, -9999px)'; d3.select(this).attr('stroke', strokeColor).attr('stroke-width', 0.4); }), (update) => update .attr('cx', (i) => xScale(X[i])) .attr('cy', (i) => yScale(Y[i])) .attr('r', (i) => sizesPx[i] / 2) .attr('fill', (i) => colorFor(Zraw[i])) .attr('fill-opacity', 0.9) .attr('stroke', strokeColor) .attr('stroke-width', 0.4) .on('mouseenter', function(ev, i) { d3.select(this).raise() .attr('stroke', isDark ? 'rgba(255,255,255,0.85)' : 'rgba(0,0,0,0.85)') .attr('stroke-width', 1.2); const r = Math.sqrt(((X[i] - cx) / a) ** 2 + ((Y[i] - cy) / b) ** 2); const type = i < lenSpiral ? 'spiral' : 'bulge'; const arm = i < lenSpiral ? (armIndices[i] + 1) : null; tipInner.innerHTML = `<div><strong>${labelOf(i)}</strong></div>` + `<div><strong>Type</strong> ${type}${arm ? ` (arm ${arm})` : ''}</div>` + `<div><strong>Size</strong> ${sizesPx[i].toFixed(1)} px</div>` + `<div><strong>X</strong> ${X[i].toFixed(2)} · <strong>Y</strong> ${Y[i].toFixed(2)}</div>` + `<div><strong>r</strong> ${r.toFixed(3)} · <strong>z</strong> ${Zraw[i].toFixed(3)}</div>`; tip.style.opacity = '1'; }) .on('mousemove', (ev, i) => { const [mx, my] = d3.pointer(ev, container); const offsetX = 10, offsetY = 12; tip.style.transform = `translate(${Math.round(mx + offsetX)}px, ${Math.round(my + offsetY)}px)`; }) .on('mouseleave', function() { tip.style.opacity = '0'; tip.style.transform = 'translate(-9999px, -9999px)'; d3.select(this).attr('stroke', strokeColor).attr('stroke-width', 0.4); }) ); };
// First render + resize if (window.ResizeObserver) { const ro = new ResizeObserver(() => render()); ro.observe(container); } else { window.addEventListener('resize', render); } render(); };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356<div class="d3-line" style="width:100%;margin:10px 0;"></div><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 mount = document.currentScript ? document.currentScript.previousElementSibling : null; const container = (mount && mount.querySelector && mount.querySelector('.d3-line')) || document.querySelector('.d3-line'); if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// Dataset params matching the Plotly version const datasets = [ { name: 'CIFAR-10', base: { ymin:0.10, ymax:0.90, k:10.0, x0:0.55 }, aug: { ymin:0.15, ymax:0.96, k:12.0, x0:0.40 }, target: 0.97 }, { name: 'CIFAR-100', base: { ymin:0.05, ymax:0.70, k: 9.5, x0:0.60 }, aug: { ymin:0.08, ymax:0.80, k:11.0, x0:0.45 }, target: 0.85 }, { name: 'ImageNet-1K', base: { ymin:0.02, ymax:0.68, k: 8.5, x0:0.65 }, aug: { ymin:0.04, ymax:0.75, k: 9.5, x0:0.50 }, target: 0.82 }, ];
// Controls UI const controls = document.createElement('div'); controls.className = 'd3-line__controls'; Object.assign(controls.style, { marginTop: '12px', display: 'flex', gap: '16px', alignItems: 'center' });
const labelDs = document.createElement('label'); Object.assign(labelDs.style, { fontSize: '12px', color: 'rgba(0,0,0,.65)', display: 'flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap', padding: '6px 10px' }); labelDs.textContent = 'Dataset'; const selectDs = document.createElement('select'); Object.assign(selectDs.style, { fontSize: '12px', padding: '2px 6px' }); datasets.forEach((d, i) => { const o = document.createElement('option'); o.value = String(i); o.textContent = d.name; selectDs.appendChild(o); }); labelDs.appendChild(selectDs);
const labelAlpha = document.createElement('label'); Object.assign(labelAlpha.style, { fontSize: '12px', color: 'rgba(0,0,0,.65)', display: 'flex', alignItems: 'center', gap: '10px', flex: '1', padding: '6px 10px' }); labelAlpha.appendChild(document.createTextNode('Augmentation α')); const slider = document.createElement('input'); slider.type = 'range'; slider.min = '0'; slider.max = '1'; slider.step = '0.01'; slider.value = '0.70'; Object.assign(slider.style, { flex: '1' }); const alphaVal = document.createElement('span'); alphaVal.className = 'alpha-value'; alphaVal.textContent = slider.value; labelAlpha.appendChild(slider); labelAlpha.appendChild(alphaVal);
controls.appendChild(labelDs); controls.appendChild(labelAlpha);
// 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 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 const colorBase = '#64748b'; // slate-500 const colorImproved = '#2563eb'; // blue-600 const colorTarget = '#4b5563'; // gray-600 const legendBgLight = 'rgba(255,255,255,0.85)'; const legendBgDark = 'rgba(17,17,23,0.85)';
// Data and helpers const N = 240; const xs = Array.from({ length: N }, (_, i) => i / (N - 1)); const logistic = (x, { ymin, ymax, k, x0 }) => ymin + (ymax - ymin) / (1 + Math.exp(-k * (x - x0))); const blend = (l, e, a) => (1 - a) * l + a * e;
let datasetIndex = 0; let alpha = parseFloat(slider.value) || 0.7;
let yBase = []; let yAug = []; let yImp = []; let yTgt = [];
function computeCurves() { const d = datasets[datasetIndex]; yBase = xs.map((x) => logistic(x, d.base)); yAug = xs.map((x) => logistic(x, d.aug)); yTgt = xs.map(() => d.target); yImp = yBase.map((v, i) => blend(v, yAug[i], alpha)); }
// Scales and layout let width = 800, height = 360; let margin = { top: 16, right: 28, bottom: 40, left: 44 }; let xScale = d3.scaleLinear(); let yScale = d3.scaleLinear();
// Paths const lineGen = d3.line() .curve(d3.curveCatmullRom.alpha(0.6)) .x((d, i) => xScale(xs[i])) .y((d) => yScale(d));
const pathBase = gLines.append('path').attr('fill', 'none').attr('stroke', colorBase).attr('stroke-width', 2); const pathImp = gLines.append('path').attr('fill', 'none').attr('stroke', colorImproved).attr('stroke-width', 2); const pathTgt = gLines.append('path').attr('fill', 'none').attr('stroke', colorTarget).attr('stroke-width', 2).attr('stroke-dasharray', '6,6');
// Hover elements const hoverLine = gHover.append('line').attr('stroke-width', 1); const hoverDotB = gHover.append('circle').attr('r', 3.5).attr('fill', colorBase).attr('stroke', '#fff').attr('stroke-width', 1); const hoverDotI = gHover.append('circle').attr('r', 3.5).attr('fill', colorImproved).attr('stroke', '#fff').attr('stroke-width', 1); const hoverDotT = gHover.append('circle').attr('r', 3.5).attr('fill', colorTarget).attr('stroke', '#fff').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.domain([0, 1]).range([0, innerWidth]); yScale.domain([0, 1]).range([innerHeight, 0]);
// Grid (horizontal) gGrid.selectAll('*').remove(); const yTicks = yScale.ticks(6); 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(); const xAxis = d3.axisBottom(xScale).ticks(8).tickSizeOuter(0); const yAxis = d3.axisLeft(yScale).ticks(6).tickSizeOuter(0).tickFormat(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) .attr('y', innerHeight + 32) .attr('text-anchor', 'end') .style('font-size', '12px') .style('fill', tickColor) .text('x'); gAxes.append('text') .attr('class', 'axis-label axis-label--y') .attr('text-anchor', 'middle') .attr('transform', `translate(${-36},${innerHeight/2}) rotate(-90)`) .style('font-size', '12px') .style('fill', tickColor) .text('y');
overlay.attr('x', 0).attr('y', 0).attr('width', innerWidth).attr('height', innerHeight); hoverLine.attr('y1', 0).attr('y2', innerHeight).attr('stroke', axisColor);
// Legend inside plot (bottom-right), no background/border/shadow const legendWidth = Math.min(180, Math.max(120, Math.round(innerWidth * 0.22))); const legendHeight = 64; gLegend .attr('x', innerWidth - legendWidth) .attr('y', innerHeight - legendHeight) .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)' }); legendRoot.html(` <div style="display:flex;flex-direction:column;gap:6px;"> <div style="display:flex;align-items:center;gap:8px;"> <span style="width:18px;height:3px;background:${colorBase};border-radius:2px;display:inline-block"></span> <span>Baseline</span> </div> <div style="display:flex;align-items:center;gap:8px;"> <span style="width:18px;height:3px;background:${colorImproved};border-radius:2px;display:inline-block"></span> <span>Improved</span> </div> <div style="display:flex;align-items:center;gap:8px;"> <span style="width:18px;height:0;border-top:2px dashed ${colorTarget};display:inline-block"></span> <span>Target</span> </div> </div> `); }
function updatePaths() { pathBase.transition().duration(200).attr('d', lineGen(yBase)); pathImp.transition().duration(200).attr('d', lineGen(yImp)); pathTgt.transition().duration(200).attr('d', lineGen(yTgt)); }
function updateAlpha(a) { alpha = a; alphaVal.textContent = a.toFixed(2); yImp = yBase.map((v, i) => blend(v, yAug[i], alpha)); pathImp.transition().duration(80).attr('d', lineGen(yImp)); }
function applyDataset() { computeCurves(); updatePaths(); }
// Hover interactions function onMove(event) { const [mx, my] = d3.pointer(event, overlay.node()); const xi = Math.max(0, Math.min(N - 1, Math.round(xScale.invert(mx) * (N - 1)))); const xpx = xScale(xs[xi]); const yb = yBase[xi], yi = yImp[xi], yt = yTgt[xi]; hoverLine.attr('x1', xpx).attr('x2', xpx).style('display', null); hoverDotB.attr('cx', xpx).attr('cy', yScale(yb)).style('display', null); hoverDotI.attr('cx', xpx).attr('cy', yScale(yi)).style('display', null); hoverDotT.attr('cx', xpx).attr('cy', yScale(yt)).style('display', null);
// Tooltip content const ds = datasets[datasetIndex].name; tipInner.innerHTML = `<div><strong>${ds}</strong></div>` + `<div><strong>x</strong> ${xs[xi].toFixed(2)}</div>` + `<div><span style="display:inline-block;width:10px;height:10px;background:${colorBase};border-radius:50%;margin-right:6px;"></span><strong>Baseline</strong> ${yb.toFixed(3)}</div>` + `<div><span style="display:inline-block;width:10px;height:10px;background:${colorImproved};border-radius:50%;margin-right:6px;"></span><strong>Improved</strong> ${yi.toFixed(3)}</div>` + `<div><span style="display:inline-block;width:10px;height:10px;background:${colorTarget};border-radius:50%;margin-right:6px;"></span><strong>Target</strong> ${yt.toFixed(3)}</div>`; 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'); hoverDotB.style('display', 'none'); hoverDotI.style('display', 'none'); hoverDotT.style('display', 'none'); }
overlay.on('mousemove', onMove).on('mouseleave', onLeave);
// Init + controls wiring computeCurves(); updateScales(); updatePaths();
// Attach controls after SVG for consistency with Plotly fragment container.appendChild(controls);
selectDs.addEventListener('change', (e) => { datasetIndex = parseInt(e.target.value) || 0; applyDataset(); }); slider.addEventListener('input', (e) => { const a = parseFloat(e.target.value) || 0; updateAlpha(a); });
// Resize handling const render = () => { updateScales(); updatePaths(); }; if (window.ResizeObserver) { const ro = new ResizeObserver(() => render()); ro.observe(container); } else { window.addEventListener('resize', render); } render(); };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
67 unmodified lines686970717273747567 unmodified lines</div><div class="palettes__grid"></div><div class="palettes__simu" role="group" aria-labelledby="cb-sim-title"><br/><p ><strong>Use color with care.</strong> Color should rarely be the only channel of meaning. Always pair it with text, icons, shape or position. The simulation below helps you spot palettes and states that become indistinguishable for people with color‑vision deficiencies. Toggle modes while checking charts, legends and interactions to ensure sufficient contrast and redundant cues.</p><!-- Hidden SVG filters used by the page-wide simulation classes --><svg aria-hidden="true" focusable="false" width="0" height="0" style="position:absolute; left:-9999px; overflow:hidden;"><defs>67 unmodified lines68697071727367 unmodified lines</div><div class="palettes__grid"></div><div class="palettes__simu" role="group" aria-labelledby="cb-sim-title"><!-- Hidden SVG filters used by the page-wide simulation classes --><svg aria-hidden="true" focusable="false" width="0" height="0" style="position:absolute; left:-9999px; overflow:hidden;"><defs>
1/// <reference path="../.astro/types.d.ts" />3 unmodified lines45678910113 unmodified linesimport Footer from '../components/Footer.astro';import ThemeToggle from '../components/ThemeToggle.astro';import Seo from '../components/Seo.astro';// @ts-ignore Astro asset import typed via env.d.tsimport ogDefaultUrl from '../content/assets/images/visual-vocabulary-poster.png?url';import 'katex/dist/katex.min.css';import '../styles/global.css';const articleFM = (ArticleMod as any).frontmatter ?? {};3 unmodified lines45678910113 unmodified linesimport Footer from '../components/Footer.astro';import ThemeToggle from '../components/ThemeToggle.astro';import Seo from '../components/Seo.astro';// Default OG image served from public/const ogDefaultUrl = '/thumb.jpg';import 'katex/dist/katex.min.css';import '../styles/global.css';const articleFM = (ArticleMod as any).frontmatter ?? {};
Dockerfile+4
app/.astro/astro/content.d.ts+206
app/scripts/export-pdf.mjs+17-7
app/src/components/HtmlEmbed.astro+9
app/src/content/article.mdx+8-17
app/src/content/assets/data/finevision.csv → app/src/content/assets/data/vision.csvRenamed
app/src/content/assets/images/placeholder-wide.pngAdded

Large File Pointer Details
- SHA256: 200daf8ade0c7f035d883fefa9a12d6ba7cca504b1d5571774748c3c90639103
- Pointer size: 130 Bytes
- Size of remote file: 34.6 kB
app/src/content/chapters/getting-started.mdx+3-4
app/src/content/chapters/writing-your-content.mdx+6-14
app/src/content/embeds/d3-line-old.htmlDeleted
app/src/content/embeds/d3-pie.html+2-2
app/src/content/embeds/d3-scatter.htmlDeleted-160
app/src/content/embeds/original_embeds/d3js/banner.htmlDeleted-244
app/src/content/embeds/original_embeds/d3js/line.htmlDeleted-356
app/src/content/embeds/palettes.html-2
app/src/env.d.tsAdded+1
app/src/pages/index.astro+2-2