thibaud frere commited on
Commit Β·
e0ad823
1
Parent(s): fef84f3
test playwright
Browse filesFiles changed (32)
- .gitignore+2
- Dockerfile+5-1
- app/.astro/astro/content.d.ts+169
- app/astro.config.mjs+4-1
- app/package-lock.json
- app/package.json
- app/scripts/export-pdf.mjsAdded+216
- app/src/components/Footer.astro+4-34
- app/src/components/HtmlFragment.astro+1-1
- app/src/components/Meta.astro+25
- app/src/pages/article.mdx β app/src/content/article.mdxRenamed+58-58
- app/src/content/fragments/banner.htmlAdded+244
- app/src/fragments/bar.html β app/src/content/fragments/bar.htmlRenamed
- app/src/fragments/heatmap.html β app/src/content/fragments/heatmap.htmlRenamed
- app/src/fragments/line.html β app/src/content/fragments/line.htmlRenamed
- app/src/content/fragments/palettes.htmlAdded+311
- app/src/fragments/banner.htmlDeleted
- app/src/pages/index.astro+28-6
- app/src/styles/_base.scss+73-28
- app/src/styles/_layout.scss+14-1
- app/src/styles/components/_code.scssAdded+31
- app/src/styles/components/_footer.scss+50-4
- app/src/styles/global.scss+5-3
- fragments/d3js/banner.htmlAdded+240
- python/fragments/banner.py β fragments/plotly/banner.pyRenamed+4-13
- python/fragments/bar.py β fragments/plotly/bar.pyRenamed
- python/fragments/heatmap.py β fragments/plotly/heatmap.pyRenamed
- python/fragments/line.py β fragments/plotly/line.pyRenamed
- python/poetry.lock β fragments/plotly/poetry.lockRenamed
- python/pyproject.toml β fragments/plotly/pyproject.tomlRenamed
- python/convert.pyDeleted-32
- python/convert_to_md.pyDeleted-110
18 unmodified lines19202118 unmodified lines*.env*.cache18 unmodified lines192021222318 unmodified lines*.env*.cache# PDF exportapp/public/*.pdf
1234510 unmodified lines161718192021# Use an official Node runtime as the base image for building the applicationFROM node:20 AS build# Set the working directory in the containerWORKDIR /app10 unmodified lines# Build the applicationRUN npm run build# Use an official Nginx runtime as the base image for serving the applicationFROM nginx:alpine12345610 unmodified lines171819202122232425# Use an official Node runtime as the base image for building the application# Build avec Playwright (navigateurs et deps prΓͺts)FROM mcr.microsoft.com/playwright:v1.55.0-jammy AS build# Set the working directory in the containerWORKDIR /app10 unmodified lines# Build the applicationRUN npm run build# GΓ©nΓ¨re le PDF (thΓ¨me light, attente complΓ¨te)RUN npm run export:pdf -- --theme=light --wait=full# Use an official Nginx runtime as the base image for serving the applicationFROM nginx:alpine
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169declare 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 = {};type DataEntryMap = {"fragments": Record<string, {id: string;collection: "fragments";data: any;}>;};type AnyEntryMap = ContentEntryMap & DataEntryMap;export type ContentConfig = never;}
19 unmodified lines2021222324252619 unmodified linesdark: 'github-dark'},defaultColor: false,wrap: true},remarkPlugins: [[remarkToc, { heading: 'Table of Contents', maxDepth: 3 }],19 unmodified lines2021222324252627282919 unmodified linesdark: 'github-dark'},defaultColor: false,wrap: true,langAlias: {mdx: 'js'}},remarkPlugins: [[remarkToc, { heading: 'Table of Contents', maxDepth: 3 }],
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216#!/usr/bin/env nodeimport { spawn } from 'node:child_process';import { setTimeout as delay } from 'node:timers/promises';import { chromium } from 'playwright';import { resolve, basename } from 'node:path';import { promises as fs } from 'node:fs';import process from 'node:process';
async function run(command, args = [], options = {}) { return new Promise((resolvePromise, reject) => { const child = spawn(command, args, { stdio: 'inherit', shell: false, ...options }); child.on('error', reject); child.on('exit', (code) => { if (code === 0) resolvePromise(undefined); else reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`)); }); });}
async function waitForServer(url, timeoutMs = 60000) { const start = Date.now(); while (Date.now() - start < timeoutMs) { try { const res = await fetch(url); if (res.ok) return; } catch {} await delay(500); } throw new Error(`Le serveur n'a pas dΓ©marrΓ© Γ temps: ${url}`);}
function parseArgs(argv) { const out = {}; for (const arg of argv.slice(2)) { if (!arg.startsWith('--')) continue; const [k, v] = arg.replace(/^--/, '').split('='); out[k] = v === undefined ? true : v; } return out;}
function slugify(text) { return String(text || '') .normalize('NFKD') .replace(/\p{Diacritic}+/gu, '') .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .slice(0, 120) || 'article';}
function parseMargin(margin) { if (!margin) return { top: '12mm', right: '12mm', bottom: '16mm', left: '12mm' }; const parts = String(margin).split(',').map(s => s.trim()).filter(Boolean); if (parts.length === 1) { return { top: parts[0], right: parts[0], bottom: parts[0], left: parts[0] }; } if (parts.length === 2) { return { top: parts[0], right: parts[1], bottom: parts[0], left: parts[1] }; } if (parts.length === 3) { return { top: parts[0], right: parts[1], bottom: parts[2], left: parts[1] }; } return { top: parts[0] || '12mm', right: parts[1] || '12mm', bottom: parts[2] || '16mm', left: parts[3] || '12mm' };}
async function waitForImages(page, timeoutMs = 15000) { await page.evaluate(async (timeout) => { const deadline = Date.now() + timeout; const imgs = Array.from(document.images || []); const unloaded = imgs.filter(img => !img.complete || (img.naturalWidth === 0)); await Promise.race([ Promise.all(unloaded.map(img => new Promise(res => { if (img.complete && img.naturalWidth !== 0) return res(undefined); img.addEventListener('load', () => res(undefined), { once: true }); img.addEventListener('error', () => res(undefined), { once: true }); }))), new Promise(res => setTimeout(res, Math.max(0, deadline - Date.now()))) ]); }, timeoutMs);}
async function waitForPlotly(page, timeoutMs = 20000) { await page.evaluate(async (timeout) => { const start = Date.now(); const hasPlots = () => Array.from(document.querySelectorAll('.js-plotly-plot')).length > 0; // Wait until plots exist or timeout while (!hasPlots() && (Date.now() - start) < timeout) { await new Promise(r => setTimeout(r, 200)); } const deadline = start + timeout; // Then wait until each plot contains the main svg const allReady = () => Array.from(document.querySelectorAll('.js-plotly-plot')).every(el => el.querySelector('svg.main-svg')); while (!allReady() && Date.now() < deadline) { await new Promise(r => setTimeout(r, 200)); } }, timeoutMs);}
async function waitForStableLayout(page, timeoutMs = 5000) { const start = Date.now(); let last = await page.evaluate(() => document.scrollingElement ? document.scrollingElement.scrollHeight : document.body.scrollHeight); let stableCount = 0; while ((Date.now() - start) < timeoutMs && stableCount < 3) { await page.waitForTimeout(250); const now = await page.evaluate(() => document.scrollingElement ? document.scrollingElement.scrollHeight : document.body.scrollHeight); if (now === last) stableCount += 1; else { stableCount = 0; last = now; } }}
async function main() { const cwd = process.cwd(); const port = Number(process.env.PREVIEW_PORT || 8080); const baseUrl = `http://127.0.0.1:${port}/`; const args = parseArgs(process.argv); // Par dΓ©faut: light (n'emploie pas de variable d'environnement implicite) const theme = (args.theme === 'dark' || args.theme === 'light') ? args.theme : 'light'; const format = args.format || 'A4'; const margin = parseMargin(args.margin); const wait = (args.wait || 'full'); // 'networkidle' | 'images' | 'plotly' | 'full'
// filename can be provided, else computed from page title later let outFileBase = (args.filename && String(args.filename).replace(/\.pdf$/i, '')) || 'article';
console.log('> Build du site Astroβ¦'); await run('npm', ['run', 'build']);
console.log('> DΓ©marrage du preview AstroοΏ½οΏ½οΏ½'); const preview = spawn('npm', ['run', 'preview'], { cwd, stdio: 'inherit' });
try { await waitForServer(baseUrl, 60000); console.log('> Serveur prΓͺt, gΓ©nΓ©ration PDFβ¦');
const browser = await chromium.launch({ headless: true }); try { const context = await browser.newContext(); await context.addInitScript((desired) => { try { localStorage.setItem('theme', desired); // Appliquer immédiatement le thème pour éviter les flashes if (document && document.documentElement) { document.documentElement.dataset.theme = desired; } } catch {} }, theme); const page = await context.newPage(); await page.goto(baseUrl, { waitUntil: 'networkidle', timeout: 60000 }); // Compute slug from title if needed if (!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 readiness if (wait === 'images' || wait === 'full') { await waitForImages(page); } if (wait === 'plotly' || wait === 'full') { await waitForPlotly(page); } if (wait === 'full') { await waitForStableLayout(page); } await page.emulateMedia({ media: 'print' }); const outPath = resolve(cwd, 'dist', `${outFileBase}.pdf`); await page.pdf({ path: outPath, format, printBackground: true, margin }); console.log(`β
PDF gΓ©nΓ©rΓ©: ${outPath}`);
// Copie de compatibilitΓ© dans dist/article.pdf (pour serveurs Nginx qui ne servent que dist) const distCompatPath = resolve(cwd, 'dist', 'article.pdf'); try { if (basename(outPath) !== 'article.pdf') { await fs.copyFile(outPath, distCompatPath); console.log(`β
PDF copiΓ© (compat dist): ${distCompatPath}`); } } catch (e) { console.warn('Impossible de copier le PDF compat vers dist/article.pdf:', e?.message || e); }
// Copie aussi dans public sous 2 noms: slug.pdf et article.pdf (compat) const publicSlugPath = resolve(cwd, 'public', `${outFileBase}.pdf`); const publicCompatPath = resolve(cwd, 'public', 'article.pdf'); try { await fs.mkdir(resolve(cwd, 'public'), { recursive: true }); await fs.copyFile(outPath, publicSlugPath); await fs.copyFile(outPath, publicCompatPath); console.log(`β
PDF copiΓ© dans: ${publicSlugPath}`); console.log(`β
PDF copiΓ© (compat): ${publicCompatPath}`); } catch (e) { console.warn('Impossible de copier le PDF vers public/:', e?.message || e); } } finally { await browser.close(); } } finally { // Tenter un arrΓͺt propre preview.kill('SIGINT'); }}
main().catch((err) => { console.error(err); process.exit(1);});
9 unmodified lines101112131415161718191 unmodified line212223242526272829303132333435363742 unmodified lines80818283848586878889909192939495969798991001019 unmodified lines1111121131141151161171181191201211221231241259 unmodified lines<section class="citation-block"><h3>Citation</h3><p>For attribution in academic contexts, please cite this work as</p><textarea readonly class="citation-text">{citationText}</textarea><h4>BibTeX citation</h4><textarea readonly class="citation-bibtex">{bibtex}</textarea></section><section class="references-block"><slot />1 unmodified line</div></footer><style>.distill-footer { margin-top: 40px; border-top: 1px solid var(--border-color); }.footer-inner { max-width: 680px; margin: 0 auto; padding: 24px 16px; }.citation-block h3 { margin: 0 0 8px; }.citation-block h4 { margin: 16px 0 8px; font-size: 14px; text-transform: uppercase; color: var(--muted-color); }.citation-text, .citation-bibtex { width: 100%; min-height: 44px; border: 1px solid var(--border-color); border-radius: 6px; background: var(--surface-bg); padding: 8px; resize: none; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 13px; color: var(--text-color); white-space: pre-wrap; overflow-y: hidden; line-height: 1.4; }.references-block h3 { margin: 24px 0 8px; }.references-block .footnotes { margin-top: 8px; }.references-block .bibliography { margin-top: 8px; }</style><script is:inline>(() => {42 unmodified linesreturn true;};const autoResizeTextareas = () => {const areas = footer.querySelectorAll('.citation-text, .citation-bibtex');areas.forEach((ta) => {ta.style.height = 'auto';const min = 44;const next = Math.max(ta.scrollHeight, min);ta.style.height = next + 'px';});};const run = () => {const referencesEl = findFirstOutsideFooter(['#references', '.references', '.bibliography']);const footnotesEl = findFirstOutsideFooter(['.footnotes']);const movedRefs = moveIntoFooter(referencesEl, 'References');const movedNotes = moveIntoFooter(footnotesEl, 'Footnotes');autoResizeTextareas();return movedRefs || movedNotes;};9 unmodified lines}// Resize on window changes (e.g., fonts, layout)window.addEventListener('resize', () => {// throttle via rAFlet raf = null;if (raf) cancelAnimationFrame(raf);raf = requestAnimationFrame(() => {autoResizeTextareas();raf = null;});}, { passive: true });})();</script>9 unmodified lines101112131415161718191 unmodified line21222324252642 unmodified lines69707172737475767778799 unmodified lines899091929394959 unmodified lines<section class="citation-block"><h3>Citation</h3><p>For attribution in academic contexts, please cite this work as</p><pre class="citation short">{citationText}</pre><p>BibTeX citation</p><pre class="citation long">{bibtex}</pre></section><section class="references-block"><slot />1 unmodified line</div></footer><script is:inline>(() => {42 unmodified linesreturn true;};const run = () => {const referencesEl = findFirstOutsideFooter(['#references', '.references', '.bibliography']);const footnotesEl = findFirstOutsideFooter(['.footnotes']);const movedRefs = moveIntoFooter(referencesEl, 'References');const movedNotes = moveIntoFooter(footnotesEl, 'Footnotes');return movedRefs || movedNotes;};9 unmodified lines}// Resize on window changes (e.g., fonts, layout)// No textarea auto-resize needed for <pre> blocks})();</script>
2 unmodified lines34567892 unmodified linesconst { src } = Astro.props as Props;// Charge tous les fragments .html sous src/fragments/** en tant que string (dev & build)const fragments = import.meta.glob('../fragments/**/*.html', { query: '?raw', import: 'default', eager: true }) as Record<string, string>;function resolveFragment(requested: string): string | null {// Autorise "banner.html" ou "fragments/banner.html"2 unmodified lines34567892 unmodified linesconst { src } = Astro.props as Props;// Charge tous les fragments .html sous src/fragments/** en tant que string (dev & build)const fragments = import.meta.glob('../content/fragments/**/*.html', { query: '?raw', import: 'default', eager: true }) as Record<string, string>;function resolveFragment(requested: string): string | null {// Autorise "banner.html" ou "fragments/banner.html"
26 unmodified lines27282930313226 unmodified lines<p>{published}</p></div>)}</div></header>26 unmodified lines2728293031323334353637383940414243444546474849505152535455565726 unmodified lines<p>{published}</p></div>)}<div class="meta-container-cell"><h3>PDF</h3><p><button id="download-pdf-btn" type="button">Download PDF</button></p></div></div></header><script>// Attache un gestionnaire pour dΓ©clencher un tΓ©lΓ©chargement programmatique(() => {const ready = () => {const btn = document.getElementById('download-pdf-btn');if (!btn) return;btn.addEventListener('click', () => {const a = document.createElement('a');a.href = '/article.pdf';a.setAttribute('download', 'article.pdf');document.body.appendChild(a);a.click();a.remove();});};if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ready, { once: true });} else { ready(); }})();</script>
1234517 unmodified lines23242526272829303132333 unmodified lines373839404142434445464748495051525354555657585933 unmodified lines9394959697989910010110210310410510610710810911011111211311414 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216311 unmodified lines1751761771781791801811821831841851861871881891901911925 unmodified lines1981992002012022032043 unmodified lines20820921021121221321482 unmodified lines2972982993003013023037 unmodified lines31131231331431531631741 unmodified lines3593603613623633643655 unmodified lines37137237337437537637724 unmodified lines402403404405406407408409410411412413414415416417418419420421422---title: "The science template:\nCraft Beautiful Blogs"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors:- "John Doe"17 unmodified linesimport visualPoster from "../assets/images/visual-vocabulary-poster.png";<Aside>Welcome to this single-page research article template built with **Astro** and **MDX**.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: 10β15 minutes.</Fragment>In this guide, youβll learn how to install the template,write content (math, citations, images, code, asides, interactive fragments),3 unmodified lines</Fragment></Aside>Ce template est heavely inspired by distill.## Features<div className="tag-list"><span className="tag">Markdown based</span><span className="tag">KaTeX math</span><span className="tag">Citations & footnotes</span><span className="tag">Automatic build</span><span className="tag">Table of content</span><span className="tag">Dark theme</span><span className="tag">HTML fragments</span><span className="tag">Plotly ready</span><span className="tag">SEO Friendly</span><span className="tag">Lightweight bundle(\<500ko)</span><span className="tag">Aside notes</span><span className="tag">Medium like zoomable images</span></div>## Getting Started33 unmodified lines## Writing Your Content### MDXAuthor your content in MDX for a pleasant, productive writing flow that combines familiar Markdown with reusable components when needed.Below are minimal examples of the core elements.Don't forget to enable syntax highlighting for MDX to make your editing experience even smoother!```bash# For VS Code but alternatively, use the Extensions marketplace UI and search for "MDX" by unifiedjs.code --install-extension unifiedjs.vscode-mdx```The initial skeleton of this article looks like this:```mdx{/* HEADER */}14 unmodified lines{/* IMPORTS */}import { Image } from 'astro:assets';import Aside from "../components/Aside.astro";import HtmlFragment from "../components/HtmlFragment.astro";import placeholder from "../assets/images/placeholder.png";import audioDemo from "../assets/audio/audio-example.wav";{/* CONTENT */}<Aside>Welcome to this single-page research article template built with Astro and MDX.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: 10β15 minutes.</Fragment>In this guide, youβll learn how to install the template,write content (math, citations, images, code, asides, interactive fragments),customize styles and behavior, and follow a few best practices for publishing.<Fragment slot="aside">If you have questions or remarks open a discussion on the <a href="https://huggingface.co/spaces/lvwerra/distill-blog-template/discussions?status=open&type=discussion">Community tab</a>!</Fragment></Aside>```It is composed of three parts:- **Header**: which contains the title and the article's metadata.- **Imports**: the imports of the different modules / images used in the article- **Content**: the content of the article**Available blocs**:11 unmodified lines### MathInline example: $x^2 + y^2 = z^2$.Block example:$$x^2 + y^2 = z^2$$```mdxInline example: $x^2 + y^2 = z^2$Block example:$$\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V$$5 unmodified lines**Optional:** Zoomable (Medium-like lightbox): add `data-zoomable` to opt-in. Only images with this attribute will open full-screen on click.**Optional:** Figcaption and credits<figure><Image3 unmodified lines/><figcaption>Optimized image with a descriptive caption.<span className="image-credit">CrΓ©dit: Photo by <a href="https://example.com">Author</a></span></figcaption></figure>82 unmodified linesUse these helpers to expand content beyond the main column when needed. They will always be centered and displayed above every other content.**Wide example**<Wide><div className="demo-wide">demo wide</div>7 unmodified lines</Wide>```**Full-bleed example**<FullBleed><div className="demo-full-bleed">demo full-bleed</div>41 unmodified lines### Embeds#### HtmlFragmentsThe main purpose of the ```HtmlFragment``` component is to embed a plotly or d3 chart in your article. Libraries are already imported in the template.5 unmodified linesimport HtmlFragment from '../components/HtmlFragment.astro'<HtmlFragment src="line.html" />```#### Iframes24 unmodified lines## Best Practices- Keep sections short and focused.- Prefer vector or optimized images; use `astro:assets` for responsive delivery.- Annotate figures and code minimally but clearly.- Use math sparingly; explain notation on first use.### Choosing the right chartPicking the right visualization depends on your goal (compare values, show distribution, part-to-whole, trends, relationships, etc.). The Visual Vocabulary poster below provides a concise mapping from analytical task to chart types.<figure><Image src={visualPoster} alt="Visual Vocabulary: choosing the right chart by task" data-zoomable /><figcaption>Visual Vocabulary: a handy reference to select chart types by purpose (comparison, distribution, part-to-whole, correlation, and more).</figcaption></figure>## Conclusions12345617 unmodified lines24252627282930313233343 unmodified lines38394041424344454647484950515253545556575859606162636433 unmodified lines989910010110210310410510610710810911011114 unmodified lines12612712812913013113213313413513613713813914014114211 unmodified lines1541551561571581591601611621631641651661671681691701711721731745 unmodified lines1801811821831841851861871881891903 unmodified lines19419519619719819920082 unmodified lines2832842852862872882897 unmodified lines29729829930030130230341 unmodified lines3453463473483493503515 unmodified lines35735835936036136224 unmodified lines387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422---title: "From Idea to Interactive:\n A Modern Template for Scientific Writing"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors:- "John Doe"17 unmodified linesimport visualPoster from "../assets/images/visual-vocabulary-poster.png";<Aside>Welcome to this single-page research article template built with **Markdown**.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, asides, interactive fragments),3 unmodified lines</Fragment></Aside>This template is inspired by [**Distill**](https://distill.pub); we aim to preserve the best of it while modernizing the stack. Their work is highly inspiring.## Features<div className="tag-list"><span className="tag">Markdown based</span><span className="tag">KaTeX math</span><span className="tag">Syntax highlighting</span><span className="tag">Citations & footnotes</span><span className="tag">Automatic build</span><span className="tag">Table of content</span><span className="tag">Dark theme</span><span className="tag">HTML fragments</span><span className="tag">Plotly ready</span><span className="tag">D3.js ready</span><span className="tag">SEO Friendly</span><span className="tag">Lightweight bundle</span><span className="tag">Aside notes</span><span className="tag">Responsive images</span><span className="tag">Medium like zoomable images</span><span className="tag">PDF export</span></div>## Getting Started33 unmodified lines## Writing Your Content### IntroductionYour article lives in two places:- `app/src/content/` β where you can find the article.mdx and bibliography.bib.- `app/src/assets/` β images, audio, and other static assets. (handled by git lfs)The initial skeleton of an article looks like this:```mdx{/* HEADER */}14 unmodified lines{/* IMPORTS */}import { Image } from 'astro:assets';import placeholder from '../assets/images/placeholder.jpg';{/* CONTENT */}# Hello, worldThis is a short paragraph written in Markdown. Below is an example image:<Image src={placeholder} alt="Example image" />```**Available blocs**:11 unmodified lines### Math**Inline**$x^2 + y^2 = z^2$.```mdx$x^2 + y^2 = z^2$```**Block**$$x^2 + y^2 = z^2$$```mdx$$\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V$$5 unmodified lines**Optional:** Zoomable (Medium-like lightbox): add `data-zoomable` to opt-in. Only images with this attribute will open full-screen on click.**Optional:** Lazy loading: add `loading="lazy"` to opt-in.**Optional:** Figcaption and credits: add a `figcaption` element with a `span` containing the credit.<figure><Image3 unmodified lines/><figcaption>Optimized image with a descriptive caption.<span className="image-credit">Credit: Photo by <a href="https://example.com">Author</a></span></figcaption></figure>82 unmodified linesUse these helpers to expand content beyond the main column when needed. They will always be centered and displayed above every other content.#### Wide example<Wide><div className="demo-wide">demo wide</div>7 unmodified lines</Wide>```#### Full-bleed example<FullBleed><div className="demo-full-bleed">demo full-bleed</div>41 unmodified lines### Embeds#### Html FragmentsThe main purpose of the ```HtmlFragment``` component is to embed a plotly or d3 chart in your article. Libraries are already imported in the template.5 unmodified linesimport HtmlFragment from '../components/HtmlFragment.astro'<HtmlFragment src="line.html" />```#### Iframes24 unmodified lines## Best Practices### Short sectionsBreak content into **small, purposeβdriven sections**. Each section should answer a **single question** or support one idea. This improves **scanability**, helps readers navigate with the TOC, and makes later edits safer.### Clear, minimal annotationsFavor **concise captions** and callouts that clarify what to look at and why it matters. In code, **highlight just the lines** that carry the idea; avoid verbose commentary. **Precision beats volume**.### Explain math notation**Introduce symbols and variables** the first time they appear, and prefer **wellβknown identities** over custom shorthand. When formulas carry the message, add one sentence of **plainβlanguage interpretation** right after.### Use the right color scaleChoosing colors well is critical: a **palette** encodes **meaning** (categories, magnitudes, oppositions), preserves **readability** and **accessibility** (**sufficient contrast**, **colorβvision safety**), and ensures **perceptually smooth transitions**. The three families below illustrate when to use **categorical**, **sequential**, or **diverging** colors and how they evolve from the same **reference hue**.<div className=""><HtmlFragment src="palettes.html" /></div>### Use the right chartPicking the right visualization depends on your goal (compare values, show distribution, part-to-whole, trends, relationships, etc.). The Visual Vocabulary poster below provides a concise mapping from analytical task to chart types.<figure><a href="https://ft-interactive.github.io/visual-vocabulary/" target="_blank" rel="noopener noreferrer"><Image src={visualPoster} alt="Visual Vocabulary: choosing the right chart by task" /></a><figcaption>Visual Vocabulary: a handy reference to select chart types by purpose (comparison, distribution, part-to-whole, correlation, and more).β <a href="https://ft-interactive.github.io/visual-vocabulary/" target="_blank" rel="noopener noreferrer">Website</a></figcaption></figure>## Conclusions
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.08; // 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>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311<div class="palettes" style="width:100%; margin: 10px 0;"> <style> .palettes .palettes__grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; } @media (max-width: 820px) { .palettes .palettes__grid { grid-template-columns: 1fr; } } .palettes .palette-card { position: relative; } .palettes .palette-card__header { position: absolute; top: 0; left: 0; right: 0; height: 6px; border-top-left-radius: 10px; border-top-right-radius: 10px; background: transparent; } .palettes .palette-card__badge { position: relative; width: 44px; height: 44px; border-radius: 50%; margin: 14px auto 6px; background: transparent; border: none; box-shadow: none; } .palettes .palette-card__badge .badge-hole { position:absolute; top:50%; left:50%; width: 26px; height: 26px; transform: translate(-50%, -50%); border-radius: 50%; background: var(--surface-bg); border: none; box-shadow: none; } .palettes .palette-card__badge .badge-marker { position:absolute; width:6px; height:6px; border-radius:50%; border: none; box-shadow: none; } .palettes .palette-card__swatches { display: flex; gap: 0; margin-top: 8px; } .palettes .palette-card__swatches .sw { flex: 1 1 0; height: 28px; min-width: 0; border: none; } .palettes .palette-card__swatches .sw:first-child { border-top-left-radius: 6px; border-bottom-left-radius: 6px; } .palettes .palette-card__swatches .sw:last-child { border-top-right-radius: 6px; border-bottom-right-radius: 6px; } .palettes .palette-card__footer { margin-top: auto; display: flex; flex-direction: column; gap: 8px; } .palettes .copy-btn { width: 100%; margin: 0; padding: 8px 10px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--surface-bg); color: var(--text-color); font-size: 12px; cursor: pointer; } .palettes .palettes__meta { display: flex; align-items: center; gap: 10px; justify-content: space-between; } .palettes .current-color { display: flex; align-items: center; gap: 10px; } .palettes .current-swatch { width: 20px; height: 20px; border-radius: 50%; border: 1px solid var(--border-color); } .palettes .current-text { display: flex; flex-direction: column; line-height: 1.1; } .palettes .current-name { font-size: 14px; font-weight: 700; color: var(--text-color); } .palettes .current-hex { font-size: 11px; color: var(--muted-color); letter-spacing: .02em; } .palettes .cvd-select { padding: 4px 8px; font-size: 12px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--surface-bg); color: var(--text-color); } </style> <div class="palettes__controls" style="display:flex; flex-direction:column; gap:10px; margin-bottom:24px;"> <div style="display:flex; align-items:center; justify-content:space-between; gap:12px;"> <div style="font-weight:700;">Pick a hue</div> <div class="hue-value" style="font-variant-numeric: tabular-nums; color: var(--muted-color);">H 220Β°</div> </div> <div class="hue-slider" style="position:relative; height:18px; border-radius:10px; border:1px solid var(--border-color); background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%); cursor: ew-resize; touch-action: none;"> <div class="hue-knob" style="position:absolute; top:50%; left:61.1%; width:14px; height:14px; border-radius:50%; border:2px solid #fff; box-shadow:0 0 0 1px rgba(0,0,0,.2), 0 2px 8px rgba(0,0,0,.25); transform:translate(-50%, -50%); background: var(--surface-bg); z-index: 2;"></div> </div> <div class="palettes__meta"> <div class="current-color"> <div class="current-swatch" aria-label="Current color" title="Current color"></div> <div class="current-text"> <div class="current-name">β</div> <div class="current-hex">β</div> </div> </div> <label style="display:flex; align-items:center; gap:8px;"> <span style="font-size:12px; color: var(--muted-color);">Color blindness preview</span> <select class="cvd-select" title="Choose a colorβblindness simulation"> <option value="none">None</option> <option value="protanopia">Protanopia (<2%)</option> <option value="deuteranopia">Deuteranopia (<2%)</option> <option value="tritanopia">Tritanopia (<0.1%)</option> <option value="achromatopsia">Monochromacy (<0.1%)</option> </select> </label> </div> </div> <div class="palettes__grid"></div></div><script> (() => { const ensureLibs = (cb) => { const loadScript = (id, src, onload, onerror) => { let s = document.getElementById(id); if (s) { return onload && onload(); } s = document.createElement('script'); s.id = id; s.src = src; s.async = true; if (onload) s.addEventListener('load', onload, { once: true }); if (onerror) s.addEventListener('error', onerror, { once: true }); document.head.appendChild(s); }; const ensureD3 = (next) => { if (window.d3) return next(); loadScript('d3-cdn', 'https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js', next, () => { loadScript('d3-cdn-fallback', 'https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js', next); }); }; const ensureChroma = (next) => { if (window.chroma) return next(); loadScript('chroma-cdn', 'https://unpkg.com/chroma-js@2.4.2/dist/chroma.min.js', next, () => { loadScript('chroma-cdn-fallback', 'https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.4.2/chroma.min.js', next); }); }; const ensureNtc = (next) => { if (window.ntc && typeof window.ntc.name === 'function') return next(); loadScript('ntc-cdn', 'https://unpkg.com/ntcjs@1.0.0/build/ntc.js', next, () => next()); }; ensureD3(() => ensureChroma(() => ensureNtc(cb))); };
const bootstrap = () => { console.log('[palettes] bootstrap start'); const mount = document.currentScript ? document.currentScript.previousElementSibling : null; const root = mount && mount.closest('.palettes') ? mount.closest('.palettes') : document.querySelector('.palettes'); if (!root || root.dataset.mounted) return; root.dataset.mounted = 'true';
const grid = root.querySelector('.palettes__grid'); const slider = root.querySelector('.hue-slider'); const knob = root.querySelector('.hue-knob'); const hueValue = root.querySelector('.hue-value'); const currentSwatch = root.querySelector('.current-swatch'); const currentName = root.querySelector('.current-name'); const currentHex = root.querySelector('.current-hex'); const simSelect = root.querySelector('.cvd-select'); console.log('[palettes] elements', { root: !!root, grid: !!grid, slider: !!slider, knob: !!knob, hueValue: !!hueValue });
// Cards data with full descriptions const cards = [ { key: 'categorical', title: 'Categorical', desc: 'Categorical colors help users map non-numeric meaning to objects in a visualization. These are designed to be visually distinct from one another. Maximum of six.', generator: (base) => { // GΓ©nΓ©ration en LCH pour des couleurs perceptuellement distinctes const baseH = chroma(base).get('hsl.h'); const L = 70; // luminositΓ© confortable const C = 80; // chroma modΓ©rΓ© pour rester dans le gamut return Array.from({ length: 6 }, (_, i) => chroma.lch(L, C, (baseH + i * 60) % 360).hex()); } }, { key: 'sequential', title: 'Sequential', desc: 'Sequential colors have numeric meaning. These are a gradation of colors that go from light to dark. They are used in a heatmap context.', generator: (base) => { const c = chroma(base).saturate(0.3); return chroma .scale([c.brighten(2), c, c.darken(2)]) .mode('lab') .correctLightness(true) .colors(6); } }, { key: 'diverging', title: 'Diverging', desc: 'Diverging colors also have numeric meaning. Theyβre useful when dealing with negative values or ranges that have two extremes with a baseline in the middle.', generator: (base) => { const c = chroma(base); const baseH = c.get('hsl.h'); const compH = (baseH + 180) % 360; const left = chroma.hsl(compH, 0.75, 0.55); const right = chroma.hsl(baseH, 0.75, 0.55); const center = '#ffffff'; // Construire deux rampes symΓ©triques qui se rejoignent (sans dupliquer le neutre) const leftRamp = chroma.scale([left, center]).mode('lch').correctLightness(true).colors(4); const rightRamp = chroma.scale([center, right]).mode('lch').correctLightness(true).colors(4); return [leftRamp[0], leftRamp[1], leftRamp[2], rightRamp[1], rightRamp[2], rightRamp[3]]; } } ];
// Render cards scaffolding const cardSel = d3.select(grid).selectAll('.palette-card').data(cards, d => d.key); const enter = cardSel.enter().append('div').attr('class', 'palette-card') .style('border', '1px solid var(--border-color)') .style('border-radius', '10px') .style('background', 'var(--surface-bg)') .style('padding', '16px 14px 12px') .style('display', 'flex') .style('flex-direction', 'column') .style('gap', '10px') .style('min-height', '240px');
enter.append('div').attr('class', 'palette-card__header');
enter.append('div').attr('class', 'palette-card__badge');
enter.append('div').attr('class', 'palette-card__title') .style('text-align', 'center') .style('font-weight', '800') .style('font-size', '28px') .text(d => d.title);
enter.append('div').attr('class', 'palette-card__desc') .style('text-align', 'center') .style('color', 'var(--muted-color)') .style('line-height', '1.6') .style('font-size', '15px') .text(d => d.desc);
const footer = enter.append('div').attr('class', 'palette-card__footer'); footer.append('div').attr('class', 'palette-card__swatches'); footer.append('button').attr('class', 'copy-btn').text('Copy palette');
// Rendering const renderPalettes = (h) => { console.log('[palettes] renderPalettes', h); const base = chroma.hsl(h, 0.75, 0.55); const uniformText = (bg) => (chroma(bg).luminance() > 0.45 ? '#111' : '#fff');
// Update current swatch + name if (currentSwatch) currentSwatch.style.background = base.hex(); const getName = (hex) => { // Prefer large color-name list if available const list = (window.__colorNames && window.__colorNames.length) ? window.__colorNames : null; if (list && window.chroma) { let bestName = null; let best = Infinity; for (let i = 0; i < list.length; i++) { const item = list[i]; const d = (chroma.deltaE ? chroma.deltaE(hex, item.hex) : chroma.distance(hex, item.hex, 'lab')); if (d < best) { best = d; bestName = item.name; } } if (bestName) return bestName; } // Fallback to ntc.js try { if (window.ntc && window.ntc.name) { const res = window.ntc.name(hex); return res && res[1]; } } catch {} // Hue-based coarse fallback const hh = chroma(hex).get('hsl.h') || 0; const labels = ['Red','Orange','Yellow','Lime','Green','Cyan','Blue','Indigo','Violet','Magenta']; const idx = Math.round(((hh % 360) / 360) * (labels.length - 1)); return labels[idx]; }; const hexStr = base.hex().toUpperCase(); if (currentName) currentName.textContent = getName(hexStr); if (currentHex) currentHex.textContent = hexStr; d3.select(root).selectAll('.palette-card').each(function(d) { const palette = d.generator(base); console.log('[palettes] palette', d.key, palette.length, palette); const sw = d3.select(this).select('.palette-card__swatches'); const data = palette.slice(0, 6); const s = sw.selectAll('.sw').data(data, (c, i) => i); const sEnter = s.enter().append('div').attr('class', 'sw'); sEnter.merge(s) .style('background', c => c) .text(''); s.exit().remove();
// Hook up copy button (keeps palette visible) const btn = d3.select(this).select('.copy-btn'); btn.on('click', async () => { const json = JSON.stringify(data, null, 2); try { await navigator.clipboard.writeText(json); const old = btn.text(); btn.text('Copied!'); setTimeout(() => btn.text(old), 900); } catch { window.prompt('Copy palette', json); } });
// Update header gradient to reflect palette const header = d3.select(this).select('.palette-card__header'); const grad = `linear-gradient(90deg, ${data.join(',')})`; header.style('background', grad);
// Update circular badge const badge = d3.select(this).select('.palette-card__badge'); if (d.key === 'categorical') { // Donut full hue circle for categorical const hueCircle = 'conic-gradient(#f00 0%, #ff0 16.6%, #0f0 33.3%, #0ff 50%, #00f 66.6%, #f0f 83.3%, #f00 100%)'; badge.style('background', hueCircle); // Clear previous markers badge.selectAll('.badge-marker').remove(); // Place markers at palette hues const radius = 21; // outer circle radius const center = 22; // half of badge size (44) data.forEach((hex) => { const h = chroma(hex).get('hsl.h') || 0; const angle = (h * Math.PI) / 180; // radians const r = radius - 3; // adjust for 6px marker size const x = center + r * Math.cos(angle - Math.PI / 2); const y = center + r * Math.sin(angle - Math.PI / 2); const mk = document.createElement('div'); mk.className = 'badge-marker'; mk.style.left = `${Math.round(x - 3)}px`; mk.style.top = `${Math.round(y - 3)}px`; mk.style.background = "rgba(255,255,255,0.9)"; badge.node().appendChild(mk); }); // Inner hole to make it a donut if (!badge.select('.badge-hole').node()) badge.append('div').attr('class', 'badge-hole'); } else { // Linear gradient left->right for sequential/diverging const linear = `linear-gradient(90deg, ${data.join(',')})`; badge.style('background', linear); badge.selectAll('.badge-marker').remove(); badge.selectAll('.badge-hole').remove(); } }); };
// Hue slider behavior let hue = 220; // initial const setHue = (h) => { hue = (h + 360) % 360; const pct = hue / 360 * 100; if (knob) knob.style.left = pct + '%'; if (hueValue) hueValue.textContent = `H ${Math.round(hue)}Β°`; console.log('[palettes] setHue', hue, pct); renderPalettes(hue); }; const getHueFromEvent = (ev) => { const rect = slider.getBoundingClientRect(); const clientX = ev.touches ? ev.touches[0].clientX : ev.clientX; const x = clientX - rect.left; const t = Math.max(0, Math.min(1, x / rect.width)); const h = t * 360; console.log('[palettes] getHueFromEvent', { clientX, left: rect.left, width: rect.width, t, h }); return h; }; const onDown = (ev) => { console.log('[palettes] onDown', ev.type); ev.preventDefault(); setHue(getHueFromEvent(ev)); const move = (e) => { e.preventDefault && e.preventDefault(); setHue(getHueFromEvent(e)); }; const up = () => { console.log('[palettes] onUp'); window.removeEventListener('mousemove', move); window.removeEventListener('touchmove', move); window.removeEventListener('mouseup', up); window.removeEventListener('touchend', up); }; window.addEventListener('mousemove', move, { passive: false }); window.addEventListener('touchmove', move, { passive: false }); window.addEventListener('mouseup', up, { once: true }); window.addEventListener('touchend', up, { once: true }); }; if (slider) { slider.addEventListener('mousedown', onDown); slider.addEventListener('touchstart', onDown, { passive: false }); console.log('[palettes] listeners attached'); } else { console.warn('[palettes] slider not found'); }
// Color-vision simulation filters (SVG) const injectFilters = () => { if (document.getElementById('cvd-filters')) return; const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('id', 'cvd-filters'); svg.setAttribute('width', '0'); svg.setAttribute('height', '0'); svg.style.position = 'absolute'; svg.innerHTML = ` <filter id="cvd-protanopia"><feColorMatrix type="matrix" values="0.567 0.433 0 0 0 0.558 0.442 0 0 0 0 0.242 0.758 0 0 0 0 0 1 0"/></filter> <filter id="cvd-deuteranopia"><feColorMatrix type="matrix" values="0.625 0.375 0 0 0 0.7 0.3 0 0 0 0 0.3 0.7 0 0 0 0 0 1 0"/></filter> <filter id="cvd-tritanopia"><feColorMatrix type="matrix" values="0.95 0.05 0 0 0 0 0.433 0.567 0 0 0 0.475 0.525 0 0 0 0 0 1 0"/></filter> <filter id="cvd-achromatopsia"><feColorMatrix type="matrix" values="0.299 0.587 0.114 0 0 0.299 0.587 0.114 0 0 0.299 0.587 0.114 0 0 0 0 0 1 0"/></filter> `; document.body.appendChild(svg); }; injectFilters();
const applySimulation = (mode) => { if (!grid) return; if (!mode || mode === 'none') { grid.style.filter = 'none'; return; } grid.style.filter = `url(#cvd-${mode})`; }; if (simSelect) simSelect.addEventListener('change', () => applySimulation(simSelect.value));
// Load extended color-name dataset, then initial render const loadColorNames = () => { if (window.__colorNames) return Promise.resolve(window.__colorNames); const url = 'https://unpkg.com/color-name-list@10.2.0/dist/colornames.json'; return fetch(url).then(r => r.json()).then(arr => { window.__colorNames = arr; return arr; }).catch(() => []); }; console.log('[palettes] initial render'); loadColorNames().finally(() => setHue(hue)); applySimulation('none');
// Fixed 3 columns layout grid.style.gridTemplateColumns = '1fr 1fr 1fr'; };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => ensureLibs(bootstrap), { once: true }); else ensureLibs(bootstrap); })();</script>
1234561 unmodified lines67686970717214 unmodified lines878889909192100 unmodified lines19319419519619719819919 unmodified lines219220221222223224225226227228229230231232233234235236237238239240241242---import Article, { frontmatter as articleFM } from './article.mdx';import Meta from '../components/Meta.astro';import HtmlFragment from '../components/HtmlFragment.astro';import Footer from '../components/Footer.astro';61 unmodified lines<script src="https://cdn.plot.ly/plotly-3.0.0.min.js" charset="utf-8"></script></head><body><ThemeToggle />14 unmodified lines<div class="title">Table of Contents</div><div id="toc-placeholder"></div></aside><main><Article /><style is:inline>100 unmodified lines// Build TOC from article headings (h2/h3/h4) and render into the sticky asideconst buildTOC = () => {const holder = document.getElementById('toc-placeholder');if (!holder || holder.children.length) return;const articleRoot = document.querySelector('section.content-grid main');if (!articleRoot) return;const headings = articleRoot.querySelectorAll('h2, h3, h4');19 unmodified linesulStack[ulStack.length-1].appendChild(li);});holder.appendChild(nav);// active link on scrollconst links = holder.querySelectorAll('a');const onScroll = () => {for (let i = headings.length - 1; i >= 0; i--) {const top = headings[i].getBoundingClientRect().top;if (top - 60 <= 0) {links.forEach(l => l.classList.remove('active'));const id = '#' + headings[i].id;const active = Array.from(links).find(l => l.getAttribute('href') === id);active && active.classList.add('active');break;}}};window.addEventListener('scroll', onScroll);onScroll();};if (document.readyState === 'loading') {1234561 unmodified lines6768697071727314 unmodified lines88899091929394959697100 unmodified lines19819920020120220320420519 unmodified lines225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264---import Article, { frontmatter as articleFM } from '../content/article.mdx';import Meta from '../components/Meta.astro';import HtmlFragment from '../components/HtmlFragment.astro';import Footer from '../components/Footer.astro';61 unmodified lines<script src="https://cdn.plot.ly/plotly-3.0.0.min.js" charset="utf-8"></script><script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script></head><body><ThemeToggle />14 unmodified lines<div class="title">Table of Contents</div><div id="toc-placeholder"></div></aside><details class="toc-mobile"><summary>Table of Contents</summary><div id="toc-mobile-placeholder"></div></details><main><Article /><style is:inline>100 unmodified lines// Build TOC from article headings (h2/h3/h4) and render into the sticky asideconst buildTOC = () => {const holder = document.getElementById('toc-placeholder');const holderMobile = document.getElementById('toc-mobile-placeholder');if ((holder && holder.children.length) && (holderMobile && holderMobile.children.length)) return;const articleRoot = document.querySelector('section.content-grid main');if (!articleRoot) return;const headings = articleRoot.querySelectorAll('h2, h3, h4');19 unmodified linesulStack[ulStack.length-1].appendChild(li);});if (holder) holder.appendChild(nav);if (holderMobile) holderMobile.appendChild(nav.cloneNode(true));// active link on scrollconst links = [...(holder ? holder.querySelectorAll('a') : []),...(holderMobile ? holderMobile.querySelectorAll('a') : [])];const onScroll = () => {for (let i = headings.length - 1; i >= 0; i--) {const top = headings[i].getBoundingClientRect().top;if (top - 60 <= 0) {links.forEach(l => l.classList.remove('active'));const id = '#' + headings[i].id;const actives = Array.from(links).filter(l => l.getAttribute('href') === id);actives.forEach(a => a.classList.add('active'));break;}}};window.addEventListener('scroll', onScroll);onScroll();// Close mobile accordion when a link inside it is clickedif (holderMobile) {const details = holderMobile.closest('details');holderMobile.addEventListener('click', (ev) => {const target = ev.target as Element | null;const anchor = target && 'closest' in target ? (target as Element).closest('a') : null;if (anchor instanceof HTMLAnchorElement && details && (details as HTMLDetailsElement).open) {(details as HTMLDetailsElement).open = false;}});}};if (document.readyState === 'loading') {
3 unmodified lines4567891057 unmodified lines6869707172737475767778798081828384858687888990919264 unmodified lines15715815916016116216316416516616716816917032 unmodified lines2032042053 unmodified lineshtml { box-sizing: border-box; }*, *::before, *::after { box-sizing: inherit; }body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Helvetica Neue, Arial, Apple Color Emoji, Segoe UI Emoji; color: var(--text-color); }/* Avoid constraining <main> inside grid; scope container sizing elsewhere if needed *//* main { max-width: 980px; margin: 24px auto; padding: 16px; } */57 unmodified lines.content-grid main pre:not(.astro-code) { background: var(--code-bg); border: 1px solid var(--border-color); border-radius: 6px; padding: var(--spacing-3); font-size: 14px; overflow: auto; }/* Sync Shiki variables with current theme *//* Standard wrapper look for code blocks */.astro-code { border: 1px solid var(--border-color); border-radius: 6px; padding: var(--spacing-3); padding-left: calc(var(--spacing-3) + 6px); font-size: 14px; }html[data-theme='light'] .astro-code { background-color: var(--code-bg); }html[data-theme='dark'] .astro-code { background-color: var(--shiki-dark-bg); }/* Apply token color from per-span vars exposed by Shiki dual themes */html[data-theme='light'] .astro-code span { color: var(--shiki-light) !important; }html[data-theme='dark'] .astro-code span { color: var(--shiki-dark) !important; }/* Token color remapping using Shiki CSS variables on the wrapper *//* Optionnel: booster le contraste light */html[data-theme='light'] .astro-code {--shiki-foreground: #24292f;--shiki-background: #ffffff;}/* Rely on Shiki's own token spans; no class remap */.content-grid main code { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }/* Placeholder block (discreet centered text) */64 unmodified lines.content-grid main hr { border: none; border-bottom: 1px solid var(--border-color); margin: var(--spacing-5) 0; }.code-block {background: var(--code-bg);border: 1px solid var(--border-color);border-radius: 6px;padding: var(--spacing-3);font-size: 14px;overflow: auto;}// ============================================================================// Media / Figures32 unmodified linesfigcaption { text-align: center; font-size: 0.9rem; color: var(--muted-color); margin-top: 6px; }.image-credit { display: block; margin-top: 4px; font-size: 12px; color: var(--muted-color); }.image-credit a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }3 unmodified lines4567891057 unmodified lines68697071727364 unmodified lines13813914014114214314414514614714814915015132 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492503 unmodified lineshtml { box-sizing: border-box; }*, *::before, *::after { box-sizing: inherit; }body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Helvetica Neue, Arial, Apple Color Emoji, Segoe UI Emoji; color: var(--text-color); }audio { display: block; }/* Avoid constraining <main> inside grid; scope container sizing elsewhere if needed *//* main { max-width: 980px; margin: 24px auto; padding: 16px; } */57 unmodified lines.content-grid main pre:not(.astro-code) { background: var(--code-bg); border: 1px solid var(--border-color); border-radius: 6px; padding: var(--spacing-3); font-size: 14px; overflow: auto; }/* Rely on Shiki's own token spans; no class remap */.content-grid main code { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }/* Placeholder block (discreet centered text) */64 unmodified lines.content-grid main hr { border: none; border-bottom: 1px solid var(--border-color); margin: var(--spacing-5) 0; }// .code-block {// background: rgba(120, 120, 120, 0.5);// border: 1px solid var(--border-color);// border-radius: 6px;// padding: var(--spacing-3);// font-size: 14px;// overflow: auto;// }// ============================================================================// Media / Figures32 unmodified linesfigcaption { text-align: center; font-size: 0.9rem; color: var(--muted-color); margin-top: 6px; }.image-credit { display: block; margin-top: 4px; font-size: 12px; color: var(--muted-color); }.image-credit a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }// ============================================================================// Buttons (minimal, Γ©purΓ©)// ============================================================================.meta .meta-container-cell button {appearance: none;background: var(--surface-bg);color: var(--text-color);border: 1px solid var(--border-color);border-radius: 6px;padding: 8px 12px;font-size: 14px;line-height: 1;cursor: pointer;transition: background-color .15s ease, border-color .15s ease, box-shadow .15s ease, transform .02s ease;}.meta .meta-container-cell button:hover {background: var(--code-bg);}.meta .meta-container-cell button:active {transform: translateY(1px);}.meta .meta-container-cell button:focus-visible {outline: none;box-shadow: 0 0 0 2px var(--link-underline);}.meta .meta-container-cell button:disabled {opacity: .6;cursor: not-allowed;}// ============================================================================// Print styles// =========================================================================@media print {html, body { background: #fff; }/* Marges gΓ©rΓ©es par Playwright; Γ©viter marges globales supplΓ©mentaires */body { margin: 0; }/* Conserver banniΓ¨re (hero), masquer Γ©lΓ©ments d'UI non nΓ©cessaires */#theme-toggle { display: none !important; }/* Liens: enlever soulignement au survol */.content-grid main a { text-decoration: none; border-bottom: 1px solid rgba(0,0,0,.2); }/* Eviter coupures dans des blocs complexes */.content-grid main pre,.content-grid main blockquote,.content-grid main table,.content-grid main figure { break-inside: avoid; page-break-inside: avoid; }/* Sauts de page doux autour des titres principaux */.content-grid main h2 { page-break-before: auto; page-break-after: avoid; break-after: avoid-page; }/* Petites tailles dβicΓ΄nes inutiles Γ lβimpression */.code-lang-chip { display: none !important; }/* Ajuster couleurs plus contrastΓ©es Γ lβimpression */:root {--border-color: rgba(0,0,0,.2);--link-underline: rgba(0,0,0,.3);--link-underline-hover: rgba(0,0,0,.4);}}
19 unmodified lines2021222324251 unmodified line2728293031323319 unmodified lines.toc nav a:hover { text-decoration: underline solid var(--muted-color); }.toc nav a.active { text-decoration: underline; }// Right aside (notes).right-aside { position: sticky; top: 24px; }.right-aside .aside-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 8px; padding: 10px; margin-bottom: 10px; font-size: 0.9rem; color: var(--text-color); }1 unmodified line// Responsive β collapse to single column@media (max-width: 1100px) {.content-grid { grid-template-columns: 1fr; }.toc { position: static; }.right-aside { display: none; }main > nav:first-of-type { display: block; }}19 unmodified lines2021222324252627282930313233343536371 unmodified line394041424344454619 unmodified lines.toc nav a:hover { text-decoration: underline solid var(--muted-color); }.toc nav a.active { text-decoration: underline; }// Mobile TOC accordion.toc-mobile { display: none; margin: 8px 0 16px; }.toc-mobile > summary { cursor: pointer; list-style: none; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--surface-bg); color: var(--text-color); font-weight: 600; }.toc-mobile[open] > summary { border-bottom-left-radius: 0; border-bottom-right-radius: 0; }.toc-mobile nav { border-left: none; padding: 10px 12px; font-size: 14px; border: 1px solid var(--border-color); border-top: none; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; background: var(--surface-bg); }.toc-mobile nav ul { margin: 0 0 6px; padding-left: 1em; }.toc-mobile nav li { list-style: none; margin: .25em 0; }.toc-mobile nav a { color: var(--text-color); text-decoration: none; border-bottom: none; }.toc-mobile nav > ul > li > a { font-weight: 700; }.toc-mobile nav a:hover { text-decoration: underline solid var(--muted-color); }.toc-mobile nav a.active { text-decoration: underline; }// Right aside (notes).right-aside { position: sticky; top: 24px; }.right-aside .aside-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 8px; padding: 10px; margin-bottom: 10px; font-size: 0.9rem; color: var(--text-color); }1 unmodified line// Responsive β collapse to single column@media (max-width: 1100px) {.content-grid { grid-template-columns: 1fr; }.toc { position: static; display: none; }.toc-mobile { display: block; }.right-aside { display: none; }main > nav:first-of-type { display: block; }}
12345678910111213141516171819202122232425262728293031
/* Sync Shiki variables with current theme *//* Standard wrapper look for code blocks */.astro-code { border: 1px solid var(--border-color); border-radius: 6px; padding: var(--spacing-3); padding-left: calc(var(--spacing-3) + 6px); font-size: 14px; }
/* Prevent code blocks from breaking layout on small screens */.astro-code { overflow-x: auto; width: 100%; max-width: 100%; box-sizing: border-box; -webkit-overflow-scrolling: touch; }section.content-grid pre { overflow-x: auto; width: 100%; max-width: 100%; box-sizing: border-box; -webkit-overflow-scrolling: touch; }section.content-grid pre code { display: inline-block; min-width: 100%; }
/* Wrap longues lignes en mobile pour Γ©viter l'overflow (URLs, etc.) */@media (max-width: 700px) { .astro-code, section.content-grid pre { white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; } section.content-grid pre code { white-space: pre-wrap; display: block; min-width: 0; }}
html[data-theme='light'] .astro-code { background-color: var(--code-bg); }
html[data-theme='dark'] .astro-code { background-color: var(--shiki-dark-bg); }
/* Apply token color from per-span vars exposed by Shiki dual themes */html[data-theme='light'] .astro-code span { color: var(--shiki-light) !important; }html[data-theme='dark'] .astro-code span { color: var(--shiki-dark) !important; }
/* Token color remapping using Shiki CSS variables on the wrapper *//* Optionnel: booster le contraste light */html[data-theme='light'] .astro-code { --shiki-foreground: #24292f; --shiki-background: #ffffff;}12345678.distill-footer { margin-top: 40px; border-top: 1px solid var(--border-color); }.footer-inner { max-width: 680px; margin: 0 auto; padding: 24px 16px; }.citation-block h3 { margin: 0 0 8px; }.citation-block h4 { margin: 16px 0 8px; font-size: 14px; text-transform: uppercase; color: var(--muted-color); }.citation-text, .citation-bibtex { width: 100%; min-height: 44px; border: 1px solid var(--border-color); border-radius: 6px; background: var(--surface-bg); padding: 8px; resize: none; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 13px; color: var(--text-color); white-space: pre-wrap; overflow-y: hidden; line-height: 1.4; }.references-block h3 { margin: 24px 0 8px; }.references-block .footnotes { margin-top: 8px; }.references-block .bibliography { margin-top: 8px; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354.distill-footer { contain: layout style; font-size: 0.8em; line-height: 1.7em; margin-top: 60px; margin-bottom: 0; border-top: 1px solid rgba(0, 0, 0, 0.1); color: rgba(0, 0, 0, 0.5); }.footer-inner { max-width: 1280px; margin: 0 auto; padding: 60px 16px 48px; display: grid; grid-template-columns: 220px minmax(0, 680px) 260px; gap: 32px; align-items: start; }// Utiliser la grille parent (3 colonnes comme .content-grid).citation-block,.references-block { display: contents; }.citation-block > h3,.references-block > h3 { grid-column: 1; font-size: 15px; margin: 0; }.citation-block > :not(h3),.references-block > :not(h3) { grid-column: 2; }.citation-block > h3 + *,.references-block > h3 + * { margin-top: 1em; }@media (max-width: 1100px) {.footer-inner { grid-template-columns: 1fr; gap: 16px; }.footer-inner > h3 { grid-column: auto; margin-top: 16px; }}.citation-block h3 { margin: 0 0 8px; }.citation-block h4 { margin: 16px 0 8px; font-size: 14px; text-transform: uppercase; color: var(--muted-color); }// Distill-like appendix citation styling.citation {font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;font-size: 11px;line-height: 15px;border-left: 1px solid rgba(0, 0, 0, 0.1);padding-left: 18px;border: 1px solid rgba(0,0,0,0.1);background: rgba(0, 0, 0, 0.02);padding: 10px 18px;border-radius: 3px;color: rgba(150, 150, 150, 1);overflow: hidden;margin-top: -12px;white-space: pre-wrap;word-wrap: break-word;}.citation a { color: rgba(0, 0, 0, 0.6); text-decoration: underline; }.citation.short { margin-top: -4px; }.references-block h3 { margin: 0; }.references-block .footnotes { margin-top: 8px; }.references-block .bibliography { margin-top: 8px; }// Distill-like list styling for references/footnotes.references-block ol { padding: 0 0 0 15px; }@media (min-width: 768px) { .references-block ol { padding: 0 0 0 30px; margin-left: -30px; } }.references-block li { margin-bottom: 1em; }.references-block a { color: rgba(0, 0, 0, 0.6); }@media (max-width: 1100px) {.footer-inner { display: block; padding: 40px 16px; }}
1 unmodified line2345672 unmodified lines10111213141516171849 unmodified lines6869707172731 unmodified line@use "./base" as *;@use "./layout" as *;@use "./components/footer" as *;/* Dark-mode form tweak */[data-theme="dark"] .plotly_input_container > select { background-color: #1a1f27; border-color: var(--border-color); color: var(--text-color); }2 unmodified lines[data-theme="dark"] .right-aside .aside-card { background: #12151b; border-color: rgba(255,255,255,.15); }[data-theme="dark"] .content-grid main pre { background: #12151b; border-color: rgba(255,255,255,.15); }[data-theme="dark"] .toc nav { border-left-color: rgba(255,255,255,.15); }[data-theme="dark"] .distill-footer { border-top-color: rgba(255,255,255,.15); }[data-theme="dark"] .citation-text,[data-theme="dark"] .citation-bibtex { background: #12151b; border-color: rgba(255,255,255,.15); color: var(--text-color); }/* Opt-in zoomable images */img[data-zoomable] { cursor: zoom-in; }49 unmodified lines// Plotly β fragments & controls// ============================================================================.plot-card { background: var(--code-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; margin: 8px 0; }.plotly-graph-div { width: 100% !important; min-height: 320px; }@media (max-width: 768px) { .plotly-graph-div { min-height: 260px; } }[id^="plot-"] { display: flex; flex-direction: column; align-items: center; gap: 15px; }1 unmodified line23456782 unmodified lines11121314151617181949 unmodified lines697071727374751 unmodified line@use "./base" as *;@use "./layout" as *;@use "./components/footer" as *;@use "./components/code" as *;/* Dark-mode form tweak */[data-theme="dark"] .plotly_input_container > select { background-color: #1a1f27; border-color: var(--border-color); color: var(--text-color); }2 unmodified lines[data-theme="dark"] .right-aside .aside-card { background: #12151b; border-color: rgba(255,255,255,.15); }[data-theme="dark"] .content-grid main pre { background: #12151b; border-color: rgba(255,255,255,.15); }[data-theme="dark"] .toc nav { border-left-color: rgba(255,255,255,.15); }[data-theme="dark"] .distill-footer { border-top-color: rgba(255,255,255,.15); color: rgba(200,200,200,.8); }[data-theme="dark"] .citation { background: rgba(255,255,255,0.04); border-color: rgba(255,255,255,.15); color: rgba(200,200,200,1); }[data-theme="dark"] .citation a { color: rgba(255,255,255,0.75); }/* Opt-in zoomable images */img[data-zoomable] { cursor: zoom-in; }49 unmodified lines// Plotly β fragments & controls// ============================================================================.plot-card { background: var(--code-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; margin: 8px 0; }.plot-card svg text { fill: var(--text-color) !important; }.plotly-graph-div { width: 100% !important; min-height: 320px; }@media (max-width: 768px) { .plotly-graph-div { min-height: 260px; } }[id^="plot-"] { display: flex; flex-direction: column; align-items: center; gap: 15px; }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240<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');
// Subtle background gradient const defs = svg.append('defs'); const grad = defs.append('radialGradient') .attr('id', 'spaceBg') .attr('cx', '50%') .attr('cy', '50%') .attr('r', '65%'); grad.append('stop').attr('offset', '0%').attr('stop-color', 'rgba(255,255,255,0.06)'); grad.append('stop').attr('offset', '60%').attr('stop-color', 'rgba(160,120,200,0.05)'); grad.append('stop').attr('offset', '100%').attr('stop-color', 'rgba(0,0,0,0)');
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'); 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: '6px 8px', borderRadius: '6px', fontSize: '12px', lineHeight: '1.3', border: '1px solid var(--border-color)', background: 'var(--surface-bg)', color: 'var(--text-color)', boxShadow: '0 2px 10px rgba(0,0,0,.15)', opacity: '0', transition: 'opacity .12s ease' }); container.appendChild(tip); }
// Final filter: remove small dots very close to the galaxy center (after placement) const centerHoleRadius = 0.08; // 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', (ev, i) => { 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; tip.innerHTML = `<div><strong>${labelOf(i)}</strong></div>` + `<div>Type: ${type}${arm ? ` (arm ${arm})` : ''}</div>` + `<div>Size: ${sizesPx[i].toFixed(1)} px</div>` + `<div>X: ${X[i].toFixed(2)} Β· Y: ${Y[i].toFixed(2)}</div>` + `<div>r: ${r.toFixed(3)} Β· z: ${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', () => { tip.style.opacity = '0'; tip.style.transform = 'translate(-9999px, -9999px)'; }), (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', (ev, i) => { 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; tip.innerHTML = `<div><strong>${labelOf(i)}</strong></div>` + `<div>Type: ${type}${arm ? ` (arm ${arm})` : ''}</div>` + `<div>Size: ${sizesPx[i].toFixed(1)} px</div>` + `<div>X: ${X[i].toFixed(2)} Β· Y: ${Y[i].toFixed(2)}</div>` + `<div>r: ${r.toFixed(3)} Β· z: ${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', () => { tip.style.opacity = '0'; tip.style.transform = 'translate(-9999px, -9999px)'; }) ); };
// 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>
51 unmodified lines5253545556575859606162636465666768697014 unmodified lines85868788899051 unmodified lines# Tailles: conserver l'échelle 5..10 pour cohérencesizes = (z_raw + 1) * 5# Filtrer les petits points proches du centre (esthétique du bulbe)# - on calcule le rayon elliptique normalisé# - on retire les points de petite taille situés trop près du centrecentral_radius_cut = 0.18min_size_center = 7.5r_total = np.sqrt(((x - cx) / a) ** 2 + ((y - cy) / b) ** 2)mask = ~((r_total <= central_radius_cut) & (sizes < min_size_center))# Appliquer le masquex = x[mask]y = y[mask]z_raw = z_raw[mask]sizes = sizes[mask]df = pd.DataFrame({"x": x,14 unmodified lines# Labels basés sur l'intensité centraledf["label"] = pd.Series(z_raw).apply(get_label)fig = go.Figure()fig.add_trace(go.Scattergl(51 unmodified lines5253545556575814 unmodified lines73747576777879808151 unmodified lines# Tailles: conserver l'échelle 5..10 pour cohérencesizes = (z_raw + 1) * 5# Suppression du filtre intermédiaire: on garde tous les points posés, on filtrera à la toute findf = pd.DataFrame({"x": x,14 unmodified lines# Labels basés sur l'intensité centraledf["label"] = pd.Series(z_raw).apply(get_label)# Ordonnancement pour le rendu: petits d'abord, gros ensuite (au-dessus)df = df.sort_values(by="z", ascending=True).reset_index(drop=True)fig = go.Figure()fig.add_trace(go.Scattergl(
1234567891011121314151617181920212223242526272829303132#!/usr/bin/env python3import markdownfrom pathlib import Pathimport sys
def convert_md_to_html(filepath): input_path = Path(filepath) output_path = input_path.with_suffix('.html') try: with open(input_path, 'r', encoding='utf-8') as md_file: text = md_file.read() html = markdown.markdown(text) with open(output_path, 'w', encoding='utf-8', errors='xmlcharrefreplace') as html_file: html_file.write(html) print(f"Converted {input_path} -> {output_path}") except FileNotFoundError: print(f"Error: Could not find file {input_path}") sys.exit(1) except Exception as e: print(f"Error converting file: {e}") sys.exit(1)
if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: python convert.py FILEPATH.md") sys.exit(1) convert_md_to_html(sys.argv[1])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110#!/usr/bin/env python3"""HTML to Markdown Converter
This script converts HTML files to Markdown format.Usage: python html_to_md.py input.html [output.md]If no output file is specified, it will use the input filename with .md extension."""
import sysimport osimport argparseimport html2textimport requestsfrom urllib.parse import urlparse
def is_url(path): """Check if the given path is a URL.""" parsed = urlparse(path) return parsed.scheme != '' and parsed.netloc != ''
def convert_html_to_markdown(html_content, **options): """Convert HTML content to Markdown.""" converter = html2text.HTML2Text() # Configure converter options converter.ignore_links = options.get('ignore_links', False) converter.ignore_images = options.get('ignore_images', False) converter.ignore_tables = options.get('ignore_tables', False) converter.body_width = options.get('body_width', 0) # 0 means no wrapping converter.unicode_snob = options.get('unicode_snob', True) # Use Unicode instead of ASCII converter.wrap_links = options.get('wrap_links', False) converter.inline_links = options.get('inline_links', True) # Convert HTML to Markdown return converter.handle(html_content)
def main(): parser = argparse.ArgumentParser(description='Convert HTML to Markdown') parser.add_argument('input', help='Input HTML file or URL') parser.add_argument('output', nargs='?', help='Output Markdown file (optional)') parser.add_argument('--ignore-links', action='store_true', help='Ignore links in the HTML') parser.add_argument('--ignore-images', action='store_true', help='Ignore images in the HTML') parser.add_argument('--ignore-tables', action='store_true', help='Ignore tables in the HTML') parser.add_argument('--body-width', type=int, default=0, help='Wrap text at this width (0 for no wrapping)') parser.add_argument('--unicode', action='store_true', help='Use Unicode characters instead of ASCII approximations') parser.add_argument('--wrap-links', action='store_true', help='Wrap links in angle brackets') parser.add_argument('--reference-links', action='store_true', help='Use reference style links instead of inline links') args = parser.parse_args() # Determine input if is_url(args.input): try: response = requests.get(args.input) response.raise_for_status() html_content = response.text except requests.exceptions.RequestException as e: print(f"Error fetching URL: {e}", file=sys.stderr) return 1 else: try: with open(args.input, 'r', encoding='utf-8') as f: html_content = f.read() except IOError as e: print(f"Error reading file: {e}", file=sys.stderr) return 1 # Configure conversion options options = { 'ignore_links': args.ignore_links, 'ignore_images': args.ignore_images, 'ignore_tables': args.ignore_tables, 'body_width': args.body_width, 'unicode_snob': args.unicode, 'wrap_links': args.wrap_links, 'inline_links': not args.reference_links, } # Convert HTML to Markdown markdown_content = convert_html_to_markdown(html_content, **options) # Determine output if args.output: output_file = args.output else: if is_url(args.input): # Generate a filename from the URL url_parts = urlparse(args.input) base_name = os.path.basename(url_parts.path) or 'index' if not base_name.endswith('.html'): base_name += '.html' output_file = os.path.splitext(base_name)[0] + '.md' else: # Generate a filename from the input file output_file = os.path.splitext(args.input)[0] + '.md' # Write output try: with open(output_file, 'w', encoding='utf-8') as f: f.write(markdown_content) print(f"Conversion successful! Output saved to: {output_file}") except IOError as e: print(f"Error writing file: {e}", file=sys.stderr) return 1 return 0
if __name__ == "__main__": sys.exit(main()).gitignore+2
Dockerfile+5-1
app/.astro/astro/content.d.ts+169
app/astro.config.mjs+4-1
app/package-lock.json
app/package.json
app/scripts/export-pdf.mjsAdded+216
app/src/components/Footer.astro+4-34
app/src/components/HtmlFragment.astro+1-1
app/src/components/Meta.astro+25
app/src/pages/article.mdx β app/src/content/article.mdxRenamed+58-58
app/src/content/fragments/banner.htmlAdded+244
app/src/fragments/bar.html β app/src/content/fragments/bar.htmlRenamed
app/src/fragments/heatmap.html β app/src/content/fragments/heatmap.htmlRenamed
app/src/fragments/line.html β app/src/content/fragments/line.htmlRenamed
app/src/content/fragments/palettes.htmlAdded+311
app/src/fragments/banner.htmlDeleted
app/src/pages/index.astro+28-6
app/src/styles/_base.scss+73-28
app/src/styles/_layout.scss+14-1
app/src/styles/components/_code.scssAdded+31
app/src/styles/components/_footer.scss+50-4
app/src/styles/global.scss+5-3
fragments/d3js/banner.htmlAdded+240
python/fragments/banner.py β fragments/plotly/banner.pyRenamed+4-13
python/fragments/bar.py β fragments/plotly/bar.pyRenamed
python/fragments/heatmap.py β fragments/plotly/heatmap.pyRenamed
python/fragments/line.py β fragments/plotly/line.pyRenamed
python/poetry.lock β fragments/plotly/poetry.lockRenamed
python/pyproject.toml β fragments/plotly/pyproject.tomlRenamed
python/convert.pyDeleted-32
python/convert_to_md.pyDeleted-110