@samizdata/mozaic 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # mozaic
2
2
 
3
- Chart components for the web and print, built on Svelte 5 and d3.
3
+ Chart components for the web and print, built on Svelte 5 and d3, and the `mozaic` command for exporting and ejecting.
4
4
 
5
5
  ```bash
6
- pnpm add mozaic d3-scale d3-array d3-shape
6
+ pnpm add @samizdata/mozaic d3-scale d3-array d3-shape
7
7
  ```
8
8
 
9
9
  ```svelte
@@ -42,4 +42,23 @@ pnpm add mozaic d3-scale d3-array d3-shape
42
42
  | `@samizdata/mozaic/export` | `figureToSvg`, `downloadSvg`, `downloadPng`, `figureToPng` |
43
43
  | `@samizdata/mozaic/recipes` | `BarChart`, `ColumnChart`, `LineChart`, `ScatterChart`, `ArrowChart`, `BarDotChart`, `StackedBarChart`, `MosaicChart`, `PercentileChart` |
44
44
 
45
+ ## CLI
46
+
47
+ The package installs a `mozaic` command (Node 22.17+):
48
+
49
+ ```bash
50
+ mozaic export [dir] # export every embed in a built site (default: build) to SVG, PDF and PNG
51
+ mozaic eject <recipe> # copy a recipe's source into your project (default: src/lib/recipes) to edit it
52
+ mozaic --help
53
+ ```
54
+
55
+ `export` reads `embed/manifest.json` from the built site, serves the folder locally and renders each embed in headless Chromium:
56
+
57
+ - `web.png` (2×) and `web.svg` at `--web-width` (default 640 px)
58
+ - `print-<width>.svg` and `print-<width>.pdf` for each print width in the manifest
59
+
60
+ Options: `--out <dir>` (default `exports`), `--only <slug,…>`, `--formats svg,pdf,png`, `--web-width <px>`, `--browser <path>`.
61
+
62
+ Chromium lookup: `--browser`, `$MOZAIC_BROWSER`, Playwright's download (`npx playwright install chromium`), any Chromium in Playwright's cache, then common system locations. Each is tried until one starts.
63
+
45
64
  Requires Svelte 5.57+. The full guides, API reference and gallery are in the repository's docs site.
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/main.js';
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => process.exit(code),
6
+ (error) => {
7
+ console.error(`mozaic: ${error instanceof Error ? error.message : error}`);
8
+ process.exit(1);
9
+ }
10
+ );
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Minimal argument parser: positionals, `--flag`, `--key value`, `--key=value`,
3
+ * and `--no-flag`.
4
+ * @param {string[]} argv
5
+ * @returns {{ positionals: string[], options: Record<string, string | boolean> }}
6
+ */
7
+ export function parseArgs(argv) {
8
+ /** @type {string[]} */
9
+ const positionals = [];
10
+ /** @type {Record<string, string | boolean>} */
11
+ const options = {};
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const arg = argv[i];
14
+ if (arg === '--') {
15
+ positionals.push(...argv.slice(i + 1));
16
+ break;
17
+ }
18
+ if (arg.startsWith('--')) {
19
+ const body = arg.slice(2);
20
+ const eq = body.indexOf('=');
21
+ if (eq >= 0) options[body.slice(0, eq)] = body.slice(eq + 1);
22
+ else if (body.startsWith('no-')) options[body.slice(3)] = false;
23
+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('-')) options[body] = argv[++i];
24
+ else options[body] = true;
25
+ } else if (arg.startsWith('-') && arg.length > 1) {
26
+ options[arg.slice(1)] = true;
27
+ } else {
28
+ positionals.push(arg);
29
+ }
30
+ }
31
+ return { positionals, options };
32
+ }
@@ -0,0 +1,93 @@
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import { homedir, platform } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { chromium } from 'playwright-core';
5
+
6
+ const SYSTEM_BROWSERS = [
7
+ '/usr/bin/chromium',
8
+ '/usr/bin/chromium-browser',
9
+ '/usr/bin/google-chrome',
10
+ '/usr/bin/google-chrome-stable',
11
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
12
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
13
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'
14
+ ];
15
+
16
+ /** Chromium builds already downloaded by any Playwright version, newest first. */
17
+ function playwrightCacheBrowsers() {
18
+ const os = platform();
19
+ const cache =
20
+ process.env.PLAYWRIGHT_BROWSERS_PATH ??
21
+ (os === 'darwin'
22
+ ? join(homedir(), 'Library', 'Caches', 'ms-playwright')
23
+ : os === 'win32'
24
+ ? join(process.env.LOCALAPPDATA ?? '', 'ms-playwright')
25
+ : join(homedir(), '.cache', 'ms-playwright'));
26
+ const executable =
27
+ os === 'darwin'
28
+ ? ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium']
29
+ : os === 'win32'
30
+ ? ['chrome-win', 'chrome.exe']
31
+ : ['chrome-linux64', 'chrome'];
32
+ try {
33
+ return readdirSync(cache)
34
+ .filter((name) => /^chromium-\d+$/.test(name))
35
+ .sort((a, b) => Number(b.split('-')[1]) - Number(a.split('-')[1]))
36
+ .map((name) => join(cache, name, ...executable));
37
+ } catch {
38
+ return [];
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Chromium executables to try, in order: `--browser`, $MOZAIC_BROWSER,
44
+ * Playwright's expected download, any other cached Playwright Chromium, then
45
+ * common system locations.
46
+ * @param {string | undefined} explicit
47
+ * @returns {string[]}
48
+ */
49
+ export function browserCandidates(explicit) {
50
+ /** @type {(string | undefined)[]} */
51
+ const candidates = [explicit, process.env.MOZAIC_BROWSER];
52
+ try {
53
+ candidates.push(chromium.executablePath());
54
+ } catch {
55
+ // Playwright's own browser is not installed.
56
+ }
57
+ candidates.push(...playwrightCacheBrowsers(), ...SYSTEM_BROWSERS);
58
+ return [...new Set(candidates.filter((path) => path !== undefined && existsSync(path)))].map(String);
59
+ }
60
+
61
+ /**
62
+ * @param {string | undefined} explicit
63
+ * @returns {string | undefined}
64
+ */
65
+ export function findBrowser(explicit) {
66
+ return browserCandidates(explicit)[0];
67
+ }
68
+
69
+ /**
70
+ * Launch the first candidate that starts. An explicit `--browser` is the only
71
+ * candidate tried when given.
72
+ * @param {string | undefined} explicit
73
+ */
74
+ export async function launchBrowser(explicit) {
75
+ const candidates = explicit ? [explicit] : browserCandidates(undefined);
76
+ if (!candidates.length) {
77
+ throw new Error(
78
+ 'No Chromium found. Install one with `npx playwright install chromium`, or pass --browser /path/to/chrome.'
79
+ );
80
+ }
81
+ /** @type {string[]} */
82
+ const failures = [];
83
+ for (const executablePath of candidates) {
84
+ try {
85
+ return await chromium.launch({ executablePath, headless: true });
86
+ } catch (error) {
87
+ failures.push(`${executablePath}: ${String(error instanceof Error ? error.message : error).split('\n')[0]}`);
88
+ }
89
+ }
90
+ throw new Error(
91
+ `Could not start Chromium. Tried:\n${failures.join('\n')}\nInstall one with \`npx playwright install chromium\` or pass --browser.`
92
+ );
93
+ }
@@ -0,0 +1,47 @@
1
+ import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { readdirSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ /** This package's root: the CLI ships inside `@samizdata/mozaic`, next to the recipe sources. */
7
+ const PACKAGE_ROOT = fileURLToPath(new URL('../../', import.meta.url));
8
+
9
+ /**
10
+ * Recipe names: the `.svelte` files in the package's `src/lib/recipes/`.
11
+ * @param {string} [root] package root (default: this package)
12
+ * @returns {string[]}
13
+ */
14
+ export function recipeNames(root = PACKAGE_ROOT) {
15
+ return readdirSync(join(root, 'src', 'lib', 'recipes'))
16
+ .filter((file) => file.endsWith('.svelte'))
17
+ .map((file) => file.slice(0, -'.svelte'.length))
18
+ .sort();
19
+ }
20
+
21
+ /**
22
+ * Rewrite a recipe's internal imports (`../core/index.js`) to package imports (`@samizdata/mozaic/core`).
23
+ * @param {string} source
24
+ */
25
+ export function rewriteImports(source) {
26
+ return source.replace(/from '\.\.\/([a-z]+)\/index\.js'/g, "from '@samizdata/mozaic/$1'");
27
+ }
28
+
29
+ /**
30
+ * Copy a recipe's source into the project so it can be edited freely.
31
+ * @param {{ name: string, to: string, cwd: string, force?: boolean, mozaicDir?: string }} options
32
+ * @returns {Promise<string>} the written file
33
+ */
34
+ export async function eject({ name, to, cwd, force = false, mozaicDir = PACKAGE_ROOT }) {
35
+ const recipes = recipeNames(mozaicDir);
36
+ if (!recipes.includes(name)) throw new Error(`Unknown recipe "${name}". Recipes: ${recipes.join(', ')}.`);
37
+ const source = await readFile(join(mozaicDir, 'src', 'lib', 'recipes', `${name}.svelte`), 'utf8');
38
+ const target = resolve(cwd, to, `${name}.svelte`);
39
+ const exists = await access(target).then(
40
+ () => true,
41
+ () => false
42
+ );
43
+ if (exists && !force) throw new Error(`${target} already exists. Use --force to overwrite it.`);
44
+ await mkdir(dirname(target), { recursive: true });
45
+ await writeFile(target, rewriteImports(source));
46
+ return target;
47
+ }
@@ -0,0 +1,133 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { launchBrowser } from './browser.js';
4
+ import { serveStatic } from './serve.js';
5
+
6
+ const PX_PER_MM = 96 / 25.4;
7
+
8
+ /** Interactive-only parts that do not belong in a static image. */
9
+ const HIDE_IN_IMAGES =
10
+ '.mz-chart-tools, .mz-tooltip, .mz-data-table, .mz-data-download, .mz-button-group, .mz-table-search, .mz-table-more { display: none !important; }';
11
+
12
+ /**
13
+ * @typedef {{ slug: string, style: string, locale: string, title: string, path: string, print: Record<string, number> }} EmbedEntry
14
+ * @typedef {{ project: string, embeds: EmbedEntry[] }} EmbedManifest
15
+ * @typedef {{ dir: string, out: string, only?: string[], formats: Set<string>, webWidth: number, browser?: string, log?: (line: string) => void }} ExportOptions
16
+ */
17
+
18
+ /**
19
+ * Wait until the embed page has hydrated, applied the requested medium and loaded its fonts.
20
+ * @param {import('playwright-core').Page} page
21
+ * @param {'web' | 'print'} medium
22
+ */
23
+ async function ready(page, medium) {
24
+ await page.waitForFunction(
25
+ (m) => {
26
+ const w = /** @type {any} */ (window);
27
+ const figure = document.querySelector('.mz-chart');
28
+ return Boolean(w.__mozaic?.ready && figure instanceof HTMLElement && figure.dataset.mzMedium === m);
29
+ },
30
+ medium,
31
+ { timeout: 15000 }
32
+ );
33
+ await page.evaluate(async () => {
34
+ await document.fonts.ready;
35
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
36
+ });
37
+ }
38
+
39
+ /**
40
+ * @param {import('playwright-core').Page} page
41
+ */
42
+ async function figureBox(page) {
43
+ const box = await page.locator('.mz-chart').first().boundingBox();
44
+ if (!box) throw new Error('No .mz-chart on the page.');
45
+ return box;
46
+ }
47
+
48
+ /**
49
+ * Export every embed in a built site's manifest to SVG, PDF and PNG.
50
+ * @param {ExportOptions} options
51
+ * @returns {Promise<string[]>} written file paths
52
+ */
53
+ export async function exportEmbeds(options) {
54
+ const { dir, out, only, formats, webWidth, log = () => {} } = options;
55
+ const manifest = /** @type {EmbedManifest} */ (
56
+ JSON.parse(await readFile(join(dir, 'embed', 'manifest.json'), 'utf8'))
57
+ );
58
+ const embeds = manifest.embeds.filter((e) => !only?.length || only.includes(e.slug));
59
+ if (!embeds.length)
60
+ throw new Error(only?.length ? `No embeds match --only ${only.join(',')}.` : 'The manifest lists no embeds.');
61
+
62
+ const server = await serveStatic(dir);
63
+ const browser = await launchBrowser(options.browser);
64
+ /** @type {string[]} */
65
+ const written = [];
66
+ /** @type {(file: string, data: string | Buffer) => Promise<void>} */
67
+ const save = async (file, data) => {
68
+ await mkdir(resolve(file, '..'), { recursive: true });
69
+ await writeFile(file, data);
70
+ written.push(file);
71
+ log(` ${file}`);
72
+ };
73
+
74
+ try {
75
+ const context = await browser.newContext({ deviceScaleFactor: 2, viewport: { width: webWidth, height: 800 } });
76
+ const page = await context.newPage();
77
+ /** @type {string[]} */
78
+ const errors = [];
79
+ page.on('pageerror', (error) => errors.push(error.message));
80
+
81
+ for (const embed of embeds) {
82
+ const folder = join(out, embed.slug, `${embed.style}-${embed.locale}`);
83
+ const url = new URL(embed.path, server.url).href;
84
+ log(`${embed.slug} (${embed.style}, ${embed.locale})`);
85
+
86
+ if (formats.has('png') || formats.has('svg')) {
87
+ await page.setViewportSize({ width: webWidth, height: 800 });
88
+ await page.goto(url);
89
+ await ready(page, 'web');
90
+ await page.addStyleTag({ content: HIDE_IN_IMAGES });
91
+ if (formats.has('png'))
92
+ await save(join(folder, 'web.png'), await page.locator('.mz-chart').first().screenshot());
93
+ if (formats.has('svg'))
94
+ await save(join(folder, 'web.svg'), await page.evaluate(() => /** @type {any} */ (window).__mozaic.toSvg()));
95
+ }
96
+
97
+ for (const [name, mm] of Object.entries(embed.print ?? {})) {
98
+ if (!formats.has('svg') && !formats.has('pdf')) break;
99
+ const width = Math.round(mm * PX_PER_MM);
100
+ await page.setViewportSize({ width: width + 32, height: 800 });
101
+ await page.goto(`${url}?medium=print&width=${width}`);
102
+ await ready(page, 'print');
103
+ if (formats.has('svg'))
104
+ await save(
105
+ join(folder, `print-${name}.svg`),
106
+ await page.evaluate(() => /** @type {any} */ (window).__mozaic.toSvg())
107
+ );
108
+ if (formats.has('pdf')) {
109
+ const box = await figureBox(page);
110
+ await page.emulateMedia({ media: 'screen' });
111
+ const pdf = await page.pdf({
112
+ width: `${Math.ceil(box.width)}px`,
113
+ height: `${Math.ceil(box.height)}px`,
114
+ printBackground: true,
115
+ pageRanges: '1'
116
+ });
117
+ await save(join(folder, `print-${name}.pdf`), pdf);
118
+ }
119
+ }
120
+ }
121
+
122
+ if (errors.length) throw new Error(`Page errors during export:\n${errors.join('\n')}`);
123
+ await save(
124
+ join(out, 'index.json'),
125
+ JSON.stringify({ project: manifest.project, files: written.map((f) => f.slice(out.length + 1)) }, null, 2)
126
+ );
127
+ await context.close();
128
+ } finally {
129
+ await browser.close();
130
+ await server.close();
131
+ }
132
+ return written;
133
+ }
@@ -0,0 +1,80 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { parseArgs } from './args.js';
4
+ import { exportEmbeds } from './export.js';
5
+ import { eject, recipeNames } from './eject.js';
6
+
7
+ const HELP = `mozaic — chart library tools
8
+
9
+ Usage:
10
+ mozaic export [dir] Export every embed in a built site (default dir: build)
11
+ --out <dir> Output folder (default: exports)
12
+ --only <slugs> Comma-separated chart slugs
13
+ --formats <list> svg,pdf,png (default: all)
14
+ --web-width <px> Width for web PNG/SVG (default: 640)
15
+ --browser <path> Chromium/Chrome executable (or set MOZAIC_BROWSER)
16
+
17
+ mozaic eject <recipe> Copy a recipe into your project to edit it
18
+ --to <dir> Destination (default: src/lib/recipes)
19
+ --force Overwrite an existing file
20
+
21
+ Recipes: ${recipeNames().join(', ')}
22
+
23
+ mozaic --version
24
+ mozaic --help
25
+ `;
26
+
27
+ /**
28
+ * @param {string[]} argv
29
+ * @returns {Promise<number>} exit code
30
+ */
31
+ export async function main(argv) {
32
+ const { positionals, options } = parseArgs(argv);
33
+ const [command, ...rest] = positionals;
34
+
35
+ if (options.version) {
36
+ const pkg = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8'));
37
+ console.log(pkg.version);
38
+ return 0;
39
+ }
40
+ if (!command || options.help || command === 'help') {
41
+ console.log(HELP);
42
+ return command || options.help ? 0 : 1;
43
+ }
44
+
45
+ if (command === 'export') {
46
+ const dir = resolve(rest[0] ?? 'build');
47
+ const out = resolve(typeof options.out === 'string' ? options.out : 'exports');
48
+ const formats = new Set(String(typeof options.formats === 'string' ? options.formats : 'svg,pdf,png').split(','));
49
+ const only = typeof options.only === 'string' ? options.only.split(',') : undefined;
50
+ const webWidth = Number(options['web-width'] ?? 640);
51
+ const files = await exportEmbeds({
52
+ dir,
53
+ out,
54
+ only,
55
+ formats,
56
+ webWidth,
57
+ browser: typeof options.browser === 'string' ? options.browser : undefined,
58
+ log: console.log
59
+ });
60
+ console.log(`Wrote ${files.length} files to ${out}`);
61
+ return 0;
62
+ }
63
+
64
+ if (command === 'eject') {
65
+ const name = rest[0];
66
+ if (!name) throw new Error(`Name a recipe: ${recipeNames().join(', ')}.`);
67
+ const file = await eject({
68
+ name,
69
+ to: typeof options.to === 'string' ? options.to : 'src/lib/recipes',
70
+ cwd: process.cwd(),
71
+ force: options.force === true
72
+ });
73
+ console.log(`Ejected ${name} to ${file}. Import it from there instead of '@samizdata/mozaic/recipes'.`);
74
+ return 0;
75
+ }
76
+
77
+ console.error(`Unknown command "${command}".\n`);
78
+ console.log(HELP);
79
+ return 1;
80
+ }
@@ -0,0 +1,54 @@
1
+ import { createServer } from 'node:http';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { extname, join, normalize, resolve, sep } from 'node:path';
4
+
5
+ /** @type {Record<string, string>} */
6
+ const TYPES = {
7
+ '.html': 'text/html; charset=utf-8',
8
+ '.js': 'text/javascript; charset=utf-8',
9
+ '.mjs': 'text/javascript; charset=utf-8',
10
+ '.css': 'text/css; charset=utf-8',
11
+ '.json': 'application/json; charset=utf-8',
12
+ '.svg': 'image/svg+xml',
13
+ '.png': 'image/png',
14
+ '.jpg': 'image/jpeg',
15
+ '.woff2': 'font/woff2',
16
+ '.woff': 'font/woff',
17
+ '.csv': 'text/csv; charset=utf-8',
18
+ '.txt': 'text/plain; charset=utf-8'
19
+ };
20
+
21
+ /**
22
+ * Serve a static directory on 127.0.0.1 (random port). Directory requests
23
+ * get their index.html. Returns the base URL and a close function.
24
+ * @param {string} dir
25
+ * @returns {Promise<{ url: string, close: () => Promise<void> }>}
26
+ */
27
+ export async function serveStatic(dir) {
28
+ const root = resolve(dir);
29
+ const server = createServer(async (req, res) => {
30
+ try {
31
+ const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname);
32
+ let file = normalize(join(root, pathname));
33
+ if (file !== root && !file.startsWith(root + sep))
34
+ throw Object.assign(new Error('Forbidden'), { code: 'EACCES' });
35
+ const info = await stat(file).catch(() => null);
36
+ if (info?.isDirectory()) file = join(file, 'index.html');
37
+ else if (!info && !extname(file)) file = `${file}.html`;
38
+ const body = await readFile(file);
39
+ res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream' });
40
+ res.end(body);
41
+ } catch (error) {
42
+ const code = /** @type {{ code?: string }} */ (error).code;
43
+ res.writeHead(code === 'EACCES' ? 403 : 404, { 'content-type': 'text/plain' });
44
+ res.end(code === 'EACCES' ? 'Forbidden' : 'Not found');
45
+ }
46
+ });
47
+ await new Promise((ok) => server.listen(0, '127.0.0.1', () => ok(undefined)));
48
+ const address = server.address();
49
+ if (!address || typeof address === 'string') throw new Error('Could not start the static server.');
50
+ return {
51
+ url: `http://127.0.0.1:${address.port}/`,
52
+ close: () => new Promise((ok) => server.close(() => ok(undefined)))
53
+ };
54
+ }
@@ -3,10 +3,12 @@
3
3
  A text annotation with an optional curved arrow pointing at a data point.
