Spaces:
Running
Running
thibaud frere commited on
Commit ·
c24ea90
1
Parent(s): b9e7b9b
update
Browse filesFiles changed (22)
- README.md-1
- app/.astro/astro/content.d.ts-185
- app/astro.config.mjs-2
- app/src/assets/images/moon.svg → app/src/assets/icones/moon.svgRenamed
- app/src/assets/images/sun.svg → app/src/assets/icones/sun.svgRenamed
- app/src/components/Note.astro+7-6
- app/src/components/ThemeToggle.astro+2-2
- app/src/content/article.mdx+11-46
- app/src/content/chapters/writing-you-content.mdx → app/src/content/chapters/available-blocks.mdxRenamed+6-83
- app/src/content/chapters/best-pratices.mdx+24-4
- app/src/content/chapters/getting-started.mdxAdded+42
- app/src/content/chapters/writing-your-content.mdxAdded+116
- app/src/content/fragments/banner.html+2-2
- app/src/content/fragments/color-picker.html+35-22
- app/src/content/fragments/d3-bar.html+6-5
- app/src/content/fragments/d3-line.html+9-9
- app/src/content/fragments/heatmap.html+1-1
- app/src/content/fragments/palettes.html+84-305
- app/src/pages/index.astro+51-11
- app/src/styles/_base.css+27-3
- app/src/styles/_variables.css+6-6
- app/src/styles/components/_poltly.css+2-2
11 unmodified lines1213141516171811 unmodified linesTO DO :- fix banner pour l'export pdf et la thumb- rename le titre ?- Vérifier la biliographie comment elle marche11 unmodified lines12131415161711 unmodified linesTO DO :- rename le titre ?- Vérifier la biliographie comment elle marche
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185declare module 'astro:content' {interface Render {'.mdx': Promise<{Content: import('astro').MarkdownInstance<{}>['Content'];headings: import('astro').MarkdownHeading[];remarkPluginFrontmatter: Record<string, any>;components: import('astro').MDXInstance<{}>['components'];}>;}}declare module 'astro:content' {interface RenderResult {Content: import('astro/runtime/server/index.js').AstroComponentFactory;headings: import('astro').MarkdownHeading[];remarkPluginFrontmatter: Record<string, any>;}interface Render {'.md': Promise<RenderResult>;}export interface RenderedContent {html: string;metadata?: {imagePaths: Array<string>;[key: string]: unknown;};}}declare module 'astro:content' {type Flatten<T> = T extends { [K: string]: infer U } ? U : never;export type CollectionKey = keyof AnyEntryMap;export type CollectionEntry<C extends CollectionKey> = Flatten<AnyEntryMap[C]>;export type ContentCollectionKey = keyof ContentEntryMap;export type DataCollectionKey = keyof DataEntryMap;type AllValuesOf<T> = T extends any ? T[keyof T] : never;type ValidContentEntrySlug<C extends keyof ContentEntryMap> = AllValuesOf<ContentEntryMap[C]>['slug'];/** @deprecated Use `getEntry` instead. */export function getEntryBySlug<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(collection: C,// Note that this has to accept a regular string too, for SSRentrySlug: E,): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;/** @deprecated Use `getEntry` instead. */export function getDataEntryById<C extends keyof DataEntryMap, E extends keyof DataEntryMap[C]>(collection: C,entryId: E,): Promise<CollectionEntry<C>>;export function getCollection<C extends keyof AnyEntryMap, E extends CollectionEntry<C>>(collection: C,filter?: (entry: CollectionEntry<C>) => entry is E,): Promise<E[]>;export function getCollection<C extends keyof AnyEntryMap>(collection: C,filter?: (entry: CollectionEntry<C>) => unknown,): Promise<CollectionEntry<C>[]>;export function getEntry<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(entry: {collection: C;slug: E;}): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof DataEntryMap,E extends keyof DataEntryMap[C] | (string & {}),>(entry: {collection: C;id: E;}): E extends keyof DataEntryMap[C]? Promise<DataEntryMap[C][E]>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(collection: C,slug: E,): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof DataEntryMap,E extends keyof DataEntryMap[C] | (string & {}),>(collection: C,id: E,): E extends keyof DataEntryMap[C]? Promise<DataEntryMap[C][E]>: Promise<CollectionEntry<C> | undefined>;/** Resolve an array of entry references from the same collection */export function getEntries<C extends keyof ContentEntryMap>(entries: {collection: C;slug: ValidContentEntrySlug<C>;}[],): Promise<CollectionEntry<C>[]>;export function getEntries<C extends keyof DataEntryMap>(entries: {collection: C;id: keyof DataEntryMap[C];}[],): Promise<CollectionEntry<C>[]>;export function render<C extends keyof AnyEntryMap>(entry: AnyEntryMap[C][string],): Promise<RenderResult>;export function reference<C extends keyof AnyEntryMap>(collection: C,): import('astro/zod').ZodEffects<import('astro/zod').ZodString,C extends keyof ContentEntryMap? {collection: C;slug: ValidContentEntrySlug<C>;}: {collection: C;id: keyof DataEntryMap[C];}>;// Allow generic `string` to avoid excessive type errors in the config// if `dev` is not running to update as you edit.// Invalid collection names will be caught at build time.export function reference<C extends string>(collection: C,): import('astro/zod').ZodEffects<import('astro/zod').ZodString, never>;type ReturnTypeOrOriginal<T> = T extends (...args: any[]) => infer R ? R : T;type InferEntrySchema<C extends keyof AnyEntryMap> = import('astro/zod').infer<ReturnTypeOrOriginal<Required<ContentConfig['collections'][C]>['schema']>>;type ContentEntryMap = {"chapters": {"best-pratices.mdx": {id: "best-pratices.mdx";slug: "best-pratices";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"writing-you-content.mdx": {id: "writing-you-content.mdx";slug: "writing-you-content";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };};};type DataEntryMap = {"fragments": Record<string, {id: string;collection: "fragments";data: any;}>;};type AnyEntryMap = ContentEntryMap & DataEntryMap;export type ContentConfig = never;}
2 unmodified lines345678920 unmodified lines303132333435362 unmodified linesimport mermaid from 'astro-mermaid';import remarkMath from 'remark-math';import rehypeKatex from 'rehype-katex';import remarkToc from 'remark-toc';import remarkFootnotes from 'remark-footnotes';import rehypeSlug from 'rehype-slug';import rehypeAutolinkHeadings from 'rehype-autolink-headings';20 unmodified lines}},remarkPlugins: [[remarkToc, { heading: 'Table of Contents', maxDepth: 3 }],remarkMath,[remarkFootnotes, { inlineNotes: true }]],2 unmodified lines34567820 unmodified lines2930313233342 unmodified linesimport mermaid from 'astro-mermaid';import remarkMath from 'remark-math';import rehypeKatex from 'rehype-katex';import remarkFootnotes from 'remark-footnotes';import rehypeSlug from 'rehype-slug';import rehypeAutolinkHeadings from 'rehype-autolink-headings';20 unmodified lines}},remarkPlugins: [remarkMath,[remarkFootnotes, { inlineNotes: true }]],
1234567891011121314151617181920212223---const { title = "Note", emoji = "📝", class: className, ...props } = Astro.props;const wrapperClass = ["note", className].filter(Boolean).join(" ");---<div class={wrapperClass} {...props}><div class="note__header"><span class="note__emoji">{emoji}</span>{title && <span class="note__title">{title}</span>}</div><div class="note__content"><slot /></div></div><style>.note { background: var(--surface-bg); border-left: 2px solid rgba(0, 0, 0, 0.1); border-radius: 4px; padding: 10px 14px; margin: 12px 0; }.note__header { display: flex; align-items: center; gap: 6px; font-weight: 600; color: var(--text-color); margin-bottom: 6px; }.note__emoji { font-size: 24px; line-height: 1; }.note__title { font-size: 13px; letter-spacing: .2px; }.note__content { color: var(--text-color); font-size: 0.95rem; }</style>123456789101112131415161718192021222324---const { title, emoji, class: className, ...props } = Astro.props;const wrapperClass = ["note", className].filter(Boolean).join(" ");const hasHeader = (emoji && String(emoji).length > 0) || (title && String(title).length > 0);---<div class={wrapperClass} {...props}>{hasHeader && <div class="note__header">{emoji && <span class="note__emoji">{emoji}</span>}{title && <span class="note__title">{title}</span>}</div>}<div class="note__content"><slot /></div></div><style>.note { background: var(--surface-bg); border-left: 2px solid var(--border-color); border-radius: 4px; padding: 10px 14px; margin: 12px 0; }.note__header { display: flex; align-items: center; gap: 6px; font-weight: 600; color: var(--text-color); margin-bottom: 6px; }.note__emoji { font-size: 24px; line-height: 1; }.note__title { font-size: 13px; letter-spacing: .2px; }.note__content { color: var(--text-color); font-size: 0.95rem; }.note__content > p:last-of-type { margin-bottom: 0 !important; }</style>
123456---import sunIconUrl from "../assets/images/sun.svg?url";import moonIconUrl from "../assets/images/moon.svg?url";---<button id="theme-toggle" aria-label="Toggle color theme"><img class="icon light" src={sunIconUrl} alt="light" width="20" height="20" />123456---import sunIconUrl from "../assets/icones/sun.svg?url";import moonIconUrl from "../assets/icones/moon.svg?url";---<button id="theme-toggle" aria-label="Toggle color theme"><img class="icon light" src={sunIconUrl} alt="light" width="20" height="20" />
1234517 unmodified lines232425262728293055 unmodified lines868788899091923 unmodified lines96979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151---title: "From Idea to Interaction:\n A Modern Template for Scientific Writing"subtitle: "Markdown-first research article template with math, citations, and interactive figures."description: "A modern, MDX-first research article template with math, citations, and interactive figures."17 unmodified linesimport audioDemo from "../assets/audio/audio-example.wav";import Aside from "../components/Aside.astro";import visualPoster from "../assets/images/visual-vocabulary-poster.png";import BestPractices from "./chapters/best-pratices.mdx";import WritingYourContent from "./chapters/writing-you-content.mdx";<Aside>Welcome to this single-page research article template built with **Markdown**.55 unmodified linesThis project is heavely inspired by [**Distill**](https://distill.pub) (2016–2021), which championed clear, web‑native scholarship.### Notable examples of excellent scientific articlesA short, curated list of well‑designed and often interactive work:3 unmodified lines- **ConvNetJS — Neural networks in the browser**: [cs.stanford.edu/people/karpathy/convnetjs](http://cs.stanford.edu/people/karpathy/convnetjs/)- **Explorable Explanations — Collection**: [explorableexplanations.com](http://explorableexplanations.com/)- **Distill — Why Momentum Really Works**: [distill.pub/2017/momentum](https://distill.pub/2017/momentum/)## Getting Started### Installation<Aside>```bashgit lfs installgit lfs pullcd appnpm install```<Fragment slot="aside">You can use yarn alternatively to npm.</Fragment></Aside>### Development```bashnpm run dev```### Build```bashnpm run build```Serving the `dist/` directory on any static host is enough to deliver the site.A [slug-title].pdf and thumb.jpg are also generated at build time. You can find them in the public folder.### DeployThe easiest way to get online is to clone [this Hugging Face Space](https://huggingface.co/spaces/tfrere/science-blog-template) and push your changes; every push triggers an automatic build and deploy.### Large files (Git LFS)**Track binaries** (e.g., `.png`, `.wav`) with **Git LFS** to keep the repository lean. This project is preconfigured to store such files via **LFS**.<WritingYourContent /><BestPractices />## ConclusionsThis template provides a **practical baseline** for writing and sharing technical articles with **math**, **citations**, and **interactive figures**. **Start simple**, **iterate** on structure and style, and keep content **maintainable** for future readers and collaborators.1234517 unmodified lines232425262728293031323355 unmodified lines899091929394953 unmodified lines99100101102103104105106107108109110111112113114115116---title: "From Idea to Life:\n A Modern Template for Scientific Writing"subtitle: "Markdown-first research article template with math, citations, and interactive figures."description: "A modern, MDX-first research article template with math, citations, and interactive figures."17 unmodified linesimport audioDemo from "../assets/audio/audio-example.wav";import Aside from "../components/Aside.astro";import visualPoster from "../assets/images/visual-vocabulary-poster.png";import BestPractices from "./chapters/best-pratices.mdx";import WritingYourContent from "./chapters/writing-your-content.mdx";import AvailableBlocks from "./chapters/available-blocks.mdx";import GettingStarted from "./chapters/getting-started.mdx";<Aside>Welcome to this single-page research article template built with **Markdown**.55 unmodified linesThis project is heavely inspired by [**Distill**](https://distill.pub) (2016–2021), which championed clear, web‑native scholarship.{/* ### Notable examples of excellent scientific articlesA short, curated list of well‑designed and often interactive work:3 unmodified lines- **ConvNetJS — Neural networks in the browser**: [cs.stanford.edu/people/karpathy/convnetjs](http://cs.stanford.edu/people/karpathy/convnetjs/)- **Explorable Explanations — Collection**: [explorableexplanations.com](http://explorableexplanations.com/)- **Distill — Why Momentum Really Works**: [distill.pub/2017/momentum](https://distill.pub/2017/momentum/)*/}<GettingStarted /><WritingYourContent /><AvailableBlocks /><BestPractices />## ConclusionThis template provides a **practical baseline** for writing and sharing technical articles with **math**, **citations**, and **interactive figures**. **Start simple**, **iterate** on structure and style, and keep content **maintainable** for future readers and collaborators.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586872 unmodified lines909192939495969798245 unmodified lines344345346347348349350351352{/* IMPORTS */}import { Image } from 'astro:assets';import placeholder from '../../assets/images/placeholder.png';import Aside from '../../components/Aside.astro';import Wide from '../../components/Wide.astro';import FullBleed from '../../components/FullBleed.astro';import HtmlFragment from '../../components/HtmlFragment.astro';import audioDemo from '../../assets/audio/audio-example.wav';## Writing Your Content### IntroductionYour article lives in two places:- `app/src/content/` — where you can find the article.mdx, bibliography.bib and html fragments.- `app/src/assets/` — images, audio, and other static assets. (handled by git lfs)This is MDX, its basically a markdown file with html and astro components.The **initial skeleton** of an article looks like this.```mdx{/* HEADER */}---title: "This is the main title"subtitle: "This will be displayed just below the banner"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors:- "John Doe"- "Alice Martin"- "Robert Brown"affiliation: "Hugging Face"published: "Feb 19, 2025"tags:- research- templateogImage: "https://example.com/your-og-image.png"---{/* 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" />```### Chapters**If** your article becomes **too long**, you can **organize** it into **separate chapters**.Simply **create a new file** in the `app/src/content/chapters` **directory**.Then, **include** your new chapter in the main article by adding the following lines:```mdximport MyChapter from './chapters/my-chapter.mdx';<MyChapter />```You can see an example of this in the <a href="">`app/src/content/chapters/best-pratices.mdx`</a> file.### ThemeAll **interactive elements** (buttons, inputs, cards, etc.) are themed with the **primary color** you choose. Feel free to update this color to match your **brand**.You can **override** the theme by changing the main variable in the `app/src/styles/_variables.css` file.You can use the **color picker** below to choose the right color.<Aside><div className=""><HtmlFragment src="color-picker.html" /></div><Fragment slot="aside">There is also a color <a href="#use-the-right-color">palette generator</a> that will help you choose the right color for your data visualizations.</Fragment></Aside>### Available blocksAll the following blocks are available in the article.mdx file. You can also create your own blocks by creating a new component in the components folder.2 unmodified lines<a className="button" href="#math">Math</a><a className="button" href="#images">Images</a><a className="button" href="#code-blocks">Code</a><a className="button" href="#citations-and-notes">Citations & notes</a><a className="button" href="#asides">Asides</a><a className="button" href="#minimal-table">Table</a><a className="button" href="#audio">Audio</a><a className="button" href="#embeds">Embeds</a></div>245 unmodified lines<div className="plot-card"><HtmlFragment src="line.html" /></div><div className="plot-card"><HtmlFragment src="bar.html" /></div><small className="muted">Example</small>```mdx1234567891011122 unmodified lines15161718192021222324245 unmodified lines270271272273274275import { Image } from 'astro:assets';import placeholder from '../../assets/images/placeholder.png';import audioDemo from '../../assets/audio/audio-example.wav';import HtmlFragment from '../../components/HtmlFragment.astro';import Aside from '../../components/Aside.astro';import Wide from '../../components/Wide.astro';import FullBleed from '../../components/FullBleed.astro';## Available blocksAll the following blocks are available in the article.mdx file. You can also create your own blocks by creating a new component in the components folder.2 unmodified lines<a className="button" href="#math">Math</a><a className="button" href="#images">Images</a><a className="button" href="#code-blocks">Code</a><a className="button" href="#mermaid-diagrams">Mermaid</a><a className="button" href="#citations-and-notes">Citations & notes</a><a className="button" href="#placement">Placement</a><a className="button" href="#minimal-table">Minimal table</a><a className="button" href="#audio">Audio</a><a className="button" href="#embeds">Embeds</a></div>245 unmodified lines<div className="plot-card"><HtmlFragment src="line.html" /></div><small className="muted">Example</small>```mdx
1234568 unmodified lines15161718192014 unmodified lines353637383940414243444546import { Image } from 'astro:assets';import visualPoster from '../../assets/images/visual-vocabulary-poster.png';## Best Practices8 unmodified lines**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 colorA 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**.14 unmodified linesPicking 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={visualPoster.src} target="_blank" rel="noopener noreferrer"><Image src={visualPoster} alt="Visual Vocabulary: choosing the right chart by task" /></a><figcaption>A handy reference to select chart types by purpose. Click to enlarge.— <a href="https://ft-interactive.github.io/visual-vocabulary/" target="_blank" rel="noopener noreferrer">Website</a></figcaption></figure>12345678 unmodified lines161718192021222324252627282930313233343536373839404114 unmodified lines5657585960616263646566import { Image } from 'astro:assets';import visualPoster from '../../assets/images/visual-vocabulary-poster.png';import Note from '../../components/Note.astro';## Best Practices8 unmodified lines**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.<div className="note-grid" style="display:grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; align-items: start;"><Note>For example, in linear regression with features $x \in \mathbb{R}^d$, weights $w \in \mathbb{R}^d$, and bias $b$, the prediction is:$$\hat{y} = w^\top x + b$$A common training objective is the mean squared error over $N$ samples:$$\mathcal{L}(w,b) = \frac{1}{N} \sum_{i=1}^{N} (w^\top x_i + b - y_i)^2$$Interpretation: the model fits a hyperplane that minimizes the average squared prediction error.</Note></div>{/* ### Use the right colorA 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**.14 unmodified linesPicking 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://raw.githubusercontent.com/Financial-Times/chart-doctor/refs/heads/main/visual-vocabulary/poster.png"} target="_blank" rel="noopener noreferrer"><Image src={visualPoster} alt="Visual Vocabulary: choosing the right chart by task" /></a><figcaption>A handy reference to select chart types by purpose — click to enlarge.</figcaption></figure>
123456789101112131415161718192021222324252627282930313233343536373839404142import Aside from '../../components/Aside.astro';
## Getting Started
### Installation
<Aside>```bashgit lfs installgit lfs pullcd appnpm install```<Fragment slot="aside"> You can also use yarn. </Fragment></Aside>
### Development
```bashnpm run dev```
### Build
```bashnpm run build```
Serving the `dist/` directory on any static host is enough to deliver the site.
A [slug-title].pdf and thumb.jpg are also generated at build time. You can find them in the public folder.
### Deploy
The recommended way is to **clone this [🤗 Hugging Face Space](https://huggingface.co/spaces/tfrere/science-blog-template)**.
Once you have cloned the Space, **just push your changes** to your repository.
**Every push automatically triggers a build and deploy** — no extra configuration needed.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116{/* IMPORTS */}import { Image } from 'astro:assets';import placeholder from '../../assets/images/placeholder.png';import Aside from '../../components/Aside.astro';import Wide from '../../components/Wide.astro';import FullBleed from '../../components/FullBleed.astro';import HtmlFragment from '../../components/HtmlFragment.astro';import audioDemo from '../../assets/audio/audio-example.wav';
## Writing Your Content
### Introduction
Your article lives in two places
- `app/src/content/` — where you can find the `article.mdx`, `bibliography.bib` and html fragments.- `app/src/assets/` — images, audio, and other static assets. (handled by git lfs)
The `article.mdx` file is a markdown file with html and astro components. It is the main file that contains your article.
<small className="muted">Example</small>```mdx{/* HEADER */}---title: "This is the main title"subtitle: "This will be displayed just below the banner"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors: - "John Doe" - "Alice Martin" - "Robert Brown"affiliation: "Hugging Face"published: "Feb 19, 2025"tags: - research - templateogImage: "https://example.com/your-og-image.png"---
{/* IMPORTS */}import { Image } from 'astro:assets';import placeholder from '../assets/images/placeholder.jpg';
{/* CONTENT */}# Hello, world
This is a short paragraph written in Markdown. Below is an example image:
<Image src={placeholder} alt="Example image" />```
### Markdown
You can use **markdown** to write your content. Here is the complete [markdown documentation](https://www.markdownguide.org/basic-syntax/).
<small className="muted">Example</small>```mdx# This is the main title
This is a short paragraph containing **bold** and *italic* text.
## This is a second level heading
- This is a list item- This is a second list item- This is a third list item```
### Chapters
**If** your article becomes **too long** for one file, you can **organize** it into **separate chapters**.
Simply **create a new file** in the `app/src/content/chapters` **directory**. Then, **include** your new chapter in the main article.
<small className="muted">Example</small>```mdximport MyChapter from './chapters/my-chapter.mdx';
<MyChapter />```
You can see an example of this in the <a target="_blank" href="https://huggingface.co/spaces/tfrere/research-article-template/blob/main/app/src/content/chapters/best-pratices.mdx">app/src/content/chapters/best-pratices.mdx</a> file.
### Table of contents The **Table of contents** is generated **automatically** from your **H2–H4** headings. Keep headings **short** and **descriptive**; links work on **desktop** and **mobile**.
### Theme
All **interactive elements** (buttons, inputs, cards, etc.) are themed with the **primary color** you choose.
You can **update this main color** to match your brand by changing the `--primary-color` variable in the `app/src/styles/_variables.css` file.
Use the **color picker** below to see how the primary color affects the theme.
#### Brand color
<Aside> <HtmlFragment src="color-picker.html" /> <Fragment slot="aside"> You can use the color picker to select the right color. Here is an example of an <a href="#">interactive element</a>. </Fragment></Aside>
#### Color palettes
Here is a suggestion of **color palettes** for your **data visualizations** that align with your **brand identity**. These palettes are generated from your `--primary-color`.
<HtmlFragment src="palettes.html" />105 unmodified lines106107108109110111112113105 unmodified linesconst strokeColor = isDark ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.12)';// Group with blend mode so points softly accumulate lightconst g = svg.selectAll('g.points').data([0]).join('g').attr('class', 'points').style('mix-blend-mode', 'screen');// Ensure container can host an absolute tooltipcontainer.style.position = container.style.position || 'relative';105 unmodified lines106107108109110111112113105 unmodified linesconst strokeColor = isDark ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.12)';// Group for points (no blend mode for better print/PDF visibility)const g = svg.selectAll('g.points').data([0]).join('g').attr('class', 'points');// Ensure container can host an absolute tooltipcontainer.style.position = container.style.position || 'relative';
12345678910111213141516171819202122232425262728293031323323 unmodified lines5758596061626331 unmodified lines959697989910012 unmodified lines11311411511611711811912019 unmodified lines1401411421431441451461471481491501511521531545 unmodified lines160161162163164165166<div class="color-picker" style="width:100%; margin: 10px 0;"><style>.color-picker .picker__stack { display:flex; flex-direction:column; gap:12px; }.color-picker .current-card { display:flex; flex-direction: column; align-items:stretch; gap:12px; padding:14px 16px; border:1px solid var(--border-color); background: var(--surface-bg); border-radius: 12px; }.color-picker .current-main { display:flex; align-items:center; gap:12px; min-width: 0; }.color-picker .current-swatch { width: 32px; height: 32px; border-radius: 8px; border: 1px solid var(--border-color); }.color-picker .current-text { display:flex; flex-direction: column; line-height: 1.2; min-width: 0; }.color-picker .current-name { font-size: 14px; font-weight: 800; color: var(--text-color); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: clamp(140px, 28vw, 260px); }.color-picker .current-hex, .color-picker .current-extra { font-size: 11px; color: var(--muted-color); letter-spacing: .02em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: clamp(140px, 28vw, 260px); }/* theme preview styles removed */.color-picker .picker__bar { display:flex; align-items:center; gap:12px; }.color-picker .picker__label { font-weight:700; font-size: 13px; color: var(--text-color); }.color-picker .hue-slider { position:relative; height:16px; 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; flex: 1 1 320px; min-width: 200px; }.color-picker .hue-knob { position:absolute; top:50%; left:93.6%; width:14px; height:14px; border-radius:50%; border:2px solid #fff; transform:translate(-50%, -50%); background: var(--surface-bg); z-index: 2; box-shadow: 0 0 0 1px rgba(0,0,0,.05); }.color-picker .hue-slider:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }.color-picker .hue-value { font-variant-numeric: tabular-nums; color: var(--muted-color); min-width: 54px; text-align: right; }@media (max-width: 560px) { .color-picker .picker__bar { gap:8px; } }</style><div class="picker__stack"><div class="current-card"><div class="current-main"><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 class="current-extra current-lch">—</div><div class="current-extra current-rgb">—</div></div></div><div class="picker__bar"><div class="picker__label">Hue</div><div class="hue-slider" role="slider" aria-label="Hue" aria-valuemin="0" aria-valuemax="360" aria-valuenow="337" tabindex="0"><div class="hue-knob"></div>23 unmodified lines};// Minimal embedded color-name list (same as palettes)const COLOR_NAMES = [{"name":"Candy Apple Red","hex":"#ff0800"},{"name":"Boiling Magma","hex":"#ff3300"},{"name":"Aerospace Orange","hex":"#ff4f00"},{"name":"Burtuqali Orange","hex":"#ff6700"},{"name":"American Orange","hex":"#ff8b00"},{"name":"Cheese","hex":"#ffa600"},{"name":"Amber","hex":"#ffbf00"},{"name":"Demonic Yellow","hex":"#ffe700"},{"name":"Bat-Signal","hex":"#feff00"},{"name":"Bitter Lime","hex":"#cfff00"},{"name":"Electric Lime","hex":"#ccff00"},{"name":"Bright Yellow Green","hex":"#9dff00"},{"name":"Lasting Lime","hex":"#88ff00"},{"name":"Bright Green","hex":"#66ff00"},{"name":"Chlorophyll Green","hex":"#4aff00"},{"name":"Green Screen","hex":"#22ff00"},{"name":"Electric Pickle","hex":"#00ff04"},{"name":"Acid","hex":"#00ff22"},{"name":"Lucent Lime","hex":"#00ff33"},{"name":"Cathode Green","hex":"#00ff55"},{"name":"Booger Buster","hex":"#00ff77"},{"name":"Green Gas","hex":"#00ff99"},{"name":"Enthusiasm","hex":"#00ffaa"},{"name":"Ice Ice Baby","hex":"#00ffdd"},{"name":"Master Sword Blue","hex":"#00ffee"},{"name":"Agressive Aqua","hex":"#00fbff"},{"name":"Vivid Sky Blue","hex":"#00ccff"},{"name":"Capri","hex":"#00bfff"},{"name":"Sky of Magritte","hex":"#0099ff"},{"name":"Azure","hex":"#007fff"},{"name":"Blue Ribbon","hex":"#0066ff"},{"name":"Blinking Blue","hex":"#0033ff"},{"name":"Icelandic Water","hex":"#0011ff"},{"name":"Blue","hex":"#0000ff"},{"name":"Blue Pencil","hex":"#2200ff"},{"name":"Electric Ultramarine","hex":"#3f00ff"},{"name":"Aladdin's Feather","hex":"#5500ff"},{"name":"Purple Climax","hex":"#8800ff"},{"name":"Amethyst Ganzstar","hex":"#8f00ff"},{"name":"Electric Purple","hex":"#bf00ff"},{"name":"Phlox","hex":"#df00ff"},{"name":"Brusque Pink","hex":"#ee00ff"},{"name":"Bright Magenta","hex":"#ff08e8"},{"name":"Brutal Pink","hex":"#ff00bb"},{"name":"Mean Girls Lipstick","hex":"#ff00ae"},{"name":"Big Bang Pink","hex":"#ff0099"},{"name":"Flaming Hot Flamingoes","hex":"#ff005d"},{"name":"Blazing Dragonfruit","hex":"#ff0054"},{"name":"Carmine Red","hex":"#ff0038"},{"name":"Bright Red","hex":"#ff000d"}];if (!window.__colorNames) window.__colorNames = COLOR_NAMES;// Shared event bus so multiple instances stay in sync31 unmodified linesconst bus = window.__colorPickerBus;const instanceId = Math.random().toString(36).slice(2);const getName = (hex) => {const list = (window.__colorNames && window.__colorNames.length) ? window.__colorNames : COLOR_NAMES;if (list && window.chroma) {12 unmodified lines};const updateUI = (h, adjusting) => {const pct = (h / 360) * 100;if (knob) knob.style.left = pct + '%';if (hueValue) hueValue.textContent = `${Math.round(h)}°`;if (slider) slider.setAttribute('aria-valuenow', String(Math.round(h)));// Use LCH for consistent chroma across hues19 unmodified linesconst hoverL = Math.max(0, Math.min(100, L - 8));const hoverHex = chroma.lch(hoverL, C, h).hex();const rootEl = document.documentElement;rootEl.style.setProperty('--primary', baseHex);rootEl.style.setProperty('--primary-hover', hoverHex);};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));return t * 360;};5 unmodified lines// Init depuis la couleur de thème si disponibletry {const cssPrimary = getComputedStyle(document.documentElement).getPropertyValue('--primary').trim();if (cssPrimary) {const initH = chroma(cssPrimary).get('hsl.h') || 0;updateUI(initH, false);12345678910111213141516171819202122232425262728293031323334353623 unmodified lines6061626364656631 unmodified lines989910010110210310410510610712 unmodified lines12012112212312412512612712812913019 unmodified lines1501511521531541551561571581591601611621631641651661675 unmodified lines173174175176177178179<div class="color-picker" style="width:100%; margin: 10px 0;"><style>.color-picker .picker__stack { display:flex; flex-direction:column; gap:12px; }.color-picker .current-card { display:grid; grid-template-columns: 30% 70%; align-items: center; gap:14px; padding:14px 32px 14px 16px; border:1px solid var(--border-color); background: var(--surface-bg); border-radius: 12px; }.color-picker .current-left { display:flex; flex-direction: column; gap:8px; min-width: 0; }.color-picker .current-right { display:flex; flex-direction: column; gap:8px; padding-left: 14px; border-left: 1px solid var(--border-color); }.color-picker .current-main { display:flex; align-items:center; gap:12px; min-width: 0; }.color-picker .current-swatch { width: 32px; height: 32px; border-radius: 8px; border: 1px solid var(--border-color); }.color-picker .current-text { display:flex; flex-direction: column; line-height: 1.2; min-width: 0; }.color-picker .current-name { font-size: 14px; font-weight: 800; color: var(--text-color); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: clamp(140px, 28vw, 260px); }.color-picker .current-hex, .color-picker .current-extra { font-size: 11px; color: var(--muted-color); letter-spacing: .02em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: clamp(140px, 28vw, 260px); }/* theme preview styles removed */.color-picker .picker__label { font-weight:700; font-size: 12px; color: var(--muted-color); text-transform: uppercase; letter-spacing: .02em; }.color-picker .hue-slider { position:relative; height:16px; 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; flex: 1 1 auto; min-width: 200px; }.color-picker .hue-knob { position:absolute; top:50%; left:93.6%; width:14px; height:14px; border-radius:50%; border:2px solid #fff; transform:translate(-50%, -50%); background: var(--surface-bg); z-index: 2; box-shadow: 0 0 0 1px rgba(0,0,0,.05); }.color-picker .hue-slider:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 2px; }.color-picker .hue-value { font-variant-numeric: tabular-nums; color: var(--muted-color); font-size: 12px; }@media (max-width: 720px) { .color-picker .current-card { grid-template-columns: 1fr; } .color-picker .current-right { padding-left: 0; border-left: none; } }</style><div class="picker__stack"><div class="current-card"><div class="current-left"><div class="current-main"><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 class="current-extra current-lch">—</div><div class="current-extra current-rgb">—</div></div></div></div><div class="current-right"><div class="picker__label">Hue</div><div class="hue-slider" role="slider" aria-label="Hue" aria-valuemin="0" aria-valuemax="360" aria-valuenow="337" tabindex="0"><div class="hue-knob"></div>23 unmodified lines};// Minimal embedded color-name list (same as palettes)const COLOR_NAMES = [{"name":"Candy Apple Red","hex":"#ff0800"},{"name":"Boiling Magma","hex":"#ff3300"},{"name":"Aerospace Orange","hex":"#ff4f00"},{"name":"Burtuqali Orange","hex":"#ff6700"},{"name":"American Orange","hex":"#ff8b00"},{"name":"Cheese","hex":"#ffa600"},{"name":"Amber","hex":"#ffbf00"},{"name":"Demonic Yellow","hex":"#ffe700"},{"name":"Bat-Signal","hex":"#feff00"},{"name":"Bitter Lime","hex":"#cfff00"},{"name":"Electric Lime","hex":"#ccff00"},{"name":"Bright Yellow Green","hex":"#9dff00"},{"name":"Lasting Lime","hex":"#88ff00"},{"name":"Bright Green","hex":"#66ff00"},{"name":"Chlorophyll Green","hex":"#4aff00"},{"name":"Green Screen","hex":"#22ff00"},{"name":"Electric Pickle","hex":"#00ff04"},{"name":"Acid","hex":"#00ff22"},{"name":"Lucent Lime","hex":"#00ff33"},{"name":"Cathode Green","hex":"#00ff55"},{"name":"Booger Buster","hex":"#00ff77"},{"name":"Green Gas","hex":"#00ff99"},{"name":"Enthusiasm","hex":"#00ffaa"},{"name":"Ice Ice Baby","hex":"#00ffdd"},{"name":"Master Sword Blue","hex":"#00ffee"},{"name":"Agressive Aqua","hex":"#00fbff"},{"name":"Vivid Sky Blue","hex":"#00ccff"},{"name":"Capri","hex":"#00bfff"},{"name":"Sky of Magritte","hex":"#0099ff"},{"name":"Azure","hex":"#007fff"},{"name":"Blue Ribbon","hex":"#0066ff"},{"name":"Blinking Blue","hex":"#0033ff"},{"name":"Icelandic Water","hex":"#0011ff"},{"name":"Blue","hex":"#0000ff"},{"name":"Blue Pencil","hex":"#2200ff"},{"name":"Electric Ultramarine","hex":"#3f00ff"},{"name":"Aladdin's Feather","hex":"#5500ff"},{"name":"Purple Climax","hex":"#8800ff"},{"name":"Amethyst Ganzstar","hex":"#8f00ff"},{"name":"Electric Purple","hex":"#bf00ff"},{"name":"Phlox","hex":"#df00ff"},{"name":"Brusque Pink","hex":"#ee00ff"},{"name":"Bright Magenta","hex":"#ff08e8"},{"name":"Big bang Pink","hex":"#ff00bb"},{"name":"Mean Girls Lipstick","hex":"#ff00ae"},{"name":"Pink","hex":"#ff0099"},{"name":"Hot Flamingoes","hex":"#ff005d"},{"name":"Blazing Dragonfruit","hex":"#ff0054"},{"name":"Carmine Red","hex":"#ff0038"},{"name":"Bright Red","hex":"#ff000d"}];if (!window.__colorNames) window.__colorNames = COLOR_NAMES;// Shared event bus so multiple instances stay in sync31 unmodified linesconst bus = window.__colorPickerBus;const instanceId = Math.random().toString(36).slice(2);const getKnobRadius = () => {try { const w = knob ? knob.getBoundingClientRect().width : 0; return w ? w / 2 : 8; } catch { return 8; }};const getName = (hex) => {const list = (window.__colorNames && window.__colorNames.length) ? window.__colorNames : COLOR_NAMES;if (list && window.chroma) {12 unmodified lines};const updateUI = (h, adjusting) => {const rect = slider.getBoundingClientRect();const r = Math.min(getKnobRadius(), Math.max(0, rect.width / 2 - 1));const t = Math.max(0, Math.min(1, (h / 360)));const leftPx = r + t * Math.max(0, (rect.width - 2 * r));if (knob) knob.style.left = (leftPx / rect.width * 100) + '%';if (hueValue) hueValue.textContent = `${Math.round(h)}°`;if (slider) slider.setAttribute('aria-valuenow', String(Math.round(h)));// Use LCH for consistent chroma across hues19 unmodified linesconst hoverL = Math.max(0, Math.min(100, L - 8));const hoverHex = chroma.lch(hoverL, C, h).hex();const rootEl = document.documentElement;rootEl.style.setProperty('--primary-color', baseHex);rootEl.style.setProperty('--primary-color-hover', hoverHex);};const getHueFromEvent = (ev) => {const rect = slider.getBoundingClientRect();const clientX = ev.touches ? ev.touches[0].clientX : ev.clientX;const x = clientX - rect.left;const r = Math.min(getKnobRadius(), Math.max(0, rect.width / 2 - 1));const effX = Math.max(r, Math.min(rect.width - r, x));const denom = Math.max(1, rect.width - 2 * r);const t = (effX - r) / denom;return t * 360;};5 unmodified lines// Init depuis la couleur de thème si disponibletry {const cssPrimary = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();if (cssPrimary) {const initH = chroma(cssPrimary).get('hsl.h') || 0;updateUI(initH, false);
3 unmodified lines456789101119 unmodified lines3132333435363746 unmodified lines8485868788899039 unmodified lines1301311321331341351363 unmodified lines.d3-bar .controls label { font-size: 12px; color: var(--muted-color); display: flex; align-items: center; gap: 8px; white-space: nowrap; padding: 6px 10px; }.d3-bar .controls select { font-size: 12px; padding: 8px 28px 8px 10px; border: 1px solid var(--border-color); border-radius: 8px; background-color: var(--surface-bg); color: var(--text-color); background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%230f1115' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 8px center; background-size: 12px; -webkit-appearance: none; -moz-appearance: none; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease; }[data-theme="dark"] .d3-bar .controls select { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); }.d3-bar .controls select:hover { border-color: var(--primary); }.d3-bar .controls select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; }.d3-bar .legend { font-size: 12px; line-height: 1.35; color: var(--text-color); }</style><script>19 unmodified linesconst components = [{ key: 'parameters', color: 'rgb(78, 165, 183)' },{ key: 'gradients', color: 'rgb(227, 138, 66)' },{ key: 'optimizer', color: 'var(--primary)' },{ key: 'activations', color: 'rgb(206, 192, 250)' },];const modelSizes = ["1B","3B","8B","70B","405B"];46 unmodified lines// Statelet currentSize = modelSizes[0];let currentMode = 'none';// Layout & scaleslet width=800, height=360; const margin = { top: 16, right: 28, bottom: 56, left: 64 };39 unmodified lines// AxesgAxes.selectAll('*').remove();gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(x0)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); });gAxes.append('g').call(d3.axisLeft(y).ticks(6).tickFormat(d3.format('.2f'))).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); });// Axis labelsgAxes.append('text').attr('class','axis-label axis-label--x').attr('x', innerWidth/2).attr('y', innerHeight + 44).attr('text-anchor','middle').style('font-size','12px').style('fill', tickColor).text('Sequence Length');3 unmodified lines456789101119 unmodified lines3132333435363746 unmodified lines848586878889909139 unmodified lines1311321331341351361373 unmodified lines.d3-bar .controls label { font-size: 12px; color: var(--muted-color); display: flex; align-items: center; gap: 8px; white-space: nowrap; padding: 6px 10px; }.d3-bar .controls select { font-size: 12px; padding: 8px 28px 8px 10px; border: 1px solid var(--border-color); border-radius: 8px; background-color: var(--surface-bg); color: var(--text-color); background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%230f1115' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 8px center; background-size: 12px; -webkit-appearance: none; -moz-appearance: none; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease; }[data-theme="dark"] .d3-bar .controls select { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); }.d3-bar .controls select:hover { border-color: var(--primary-color); }.d3-bar .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; }.d3-bar .legend { font-size: 12px; line-height: 1.35; color: var(--text-color); }</style><script>19 unmodified linesconst components = [{ key: 'parameters', color: 'rgb(78, 165, 183)' },{ key: 'gradients', color: 'rgb(227, 138, 66)' },{ key: 'optimizer', color: 'var(--primary-color)' },{ key: 'activations', color: 'rgb(206, 192, 250)' },];const modelSizes = ["1B","3B","8B","70B","405B"];46 unmodified lines// Statelet currentSize = modelSizes[0];let currentMode = 'selective';selRecomp.value = currentMode;// Layout & scaleslet width=800, height=360; const margin = { top: 16, right: 28, bottom: 56, left: 64 };39 unmodified lines// AxesgAxes.selectAll('*').remove();gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(x0)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); });gAxes.append('g').call(d3.axisLeft(y).ticks(6).tickFormat(d3.format('~f'))).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); });// Axis labelsgAxes.append('text').attr('class','axis-label axis-label--x').attr('x', innerWidth/2).attr('y', innerHeight + 44).attr('text-anchor','middle').style('font-size','12px').style('fill', tickColor).text('Sequence Length');
20 unmodified lines2122232425262728293031323334353614 unmodified lines515253545556577 unmodified lines656667686970717273747576104 unmodified lines18118218318418518618733 unmodified lines22122222322422522622722822923023123223320 unmodified linesbackground-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");}.d3-line .d3-line__controls select:hover {border-color: var(--primary);}.d3-line .d3-line__controls select:focus {border-color: var(--primary);box-shadow: 0 0 0 3px rgba(232,137,171,.25);outline: none;}.d3-line .d3-line__controls label { gap: 8px; }/* Range slider themed with --primary */.d3-line .d3-line__controls input[type="range"] {-webkit-appearance: none;appearance: none;14 unmodified lineswidth: 16px;height: 16px;border-radius: 50%;background: var(--primary);border: 2px solid var(--on-primary);margin-top: -5px;cursor: pointer;7 unmodified lineswidth: 16px;height: 16px;border-radius: 50%;background: var(--primary);border: 2px solid var(--on-primary);cursor: pointer;}/* Improved line color via CSS */.d3-line .lines path.improved { stroke: var(--primary); }</style><script>(() => {104 unmodified lines// Colorsconst colorBase = '#64748b'; // slate-500const colorImproved = 'var(--primary)';const colorTarget = '#4b5563'; // gray-600const legendBgLight = 'rgba(255,255,255,0.85)';const legendBgDark = 'rgba(17,17,23,0.85)';33 unmodified lines.y((d) => yScale(d));const pathBase = gLines.append('path').attr('fill', 'none').attr('stroke', colorBase).attr('stroke-width', 2);const pathImp = gLines.append('path').attr('class', 'improved').attr('fill', 'none').style('stroke', 'var(--primary)').attr('stroke-width', 2);const pathTgt = gLines.append('path').attr('fill', 'none').attr('stroke', colorTarget).attr('stroke-width', 2).attr('stroke-dasharray', '6,6');// Hover elementsconst hoverLine = gHover.append('line').attr('stroke-width', 1);const hoverDotB = gHover.append('circle').attr('r', 3.5).attr('fill', colorBase).attr('stroke', '#fff').attr('stroke-width', 1);const hoverDotI = gHover.append('circle').attr('class', 'improved').attr('r', 3.5).style('fill', 'var(--primary)').attr('stroke', '#fff').attr('stroke-width', 1);const hoverDotT = gHover.append('circle').attr('r', 3.5).attr('fill', colorTarget).attr('stroke', '#fff').attr('stroke-width', 1);const overlay = gHover.append('rect').attr('fill', 'transparent').style('cursor', 'crosshair');20 unmodified lines2122232425262728293031323334353614 unmodified lines515253545556577 unmodified lines656667686970717273747576104 unmodified lines18118218318418518618733 unmodified lines22122222322422522622722822923023123223320 unmodified linesbackground-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");}.d3-line .d3-line__controls select:hover {border-color: var(--primary-color);}.d3-line .d3-line__controls select:focus {border-color: var(--primary-color);box-shadow: 0 0 0 3px rgba(232,137,171,.25);outline: none;}.d3-line .d3-line__controls label { gap: 8px; }/* Range slider themed with --primary-color */.d3-line .d3-line__controls input[type="range"] {-webkit-appearance: none;appearance: none;14 unmodified lineswidth: 16px;height: 16px;border-radius: 50%;background: var(--primary-color);border: 2px solid var(--on-primary);margin-top: -5px;cursor: pointer;7 unmodified lineswidth: 16px;height: 16px;border-radius: 50%;background: var(--primary-color);border: 2px solid var(--on-primary);cursor: pointer;}/* Improved line color via CSS */.d3-line .lines path.improved { stroke: var(--primary-color); }</style><script>(() => {104 unmodified lines// Colorsconst colorBase = '#64748b'; // slate-500const colorImproved = 'var(--primary-color)';const colorTarget = '#4b5563'; // gray-600const legendBgLight = 'rgba(255,255,255,0.85)';const legendBgDark = 'rgba(17,17,23,0.85)';33 unmodified lines.y((d) => yScale(d));const pathBase = gLines.append('path').attr('fill', 'none').attr('stroke', colorBase).attr('stroke-width', 2);const pathImp = gLines.append('path').attr('class', 'improved').attr('fill', 'none').style('stroke', 'var(--primary-color)').attr('stroke-width', 2);const pathTgt = gLines.append('path').attr('fill', 'none').attr('stroke', colorTarget).attr('stroke-width', 2).attr('stroke-dasharray', '6,6');// Hover elementsconst hoverLine = gHover.append('line').attr('stroke-width', 1);const hoverDotB = gHover.append('circle').attr('r', 3.5).attr('fill', colorBase).attr('stroke', '#fff').attr('stroke-width', 1);const hoverDotI = gHover.append('circle').attr('class', 'improved').attr('r', 3.5).style('fill', 'var(--primary-color)').attr('stroke', '#fff').attr('stroke-width', 1);const hoverDotT = gHover.append('circle').attr('r', 3.5).attr('fill', colorTarget).attr('stroke', '#fff').attr('stroke-width', 1);const overlay = gHover.append('rect').attr('fill', 'transparent').style('cursor', 'crosshair');
25 unmodified lines2627282930313225 unmodified lines{ key: 'model', label: 'Model', color: '#a78bfa' },{ key: 'forward', label: 'Forward', color: '#14b8a6' },{ key: 'backward', label: 'Backward', color: '#f59e0b' },{ key: 'gradients', label: 'Gradients', color: 'var(--primary)' },{ key: 'optimization', label: 'Optimization', color: '#10b981' },{ key: 'updated', label: 'Updated', color: '#7c3aed' },];25 unmodified lines2627282930313225 unmodified lines{ key: 'model', label: 'Model', color: '#a78bfa' },{ key: 'forward', label: 'Forward', color: '#14b8a6' },{ key: 'backward', label: 'Backward', color: '#f59e0b' },{ key: 'gradients', label: 'Gradients', color: 'var(--primary-color)' },{ key: 'optimization', label: 'Optimization', color: '#10b981' },{ key: 'updated', label: 'Updated', color: '#7c3aed' },];
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337<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)!important; 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 337°</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:93.6%; width:14px; height:14px; border-radius:50%; border:2px solid #fff; 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);});};// ntc.js removed; rely on embedded color-name listensureD3(() => ensureChroma(cb));};// Embedded reduced color-name list (~50 items), minifiedconst COLOR_NAMES=[{"name":"Candy Apple Red","hex":"#ff0800"},{"name":"Boiling Magma","hex":"#ff3300"},{"name":"Aerospace Orange","hex":"#ff4f00"},{"name":"Burtuqali Orange","hex":"#ff6700"},{"name":"American Orange","hex":"#ff8b00"},{"name":"Cheese","hex":"#ffa600"},{"name":"Amber","hex":"#ffbf00"},{"name":"Demonic Yellow","hex":"#ffe700"},{"name":"Bat-Signal","hex":"#feff00"},{"name":"Bitter Lime","hex":"#cfff00"},{"name":"Electric Lime","hex":"#ccff00"},{"name":"Bright Yellow Green","hex":"#9dff00"},{"name":"Lasting Lime","hex":"#88ff00"},{"name":"Bright Green","hex":"#66ff00"},{"name":"Chlorophyll Green","hex":"#4aff00"},{"name":"Green Screen","hex":"#22ff00"},{"name":"Electric Pickle","hex":"#00ff04"},{"name":"Acid","hex":"#00ff22"},{"name":"Lucent Lime","hex":"#00ff33"},{"name":"Cathode Green","hex":"#00ff55"},{"name":"Booger Buster","hex":"#00ff77"},{"name":"Green Gas","hex":"#00ff99"},{"name":"Enthusiasm","hex":"#00ffaa"},{"name":"Ice Ice Baby","hex":"#00ffdd"},{"name":"Master Sword Blue","hex":"#00ffee"},{"name":"Agressive Aqua","hex":"#00fbff"},{"name":"Vivid Sky Blue","hex":"#00ccff"},{"name":"Capri","hex":"#00bfff"},{"name":"Sky of Magritte","hex":"#0099ff"},{"name":"Azure","hex":"#007fff"},{"name":"Blue Ribbon","hex":"#0066ff"},{"name":"Blinking Blue","hex":"#0033ff"},{"name":"Icelandic Water","hex":"#0011ff"},{"name":"Blue","hex":"#0000ff"},{"name":"Blue Pencil","hex":"#2200ff"},{"name":"Electric Ultramarine","hex":"#3f00ff"},{"name":"Aladdin's Feather","hex":"#5500ff"},{"name":"Purple Climax","hex":"#8800ff"},{"name":"Amethyst Ganzstar","hex":"#8f00ff"},{"name":"Electric Purple","hex":"#bf00ff"},{"name":"Phlox","hex":"#df00ff"},{"name":"Brusque Pink","hex":"#ee00ff"},{"name":"Bright Magenta","hex":"#ff08e8"},{"name":"Brutal Pink","hex":"#ff00bb"},{"name":"Mean Girls Lipstick","hex":"#ff00ae"},{"name":"Big Bang Pink","hex":"#ff0099"},{"name":"Flaming Hot Flamingoes","hex":"#ff005d"},{"name":"Blazing Dragonfruit","hex":"#ff0054"},{"name":"Carmine Red","hex":"#ff0038"},{"name":"Bright Red","hex":"#ff000d"}];window.__colorNames = COLOR_NAMES;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 });// Shared bus to sync with color-picker instancesif (!window.__colorPickerBus) {window.__colorPickerBus = (() => {let hue = 337; let adjusting = false; const listeners = new Set();return {get: () => ({ hue, adjusting }),publish: (sourceId, nextHue, isAdjusting) => { hue = ((nextHue % 360) + 360) % 360; adjusting = !!isAdjusting; listeners.forEach(fn => { try { fn({ sourceId, hue, adjusting }); } catch {} }); },subscribe: (fn) => { listeners.add(fn); return () => listeners.delete(fn); }};})();}const bus = window.__colorPickerBus;const instanceId = Math.random().toString(36).slice(2);// Cards data with full descriptionsconst 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) => {// Generate in LCH for perceptually distinct colorsconst baseH = chroma(base).get('hsl.h');const L = 70; // comfortable lightnessconst C = 80; // moderate chroma to stay within gamutreturn 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';// Build two symmetric ramps that meet (without duplicating the neutral)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 scaffoldingconst 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');// Renderingconst renderPalettes = (h) => {console.log('[palettes] renderPalettes', h);const base = chroma.hsl(h, 0.67, 0.72);// Update CSS variables for live theming only during interactiontry {if (isAdjusting) {const baseHex = base.hex();const hoverHex = chroma(base).darken(0.6).hex();const rootEl = document.documentElement;rootEl.style.setProperty('--primary', baseHex);rootEl.style.setProperty('--primary-hover', hoverHex);}} catch (e) {console.warn('[palettes] failed updating CSS vars', e);}const uniformText = (bg) => (chroma(bg).luminance() > 0.45 ? '#111' : '#fff');// Update current swatch + nameif (currentSwatch) currentSwatch.style.background = base.hex();const getName = (hex) => {// Prefer embedded reduced listconst list = (window.__colorNames && window.__colorNames.length) ? window.__colorNames : COLOR_NAMES;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;}// Hue-based coarse fallbackconst 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 paletteconst header = d3.select(this).select('.palette-card__header');const grad = `linear-gradient(90deg, ${data.join(',')})`;header.style('background', grad);// Update circular badgeconst badge = d3.select(this).select('.palette-card__badge');if (d.key === 'categorical') {// Donut full hue circle for categoricalconst 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 markersbadge.selectAll('.badge-marker').remove();// Place markers at palette huesconst radius = 21; // outer circle radiusconst center = 22; // half of badge size (44)data.forEach((hex) => {const h = chroma(hex).get('hsl.h') || 0;const angle = (h * Math.PI) / 180; // radiansconst r = radius - 3; // adjust for 6px marker sizeconst 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 donutif (!badge.select('.badge-hole').node()) badge.append('div').attr('class', 'badge-hole');} else {// Linear gradient left->right for sequential/divergingconst linear = `linear-gradient(90deg, ${data.join(',')})`;badge.style('background', linear);badge.selectAll('.badge-marker').remove();badge.selectAll('.badge-hole').remove();}});};// Hue slider behaviorlet hue = 337; // initiallet isAdjusting = false; // only update theme while interactingconst 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(); isAdjusting = true; const h0 = getHueFromEvent(ev); setHue(h0); bus.publish(instanceId, h0, true); const move = (e) => { e.preventDefault && e.preventDefault(); const hh = getHueFromEvent(e); setHue(hh); bus.publish(instanceId, hh, true); }; const up = () => { console.log('[palettes] onUp'); isAdjusting = false; bus.publish(instanceId, hue, false); 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'); }// Subscribe to bus to receive updates from other pickersconst unsubscribe = bus.subscribe(({ sourceId, hue: H, adjusting }) => { if (sourceId === instanceId) return; isAdjusting = adjusting; setHue(H); });// 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));console.log('[palettes] initial render');// Initialize from shared hue without updating CSS variablesconst shared = bus.get();isAdjusting = false;setHue(shared && typeof shared.hue === 'number' ? shared.hue : hue);applySimulation('none');// Fixed 3 columns layoutgrid.style.gridTemplateColumns = '1fr 1fr 1fr';};if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => ensureLibs(bootstrap), { once: true });else ensureLibs(bootstrap);})();</script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116<div class="palettes" style="width:100%; margin: 10px 0;"><style>.palettes .palettes__grid { display: grid; grid-template-columns: 1fr; gap: 12px; }.palettes .palette-card { position: relative; display: grid; grid-template-columns: 260px 1fr auto; align-items: center; gap: 14px; border: 1px solid var(--border-color); border-radius: 10px; background: var(--surface-bg); padding: 12px; transition: box-shadow .18s ease, transform .18s ease, border-color .18s ease; }/* removed circular badge */.palettes .palette-card__swatches { display: flex; gap: 0; margin: 0; height: 40px; overflow: hidden; border-radius: 8px; }.palettes .palette-card__swatches .sw { flex: 1 1 0; height: 100%; min-width: 0; border: none; }.palettes .palette-card__content { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; justify-content: center; min-width: 0; padding-left: 12px; border-left: 1px solid var(--border-color); }.palettes .palette-card__actions { display: flex; align-items: center; justify-content: flex-end; justify-self: end; }.palettes .copy-btn { margin: 0; padding: 6px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--surface-bg); color: var(--text-color)!important; font-size: 12px; cursor: pointer; transition: background .18s ease, color .18s ease, border-color .18s ease; }.palettes .copy-btn:hover { background: var(--primary-color); color: var(--on-primary)!important; border-color: transparent; }.palettes .copy-btn:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 2px; }@media (max-width: 640px) {.palettes .palette-card { grid-template-columns: 1fr; align-items: stretch; gap: 10px; }.palettes .palette-card__swatches { height: 36px; border-radius: 8px; }.palettes .palette-card__content { border-left: none; padding-left: 0; }.palettes .palette-card__actions { justify-self: start; }}</style><div class="palettes__grid"></div></div><script>(() => {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 ensureChroma = (next) => {if (window.chroma) return next();const tryReady = () => { if (window.chroma) next(); else setTimeout(tryReady, 25); };const existing = document.getElementById('chroma-cdn') || document.getElementById('chroma-cdn-fallback');if (existing) { tryReady(); return; }loadScript('chroma-cdn', 'https://unpkg.com/chroma-js@2.4.2/dist/chroma.min.js', tryReady, () => {loadScript('chroma-cdn-fallback', 'https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.4.2/chroma.min.js', tryReady);});};const cards = [{ key: 'categorical', title: 'Categorical', desc: 'For <strong>non‑numeric categories</strong>; <strong>visually distinct</strong> colors. <strong>Up to 6</strong>.', generator: (baseHex) => {const base = chroma(baseHex);const lc = base.lch();const baseH = base.get('hsl.h') || 0;const L = Math.max(40, Math.min(85, lc[0] || 70));const C = Math.max(40, Math.min(90, lc[1] || 80));const offsets = [180, 120, -120, 60, -60];const rest = offsets.map(off => chroma.lch(L, C, (baseH + off + 360) % 360).hex());return [base.hex(), ...rest];}},{ key: 'sequential', title: 'Sequential', desc: 'For <strong>numeric scales</strong>; gradient from <strong>light to dark</strong>; ideal for <strong>heatmaps</strong>.', generator: (baseHex) => {const c = chroma(baseHex).saturate(0.3);return chroma.scale([c.brighten(2), c, c.darken(2)]).mode('lab').correctLightness(true).colors(6);}},{ key: 'diverging', title: 'Diverging', desc: 'For <strong>centered ranges</strong> with <strong>two extremes</strong> (e.g., negatives/positives) around a <strong>baseline</strong>.', generator: (baseHex) => {const baseH = chroma(baseHex).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';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]];}}];const getCssPrimary = () => {try { return getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim(); } catch { return ''; }};const render = () => {const mount = document.currentScript ? document.currentScript.previousElementSibling : null;const root = mount && mount.closest('.palettes') ? mount.closest('.palettes') : document.querySelector('.palettes');if (!root) return;const grid = root.querySelector('.palettes__grid');if (!grid) return;grid.innerHTML = '';const css = getCssPrimary();const baseHex = css && /^#|rgb|hsl/i.test(css) ? chroma(css).hex() : '#E889AB';cards.forEach((c) => {const card = document.createElement('div'); card.className = 'palette-card';const sw = document.createElement('div'); sw.className = 'palette-card__swatches';const colors = c.generator(baseHex).slice(0, 6);colors.forEach(col => { const d = document.createElement('div'); d.className = 'sw'; d.style.background = col; sw.appendChild(d); });const content = document.createElement('div'); content.className = 'palette-card__content';const title = document.createElement('div'); title.className = 'palette-card__title'; title.style.textAlign = 'left'; title.style.fontWeight = '800'; title.style.fontSize = '15px'; title.textContent = c.title;const desc = document.createElement('div'); desc.className = 'palette-card__desc'; desc.style.textAlign = 'left'; desc.style.color = 'var(--muted-color)'; desc.style.lineHeight = '1.5'; desc.style.fontSize = '12px'; desc.innerHTML = c.desc;const actions = document.createElement('div'); actions.className = 'palette-card__actions';const btn = document.createElement('button'); btn.className = 'copy-btn'; btn.textContent = 'Copy';btn.addEventListener('click', async () => {const json = JSON.stringify(colors, null, 2);try { await navigator.clipboard.writeText(json); const old = btn.textContent; btn.textContent = 'Copied!'; setTimeout(() => btn.textContent = old, 900); } catch { window.prompt('Copy palette', json); }});content.appendChild(title); content.appendChild(desc);actions.appendChild(btn);card.appendChild(sw); card.appendChild(content); card.appendChild(actions);grid.appendChild(card);});};const bootstrap = () => {render();const mo = new MutationObserver(() => render());mo.observe(document.documentElement, { attributes: true, attributeFilter: ['style'] });};if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => ensureChroma(bootstrap), { once: true });else ensureChroma(bootstrap);})();</script>
81 unmodified lines8283848586878889909192100 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521613 unmodified lines23023123223323423523623723823924081 unmodified lines<section class="content-grid"><aside class="toc"><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 />100 unmodified lines<script>// 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');if (!headings.length) return;const nav = document.createElement('nav');let ulStack = [document.createElement('ul')];nav.appendChild(ulStack[0]);const levelOf = (tag) => tag === 'H2' ? 2 : tag === 'H3' ? 3 : 4;let prev = 2;headings.forEach((h) => {const lvl = levelOf(h.tagName);// ensure id existsif (!h.id) h.id = h.textContent.toLowerCase().replace(/\s+/g, '_');// adjust depthwhile (lvl > prev) { const ul = document.createElement('ul'); ulStack[ulStack.length-1].lastElementChild?.appendChild(ul); ulStack.push(ul); prev++; }while (lvl < prev) { ulStack.pop(); prev--; }13 unmodified lines...(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;81 unmodified lines8283848586878889909192100 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525613 unmodified lines27027127227327427527627727827928081 unmodified lines<section class="content-grid"><aside class="toc"><div class="title">Table of Contents</div><div id="article-toc-placeholder"></div></aside><details class="toc-mobile"><summary>Table of Contents</summary><div id="article-toc-mobile-placeholder"></div></details><main><Article />100 unmodified lines<script>// Build TOC from article headings (h2/h3/h4) and render into the sticky asideconst buildTOC = () => {const holder = document.getElementById('article-toc-placeholder');const holderMobile = document.getElementById('article-toc-mobile-placeholder');// Always rebuild TOC to avoid stale entriesif (holder) holder.innerHTML = '';if (holderMobile) holderMobile.innerHTML = '';const articleRoot = document.querySelector('section.content-grid main');if (!articleRoot) return;const headings = articleRoot.querySelectorAll('h2, h3, h4');if (!headings.length) return;// Filter out headings that should not appear in TOCconst normalize = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();const isTocLabel = (s) => /^(table\s+of\s+contents?)$|^toc$/i.test(String(s || '').replace(/[^a-zA-Z0-9]+/g, ' ').trim());const shouldSkip = (h) => {const t = h.textContent || '';const id = String(h.id || '');const slug = normalize(t).replace(/\s+/g, '_');if (isTocLabel(t)) return true;if (isTocLabel(id.replace(/[_-]+/g, ' '))) return true;if (isTocLabel(slug.replace(/[_-]+/g, ' '))) return true;return false;};const headingsArr = Array.from(headings).filter(h => !shouldSkip(h));if (!headingsArr.length) return;// Ensure unique ids for headings (deduplicate duplicates)const usedIds = new Set<string>();const slugify = (s: string) => String(s || '').toLowerCase().trim().replace(/\s+/g, '_').replace(/[^a-z0-9_\-]/g, '');headingsArr.forEach((h) => {let id = (h.id || '').trim();if (!id) {const base = slugify(h.textContent || '');id = base || 'section';}let candidate = id;let n = 2;while (usedIds.has(candidate)) {candidate = `${id}-${n++}`;}if (h.id !== candidate) h.id = candidate;usedIds.add(candidate);});const nav = document.createElement('nav');let ulStack = [document.createElement('ul')];nav.appendChild(ulStack[0]);const levelOf = (tag) => tag === 'H2' ? 2 : tag === 'H3' ? 3 : 4;let prev = 2;headingsArr.forEach((h) => {const lvl = levelOf(h.tagName);// adjust depthwhile (lvl > prev) { const ul = document.createElement('ul'); ulStack[ulStack.length-1].lastElementChild?.appendChild(ul); ulStack.push(ul); prev++; }while (lvl < prev) { ulStack.pop(); prev--; }13 unmodified lines...(holderMobile ? holderMobile.querySelectorAll('a') : [])];const onScroll = () => {for (let i = headingsArr.length - 1; i >= 0; i--) {const top = headingsArr[i].getBoundingClientRect().top;if (top - 60 <= 0) {links.forEach(l => l.classList.remove('active'));const id = '#' + headingsArr[i].id;const actives = Array.from(links).filter(l => l.getAttribute('href') === id);actives.forEach(a => a.classList.add('active'));break;
41 unmodified lines4243444546474849128 unmodified lines17817918018118218318454 unmodified lines23924024124224324441 unmodified linesmargin: var(--spacing-8) 0 var(--spacing-4);}.content-grid main a { color: var(--primary); text-decoration: none; border-bottom: 1px solid var(--link-underline); }.content-grid main a:hover { color: var(--primary-hover); border-bottom: 1px solid var(--link-underline-hover); }/* Do not underline heading links inside the article (not the TOC) */.content-grid main h2 a,128 unmodified lines/* ============================================================================ */button, .button {appearance: none;background: linear-gradient(15deg, var(--primary) 0%, var(--primary-hover) 35%);color: white!important;border: 1px solid transparent;border-radius: 6px;54 unmodified lines--link-underline: rgba(0,0,0,.3);--link-underline-hover: rgba(0,0,0,.4);}}.muted {41 unmodified lines4243444546474849128 unmodified lines17817918018118218318454 unmodified lines23924024124224324424524624724824925025125225325425525625725825926026126226326426526626726841 unmodified linesmargin: var(--spacing-8) 0 var(--spacing-4);}.content-grid main a { color: var(--primary-color); text-decoration: none; border-bottom: 1px solid var(--link-underline); }.content-grid main a:hover { color: var(--primary-color-hover); border-bottom: 1px solid var(--link-underline-hover); }/* Do not underline heading links inside the article (not the TOC) */.content-grid main h2 a,128 unmodified lines/* ============================================================================ */button, .button {appearance: none;background: linear-gradient(15deg, var(--primary-color) 0%, var(--primary-color-hover) 35%);color: white!important;border: 1px solid transparent;border-radius: 6px;54 unmodified lines--link-underline: rgba(0,0,0,.3);--link-underline-hover: rgba(0,0,0,.4);}/* Force single column to reduce widows/orphans and awkward breaks */.content-grid { grid-template-columns: 1fr !important; }.toc, .right-aside, .toc-mobile { display: none !important; }main > nav:first-of-type { display: none !important; }/* Avoid page breaks inside complex visual blocks */.hero,.hero-banner,.d3-galaxy,.d3-galaxy svg,.plot-card,.js-plotly-plot,figure,pre,table,blockquote,.wide,.full-bleed {break-inside: avoid;page-break-inside: avoid;}/* Prefer keeping header+lead together */.hero { page-break-after: avoid; }}.muted {
8 unmodified lines9101112131415163 unmodified lines202122232425262714 unmodified lines42434445464748498 unmodified lines--neutral-200: rgb(245, 245, 245);/* Primary brand color */--primary: rgb(232, 137, 171);--primary-hover: rgb(212, 126, 156);--on-primary: #ffffff;--text-color: rgba(0,0,0,.85);3 unmodified lines/* Light surfaces & links */--surface-bg: #fafafa;--code-bg: #f6f8fa;--link-underline: var(--primary); /* based on --primary */--link-underline-hover: var(--primary-hover);--spacing-1: 8px;--spacing-2: 12px;14 unmodified lines--surface-bg: #12151b;--code-bg: #12151b;/* Primary in dark mode */--primary: rgb(232, 137, 171);--primary-hover: rgb(212, 126, 156);--on-primary: #0f1115;color-scheme: dark;8 unmodified lines9101112131415163 unmodified lines202122232425262714 unmodified lines42434445464748498 unmodified lines--neutral-200: rgb(245, 245, 245);/* Primary brand color */--primary-color: rgb(232, 137, 171);--primary-color-hover: rgb(212, 126, 156);--on-primary: #ffffff;--text-color: rgba(0,0,0,.85);3 unmodified lines/* Light surfaces & links */--surface-bg: #fafafa;--code-bg: #f6f8fa;--link-underline: var(--primary-color); /* based on --primary-color */--link-underline-hover: var(--primary-color-hover);--spacing-1: 8px;--spacing-2: 12px;14 unmodified lines--surface-bg: #12151b;--code-bg: #12151b;/* Primary in dark mode */--primary-color: rgb(232, 137, 171);--primary-color-hover: rgb(212, 126, 156);--on-primary: #0f1115;color-scheme: dark;
12 unmodified lines131415161718192012 unmodified lines.plotly_input_container > select { padding: 2px 4px; line-height: 1.5em; text-align: center; border-radius: 4px; font-size: 12px; background-color: var(--neutral-200); outline: none; border: 1px solid var(--neutral-300); }.plotly_slider { display: flex; align-items: center; gap: 10px; }.plotly_slider > input[type="range"] { -webkit-appearance: none; appearance: none; height: 2px; background: var(--neutral-400); border-radius: 5px; outline: none; }.plotly_slider > input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; width: 18px; height: 18px; border-radius: 50%; background: var(--primary); cursor: pointer; }.plotly_slider > input[type="range"]::-moz-range-thumb { width: 18px; height: 18px; border-radius: 50%; background: var(--primary); cursor: pointer; }.plotly_slider > span { font-size: 14px; line-height: 1.6em; min-width: 16px; }/* ---------------------------------------------------------------------------- */12 unmodified lines131415161718192012 unmodified lines.plotly_input_container > select { padding: 2px 4px; line-height: 1.5em; text-align: center; border-radius: 4px; font-size: 12px; background-color: var(--neutral-200); outline: none; border: 1px solid var(--neutral-300); }.plotly_slider { display: flex; align-items: center; gap: 10px; }.plotly_slider > input[type="range"] { -webkit-appearance: none; appearance: none; height: 2px; background: var(--neutral-400); border-radius: 5px; outline: none; }.plotly_slider > input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; width: 18px; height: 18px; border-radius: 50%; background: var(--primary-color); cursor: pointer; }.plotly_slider > input[type="range"]::-moz-range-thumb { width: 18px; height: 18px; border-radius: 50%; background: var(--primary-color); cursor: pointer; }.plotly_slider > span { font-size: 14px; line-height: 1.6em; min-width: 16px; }/* ---------------------------------------------------------------------------- */
README.md-1
app/.astro/astro/content.d.ts-185
app/astro.config.mjs-2
app/src/assets/images/moon.svg → app/src/assets/icones/moon.svgRenamed
app/src/assets/images/sun.svg → app/src/assets/icones/sun.svgRenamed
app/src/components/Note.astro+7-6
app/src/components/ThemeToggle.astro+2-2
app/src/content/article.mdx+11-46
app/src/content/chapters/writing-you-content.mdx → app/src/content/chapters/available-blocks.mdxRenamed+6-83
app/src/content/chapters/best-pratices.mdx+24-4
app/src/content/chapters/getting-started.mdxAdded+42
app/src/content/chapters/writing-your-content.mdxAdded+116
app/src/content/fragments/banner.html+2-2
app/src/content/fragments/color-picker.html+35-22
app/src/content/fragments/d3-bar.html+6-5
app/src/content/fragments/d3-line.html+9-9
app/src/content/fragments/heatmap.html+1-1
app/src/content/fragments/palettes.html+84-305
app/src/pages/index.astro+51-11
app/src/styles/_base.css+27-3
app/src/styles/_variables.css+6-6
app/src/styles/components/_poltly.css+2-2