@samizdata/mozaic 0.5.1 → 0.7.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 +21 -2
- package/cli/bin/mozaic.js +10 -0
- package/cli/src/args.js +32 -0
- package/cli/src/browser.js +93 -0
- package/cli/src/eject.js +47 -0
- package/cli/src/export.js +133 -0
- package/cli/src/main.js +80 -0
- package/cli/src/serve.js +54 -0
- package/dist/frame/Source.svelte +32 -3
- package/dist/frame/Source.svelte.d.ts +13 -4
- package/dist/frame/index.d.ts +1 -0
- package/dist/frame/types.d.ts +7 -0
- package/dist/frame/types.js +1 -0
- package/dist/recipes/ArrowChart.svelte +4 -3
- package/dist/recipes/ArrowChart.svelte.d.ts +3 -1
- package/dist/recipes/BarChart.svelte +4 -3
- package/dist/recipes/BarChart.svelte.d.ts +3 -1
- package/dist/recipes/BarDotChart.svelte +4 -3
- package/dist/recipes/BarDotChart.svelte.d.ts +3 -1
- package/dist/recipes/ColumnChart.svelte +4 -3
- package/dist/recipes/ColumnChart.svelte.d.ts +3 -1
- package/dist/recipes/LineChart.svelte +4 -3
- package/dist/recipes/LineChart.svelte.d.ts +3 -1
- package/dist/recipes/MosaicChart.svelte +4 -3
- package/dist/recipes/MosaicChart.svelte.d.ts +3 -1
- package/dist/recipes/PercentileChart.svelte +4 -3
- package/dist/recipes/PercentileChart.svelte.d.ts +3 -1
- package/dist/recipes/ScatterChart.svelte +4 -3
- package/dist/recipes/ScatterChart.svelte.d.ts +3 -1
- package/dist/recipes/StackedBarChart.svelte +4 -3
- package/dist/recipes/StackedBarChart.svelte.d.ts +3 -1
- package/package.json +14 -4
- package/src/lib/recipes/ArrowChart.svelte +4 -3
- package/src/lib/recipes/BarChart.svelte +4 -3
- package/src/lib/recipes/BarDotChart.svelte +4 -3
- package/src/lib/recipes/ColumnChart.svelte +4 -3
- package/src/lib/recipes/LineChart.svelte +4 -3
- package/src/lib/recipes/MosaicChart.svelte +4 -3
- package/src/lib/recipes/PercentileChart.svelte +4 -3
- package/src/lib/recipes/ScatterChart.svelte +4 -3
- package/src/lib/recipes/StackedBarChart.svelte +4 -3
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.
|
package/cli/src/args.js
ADDED
|
@@ -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
|
+
}
|
package/cli/src/eject.js
ADDED
|
@@ -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
|
+
}
|
package/cli/src/main.js
ADDED
|
@@ -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
|
+
}
|
package/cli/src/serve.js
ADDED
|
@@ -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
|
+
}
|
package/dist/frame/Source.svelte
CHANGED
|
@@ -1,18 +1,38 @@
|
|
|
1
1
|
<!--
|
|
2
2
|
@component
|
|
3
|
-
"Source: …", with the label in the chart's language.
|
|
3
|
+
"Source: …", with the label in the chart's language. Pass `sources` as text or as a list of
|
|
4
|
+
sources with optional links (`[{ label: 'ANRE', href: 'https://anre.md/…' }, …]`, joined with
|
|
5
|
+
"; "), or write the text as children. The label turns plural for more than one listed source,
|
|
6
|
+
or set `plural`. Links open in a new tab; in print they are plain text.
|
|
4
7
|
-->
|
|
5
8
|
<script lang="ts">
|
|
6
9
|
import type { Snippet } from 'svelte';
|
|
7
10
|
import { useChart } from '../core/context.js';
|
|
11
|
+
import type { SourceItem } from './types.js';
|
|
8
12
|
|
|
9
|
-
|
|
13
|
+
interface Props {
|
|
14
|
+
/** The sources: plain text, or a list of sources with optional links. */
|
|
15
|
+
sources?: string | SourceItem[];
|
|
16
|
+
/** Use the plural label ("Sources"). Defaults to true for more than one item in `sources`. */
|
|
17
|
+
plural?: boolean;
|
|
18
|
+
children?: Snippet;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let { sources, plural, children }: Props = $props();
|
|
10
22
|
|
|
11
23
|
const chart = useChart();
|
|
24
|
+
const items = $derived<SourceItem[]>(typeof sources === 'string' ? [{ label: sources }] : (sources ?? []));
|
|
25
|
+
const many = $derived(plural ?? (Array.isArray(sources) && sources.length > 1));
|
|
26
|
+
const linked = $derived(chart.medium !== 'print');
|
|
12
27
|
</script>
|
|
13
28
|
|
|
14
29
|
<p class="mz-source">
|
|
15
|
-
<span class="mz-label">{
|
|
30
|
+
<span class="mz-label">{many ? chart.locale.strings.sources : chart.locale.strings.source}:</span>
|
|
31
|
+
{#each items as item, i (i)}{i > 0 ? '; ' : ''}{#if item.href && linked}<a
|
|
32
|
+
href={item.href}
|
|
33
|
+
target="_blank"
|
|
34
|
+
rel="noopener">{item.label}</a
|
|
35
|
+
>{:else}{item.label}{/if}{/each}
|
|
16
36
|
{@render children?.()}
|
|
17
37
|
</p>
|
|
18
38
|
|
|
@@ -26,4 +46,13 @@
|
|
|
26
46
|
text-transform: var(--mz-label-transform);
|
|
27
47
|
letter-spacing: var(--mz-label-tracking);
|
|
28
48
|
}
|
|
49
|
+
.mz-source a {
|
|
50
|
+
color: inherit;
|
|
51
|
+
text-decoration-line: underline;
|
|
52
|
+
text-decoration-thickness: 1px;
|
|
53
|
+
text-underline-offset: 2px;
|
|
54
|
+
}
|
|
55
|
+
.mz-source a:hover {
|
|
56
|
+
text-decoration-thickness: 2px;
|
|
57
|
+
}
|
|
29
58
|
</style>
|
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import type { Snippet } from 'svelte';
|
|
2
|
-
type
|
|
2
|
+
import type { SourceItem } from './types.js';
|
|
3
|
+
interface Props {
|
|
4
|
+
/** The sources: plain text, or a list of sources with optional links. */
|
|
5
|
+
sources?: string | SourceItem[];
|
|
6
|
+
/** Use the plural label ("Sources"). Defaults to true for more than one item in `sources`. */
|
|
3
7
|
plural?: boolean;
|
|
4
8
|
children?: Snippet;
|
|
5
|
-
}
|
|
6
|
-
/**
|
|
7
|
-
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* "Source: …", with the label in the chart's language. Pass `sources` as text or as a list of
|
|
12
|
+
* sources with optional links (`[{ label: 'ANRE', href: 'https://anre.md/…' }, …]`, joined with
|
|
13
|
+
* "; "), or write the text as children. The label turns plural for more than one listed source,
|
|
14
|
+
* or set `plural`. Links open in a new tab; in print they are plain text.
|
|
15
|
+
*/
|
|
16
|
+
declare const Source: import("svelte").Component<Props, {}, "">;
|
|
8
17
|
type Source = ReturnType<typeof Source>;
|
|
9
18
|
export default Source;
|
package/dist/frame/index.d.ts
CHANGED
|
@@ -10,3 +10,4 @@ export { default as Byline } from './Byline.svelte';
|
|
|
10
10
|
export { default as DataTable } from './DataTable.svelte';
|
|
11
11
|
export { default as DataDownload } from './DataDownload.svelte';
|
|
12
12
|
export { setDownloads, useChart, useLocale, useTheme } from '../core/context.js';
|
|
13
|
+
export type { SourceItem } from './types.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -11,7 +11,7 @@ project and change anything.
|
|
|
11
11
|
import type { Snippet } from 'svelte';
|
|
12
12
|
import { scaleBand, scaleLinear } from 'd3-scale';
|
|
13
13
|
import { max, min } from 'd3-array';
|
|
14
|
-
import { Chart, Header, Title, Subtitle, Footer, Source, Notes } from '../frame/index.js';
|
|
14
|
+
import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
|
|
15
15
|
import type { ChartEmbed } from '../embed/index.js';
|
|
16
16
|
import { Plot, Svg, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
|
|
17
17
|
import { Arrows } from '../marks/index.js';
|
|
@@ -38,7 +38,8 @@ project and change anything.
|
|
|
38
38
|
title?: string;
|
|
39
39
|
subtitle?: string;
|
|
40
40
|
notes?: string;
|
|
41
|
-
|
|
41
|
+
/** Plain text, or sources with optional links (see `<Source>`). */
|
|
42
|
+
source?: string | SourceItem[];
|
|
42
43
|
alt?: string;
|
|
43
44
|
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
44
45
|
embed?: ChartEmbed;
|
|
@@ -215,7 +216,7 @@ project and change anything.
|
|
|
215
216
|
{#if notes || source}
|
|
216
217
|
<Footer>
|
|
217
218
|
{#if notes}<Notes>{notes}</Notes>{/if}
|
|
218
|
-
{#if source}<Source
|
|
219
|
+
{#if source}<Source sources={source} />{/if}
|
|
219
220
|
</Footer>
|
|
220
221
|
{/if}
|
|
221
222
|
</Chart>
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Snippet } from 'svelte';
|
|
2
|
+
import { type SourceItem } from '../frame/index.js';
|
|
2
3
|
import type { ChartEmbed } from '../embed/index.js';
|
|
3
4
|
import { type PlotContext } from '../core/index.js';
|
|
4
5
|
import { type LocaleCode } from '../locale/index.js';
|
|
@@ -21,7 +22,8 @@ declare function $$render<T>(): {
|
|
|
21
22
|
title?: string;
|
|
22
23
|
subtitle?: string;
|
|
23
24
|
notes?: string;
|
|
24
|
-
|
|
25
|
+
/** Plain text, or sources with optional links (see `<Source>`). */
|
|
26
|
+
source?: string | SourceItem[];
|
|
25
27
|
alt?: string;
|
|
26
28
|
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
27
29
|
embed?: ChartEmbed;
|
|
@@ -8,7 +8,7 @@ file into your project and change anything.
|
|
|
8
8
|
import type { Snippet } from 'svelte';
|
|
9
9
|
import { scaleBand, scaleLinear } from 'd3-scale';
|
|
10
10
|
import { max, min } from 'd3-array';
|
|
11
|
-
import { Chart, Header, Title, Subtitle, Footer, Source, Notes } from '../frame/index.js';
|
|
11
|
+
import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
|
|
12
12
|
import type { ChartEmbed } from '../embed/index.js';
|
|
13
13
|
import { Plot, Svg, Html, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
|
|
14
14
|
import { Bars, Rules, Text } from '../marks/index.js';
|
|
@@ -28,7 +28,8 @@ file into your project and change anything.
|
|
|
28
28
|
title?: string;
|
|
29
29
|
subtitle?: string;
|
|
30
30
|
notes?: string;
|
|
31
|
-
|
|
31
|
+
/** Plain text, or sources with optional links (see `<Source>`). */
|
|
32
|
+
source?: string | SourceItem[];
|
|
32
33
|
alt?: string;
|
|
33
34
|
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
34
35
|
embed?: ChartEmbed;
|
|
@@ -116,7 +117,7 @@ file into your project and change anything.
|
|
|
116
117
|
{#if notes || source}
|
|
117
118
|
<Footer>
|
|
118
119
|
{#if notes}<Notes>{notes}</Notes>{/if}
|
|
119
|
-
{#if source}<Source
|
|
120
|
+
{#if source}<Source sources={source} />{/if}
|
|
120
121
|
</Footer>
|
|
121
122
|
{/if}
|
|
122
123
|
</Chart>
|