4
4
  `x`/`y` are in data space (band scales point at the band centre); `dx`/`dy`
5
5
  place the label in pixels relative to that point. Newlines split the label.
6
+ Pass `color` (the target's series colour) to colour the text and arrow.
6
7
  -->
7
8
  <script lang="ts">
8
9
  import { useChart, usePlot } from '../core/context.js';
9
10
  import { scaled } from '../core/scales.js';
11
+ import { readableColor } from '../styles/color.js';
10
12
  import { calloutGeometry } from './callout-geometry.js';
11
13
 
12
14
  interface Props {
@@ -21,6 +23,12 @@ place the label in pixels relative to that point. Newlines split the label.
21
23
  /** Defaults to `start` when the label is right of the target, `end` when left. */
22
24
  anchor?: 'start' | 'middle' | 'end';
23
25
  fontSize?: number;
26
+ /**
27
+ * Colour for the text and arrow, usually the series colour of the
28
+ * target. Darkened (or lightened on dark backgrounds) where needed to
29
+ * reach 4.5:1 against the background. Defaults to the text colour.
30
+ */
31
+ color?: string;
24
32
  class?: string;
25
33
  }
26
34
 
@@ -34,6 +42,7 @@ place the label in pixels relative to that point. Newlines split the label.
34
42
  arrow = true,
35
43
  anchor,
36
44
  fontSize,
45
+ color,
37
46
  class: className = ''
38
47
  }: Props = $props();
39
48
 
@@ -41,6 +50,7 @@ place the label in pixels relative to that point. Newlines split the label.
41
50
  const plot = usePlot();
42
51
 
43
52
  const size = $derived(fontSize ?? chart.theme.plot.fontSize);
53
+ const ink = $derived(color ? readableColor(color, chart.theme.tokens['--mz-color-bg']) : undefined);
44
54
  const lines = $derived(label.split('\n'));
45
55
  const lineHeight = $derived(size * 1.25);
46
56
  const textAnchor = $derived(anchor ?? (dx > 0 ? 'start' : dx < 0 ? 'end' : 'middle'));
@@ -59,10 +69,10 @@ place the label in pixels relative to that point. Newlines split the label.
59
69
 
60
70
  <g class="mz-callout {className}">
61
71
  {#if arrow}
62
- <path class="mz-callout-arrow" d={geometry.arrow} />
63
- <path class="mz-callout-arrow" d={geometry.head} />
72
+ <path class="mz-callout-arrow" d={geometry.arrow} style:stroke={ink} />
73
+ <path class="mz-callout-arrow" d={geometry.head} style:stroke={ink} />
64
74
  {/if}
65
- <text x={lx} y={ly} text-anchor={textAnchor} font-size={size}>
75
+ <text x={lx} y={ly} text-anchor={textAnchor} font-size={size} style:fill={ink}>
66
76
  {#each lines as line, i}
67
77
  <tspan x={lx} dy={i === 0 ? 0 : lineHeight}>{line}</tspan>
68
78
  {/each}
@@ -10,12 +10,19 @@ interface Props {
10
10
  /** Defaults to `start` when the label is right of the target, `end` when left. */
11
11
  anchor?: 'start' | 'middle' | 'end';
12
12
  fontSize?: number;
13
+ /**
14
+ * Colour for the text and arrow, usually the series colour of the
15
+ * target. Darkened (or lightened on dark backgrounds) where needed to
16
+ * reach 4.5:1 against the background. Defaults to the text colour.
17
+ */
18
+ color?: string;
13
19
  class?: string;
14
20
  }
15
21
  /**
16
22
  * A text annotation with an optional curved arrow pointing at a data point.
17
23
  * `x`/`y` are in data space (band scales point at the band centre); `dx`/`dy`
18
24
  * place the label in pixels relative to that point. Newlines split the label.
25
+ * Pass `color` (the target's series colour) to colour the text and arrow.
19
26
  */
20
27
  declare const Callout: import("svelte").Component<Props, {}, "">;
21
28
  type Callout = ReturnType<typeof Callout>;
@@ -2,10 +2,12 @@
2
2
  @component
3
3
  A label next to a data point, with an optional marker dot. For labelling a
4
4
  few highlighted points in a scatter plot. Text has a halo for legibility.
5
+ Pass `color` (the point's series colour) to colour the label and marker.
5
6
  -->
6
7
  <script lang="ts">
7
- import { usePlot } from '../core/context.js';
8
+ import { useChart, usePlot } from '../core/context.js';
8
9
  import { position } from '../core/scales.js';
10
+ import { readableColor } from '../styles/color.js';
9
11
 
10
12
  interface Props {
11
13
  x: unknown;
@@ -17,23 +19,43 @@ few highlighted points in a scatter plot. Text has a halo for legibility.
17
19
  /** Draw a ring around the point. */
18
20
  marker?: boolean;
19
21
  bold?: boolean;
22
+ /**
23
+ * Colour for the label and marker, usually the series colour of the
24
+ * point. Darkened (or lightened on dark backgrounds) where needed to
25
+ * reach 4.5:1 against the background. Defaults to the text colour.
26
+ */
27
+ color?: string;
20
28
  class?: string;
21
29
  }
22
30
 
23
- let { x, y, label, dx = 6, dy = 0, anchor, marker = false, bold = false, class: className = '' }: Props = $props();
31
+ let {
32
+ x,
33
+ y,
34
+ label,
35
+ dx = 6,
36
+ dy = 0,
37
+ anchor,
38
+ marker = false,
39
+ bold = false,
40
+ color,
41
+ class: className = ''
42
+ }: Props = $props();
24
43
 
44
+ const chart = useChart();
25
45
  const plot = usePlot();
26
46
  const p = $derived(position(plot, x, y));
27
47
  const textAnchor = $derived(anchor ?? (dx > 0 ? 'start' : dx < 0 ? 'end' : 'middle'));
48
+ const ink = $derived(color ? readableColor(color, chart.theme.tokens['--mz-color-bg']) : undefined);
28
49
  </script>
29
50
 
30
51
  <g class="mz-label {className}">
31
- {#if marker}<circle cx={p[0]} cy={p[1]} r={6} />{/if}
52
+ {#if marker}<circle cx={p[0]} cy={p[1]} r={6} style:stroke={ink} />{/if}
32
53
  <text
33
54
  x={p[0] + dx}
34
55
  y={p[1] + dy}
35
56
  dy="0.32em"
36
57
  text-anchor={textAnchor}
58
+ style:fill={ink}
37
59
  style:font-weight={bold ? 'var(--mz-weight-strong)' : undefined}>{label}</text
38
60
  >
39
61
  </g>
@@ -8,11 +8,18 @@ interface Props {
8
8
  /** Draw a ring around the point. */
9
9
  marker?: boolean;
10
10
  bold?: boolean;
11
+ /**
12
+ * Colour for the label and marker, usually the series colour of the
13
+ * point. Darkened (or lightened on dark backgrounds) where needed to
14
+ * reach 4.5:1 against the background. Defaults to the text colour.
15
+ */
16
+ color?: string;
11
17
  class?: string;
12
18
  }
13
19
  /**
14
20
  * A label next to a data point, with an optional marker dot. For labelling a
15
21
  * few highlighted points in a scatter plot. Text has a halo for legibility.
22
+ * Pass `color` (the point's series colour) to colour the label and marker.
16
23
  */
17
24
  declare const Label: import("svelte").Component<Props, {}, "">;
18
25
  type Label = ReturnType<typeof Label>;
@@ -1,12 +1,14 @@
1
1
  <!--
2
2
  @component
3
3
  Direct labels at the end of lines: a dot in the series colour on the last
4
- point, and the label in text colour beside it. Labels are nudged apart so
5
- they never overlap; a short leader joins a nudged label to its dot.
4
+ point, and the label beside it, in the text colour or (with `colorText`) in
5
+ the series colour so the labels double as the legend. Labels are nudged apart
6
+ so they never overlap; a short leader joins a nudged label to its dot.
6
7
  -->
7
8
  <script lang="ts" generics="T">
8
- import { usePlot } from '../core/context.js';
9
+ import { useChart, usePlot } from '../core/context.js';
9
10
  import { scaled } from '../core/scales.js';
11
+ import { readableColor } from '../styles/color.js';
10
12
  import { avoidOverlap } from '../transforms/labels.js';
11
13
 
12
14
  interface Props {
@@ -20,12 +22,19 @@ they never overlap; a short leader joins a nudged label to its dot.
20
22
  dx?: number;
21
23
  /** Minimum vertical distance between labels, px. */
22
24
  minGap?: number;
25
+ /**
26
+ * Colour each label like its series, darkened (or lightened on dark
27
+ * backgrounds) where needed to reach 4.5:1 against the background.
28
+ */
29
+ colorText?: boolean;
23
30
  class?: string;
24
31
  }
25
32
 
26
- let { data, x, y, text, color, dx = 10, minGap = 14, class: className = '' }: Props = $props();
33
+ let { data, x, y, text, color, dx = 10, minGap = 14, colorText = false, class: className = '' }: Props = $props();
27
34
 
35
+ const chart = useChart();
28
36
  const plot = usePlot();
37
+ const background = $derived(chart.theme.tokens['--mz-color-bg']);
29
38
 
30
39
  const labels = $derived.by(() => {
31
40
  const points = data.map((d) => ({ d, px: scaled(plot.x, x(d)), py: scaled(plot.y, y(d)) }));
@@ -44,7 +53,12 @@ they never overlap; a short leader joins a nudged label to its dot.
44
53
  <path class="mz-leader" d="M{label.px + 5},{label.py}L{label.px + dx - 3},{label.ly}" />
45
54
  {/if}
46
55
  <circle cx={label.px} cy={label.py} r={4} fill={color(label.d)} />
47
- <text x={label.px + dx} y={label.ly} dy="0.32em">{text(label.d)}</text>
56
+ <text
57
+ x={label.px + dx}
58
+ y={label.ly}
59
+ dy="0.32em"
60
+ style:fill={colorText ? readableColor(color(label.d), background) : undefined}>{text(label.d)}</text
61
+ >
48
62
  {/each}
49
63
  </g>
50
64
 
@@ -10,6 +10,11 @@ declare function $$render<T>(): {
10
10
  dx?: number;
11
11
  /** Minimum vertical distance between labels, px. */
12
12
  minGap?: number;
13
+ /**
14
+ * Colour each label like its series, darkened (or lightened on dark
15
+ * backgrounds) where needed to reach 4.5:1 against the background.
16
+ */
17
+ colorText?: boolean;
13
18
  class?: string;
14
19
  };
15
20
  exports: {};
@@ -33,8 +38,9 @@ interface $$IsomorphicComponent {
33
38
  }
34
39
  /**
35
40
  * Direct labels at the end of lines: a dot in the series colour on the last
36
- * point, and the label in text colour beside it. Labels are nudged apart so
37
- * they never overlap; a short leader joins a nudged label to its dot.
41
+ * point, and the label beside it, in the text colour or (with `colorText`) in
42
+ * the series colour so the labels double as the legend. Labels are nudged apart
43
+ * so they never overlap; a short leader joins a nudged label to its dot.
38
44
  */
39
45
  declare const LineEndLabels: $$IsomorphicComponent;
40
46
  type LineEndLabels<T> = InstanceType<typeof LineEndLabels<T>>;
@@ -2,6 +2,15 @@
2
2
  export declare function luminance(hex: string): number;
3
3
  /** WCAG contrast ratio between two `#rrggbb` colours (1–21). */
4
4
  export declare function contrastRatio(a: string, b: string): number;
5
+ /**
6
+ * A data colour that can be used for text: `color` itself when it reaches
7
+ * `minContrast` (WCAG 4.5:1 by default) against `background`, otherwise the
8
+ * least-changed shade of it that does, darkened towards black on light
9
+ * backgrounds and lightened towards white on dark ones. Lets a label take its
10
+ * series colour and still be readable. Colours that aren't `#rgb`/`#rrggbb`
11
+ * are returned unchanged.
12
+ */
13
+ export declare function readableColor(color: string, background?: string, minContrast?: number): string;
5
14
  /**
6
15
  * `n` colours from a light → dark ramp for binned data (choropleths, heat
7
16
  * steps). Steps too pale to see against `background` (below `minContrast`)
@@ -12,6 +12,54 @@ export function contrastRatio(a, b) {
12
12
  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
13
13
  return (hi + 0.05) / (lo + 0.05);
14
14
  }
15
+ const HEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
16
+ function expand(hex) {
17
+ const h = hex.slice(1);
18
+ return h.length === 3 ? `#${[...h].map((c) => c + c).join('')}` : hex;
19
+ }
20
+ function toLinear(c) {
21
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
22
+ }
23
+ function toHex(linear) {
24
+ return `#${linear
25
+ .map((c) => {
26
+ const s = c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
27
+ return Math.round(Math.min(1, Math.max(0, s)) * 255)
28
+ .toString(16)
29
+ .padStart(2, '0');
30
+ })
31
+ .join('')}`;
32
+ }
33
+ /**
34
+ * A data colour that can be used for text: `color` itself when it reaches
35
+ * `minContrast` (WCAG 4.5:1 by default) against `background`, otherwise the
36
+ * least-changed shade of it that does, darkened towards black on light
37
+ * backgrounds and lightened towards white on dark ones. Lets a label take its
38
+ * series colour and still be readable. Colours that aren't `#rgb`/`#rrggbb`
39
+ * are returned unchanged.
40
+ */
41
+ export function readableColor(color, background = '#ffffff', minContrast = 4.5) {
42
+ if (!HEX.test(color) || !HEX.test(background))
43
+ return color;
44
+ const c = expand(color).toLowerCase();
45
+ const bg = expand(background);
46
+ if (contrastRatio(c, bg) >= minContrast)
47
+ return c;
48
+ const target = contrastRatio('#000000', bg) >= contrastRatio('#ffffff', bg) ? 0 : 1;
49
+ const n = parseInt(c.slice(1), 16);
50
+ const linear = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((v) => toLinear(v / 255));
51
+ const mix = (t) => toHex(linear.map((v) => v + (target - v) * t));
52
+ // Smallest mix towards black/white that passes; contrast rises with t.
53
+ let [lo, hi] = [0, 1];
54
+ for (let i = 0; i < 24; i++) {
55
+ const mid = (lo + hi) / 2;
56
+ if (contrastRatio(mix(mid), bg) >= minContrast)
57
+ hi = mid;
58
+ else
59
+ lo = mid;
60
+ }
61
+ return mix(hi);
62
+ }
15
63
  /**
16
64
  * `n` colours from a light → dark ramp for binned data (choropleths, heat
17
65
  * steps). Steps too pale to see against `background` (below `minContrast`)
@@ -2,7 +2,7 @@ import type { Breakpoint, Theme } from './types.js';
2
2
  export type { Breakpoint, Medium, Padding, Theme, ThemeOverrides } from './types.js';
3
3
  /** House styles live with each brand (e.g. `datavis/mozaic/` in a brand repo) and extend `base`. */
4
4
  export { base, extendTheme } from './base.js';
5
- export { contrastRatio, luminance, rampSteps } from './color.js';
5
+ export { contrastRatio, luminance, rampSteps, readableColor } from './color.js';
6
6
  export { checkTheme } from './check.js';
7
7
  /** Serialise theme tokens into an inline `style` attribute value. */
8
8
  export declare function tokensToStyle(tokens: Theme['tokens']): string;
@@ -1,6 +1,6 @@
1
1
  /** House styles live with each brand (e.g. `datavis/mozaic/` in a brand repo) and extend `base`. */
2
2
  export { base, extendTheme } from './base.js';
3
- export { contrastRatio, luminance, rampSteps } from './color.js';
3
+ export { contrastRatio, luminance, rampSteps, readableColor } from './color.js';
4
4
  export { checkTheme } from './check.js';
5
5
  /** Serialise theme tokens into an inline `style` attribute value. */
6
6
  export function tokensToStyle(tokens) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@samizdata/mozaic",
3
- "version": "0.6.0",
4
- "description": "Chart components for the web and print, built on Svelte 5 and d3.",
3
+ "version": "0.8.0",
4
+ "description": "Chart components for the web and print, built on Svelte 5 and d3, and the mozaic CLI (export embeds to SVG, PDF and PNG; eject recipes).",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "author": "Nicu Calcea",
7
7
  "repository": {
@@ -12,9 +12,14 @@
12
12
  "homepage": "https://github.com/samizdata-co/mozaic#readme",
13
13
  "bugs": "https://github.com/samizdata-co/mozaic/issues",
14
14
  "type": "module",
15
+ "bin": {
16
+ "mozaic": "./cli/bin/mozaic.js"
17
+ },
15
18
  "files": [
16
19
  "dist",
17
20
  "src/lib/recipes",
21
+ "cli/bin",
22
+ "cli/src",
18
23
  "!dist/**/*.test.*",
19
24
  "!dist/**/*.spec.*"
20
25
  ],
@@ -107,7 +112,8 @@
107
112
  "d3-hierarchy": "^3.1.2",
108
113
  "d3-scale": "^4.0.2",
109
114
  "d3-shape": "^3.2.0",
110
- "d3-time-format": "^4.1.0"
115
+ "d3-time-format": "^4.1.0",
116
+ "playwright-core": "1.64.1"
111
117
  },
112
118
  "devDependencies": {
113
119
  "@sveltejs/adapter-auto": "^8.0.0",
@@ -124,6 +130,7 @@
124
130
  "@types/d3-shape": "^3.1.6",
125
131
  "@types/d3-time-format": "^4.0.3",
126
132
  "@types/geojson": "^7946.0.14",
133
+ "@types/node": "^24.0.0",
127
134
  "@vitest/coverage-v8": "^4.1.12",
128
135
  "d3-scale-chromatic": "^3.1.0",
129
136
  "linkedom": "^0.18.14",
@@ -144,10 +151,13 @@
144
151
  "#lib": "./src/lib/index.js",
145
152
  "#lib/*": "./src/lib/*"
146
153
  },
154
+ "engines": {
155
+ "node": ">=22.17"
156
+ },
147
157
  "scripts": {
148
158
  "dev": "vite dev",
149
159
  "package": "svelte-kit sync && svelte-package && publint",
150
- "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
160
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && tsc -p cli/jsconfig.json",
151
161
  "test:unit": "vitest",
152
162
  "test": "vitest --run",
153
163
  "test:coverage": "vitest --run --coverage"