sparklemacsparkline 0.0.0-stage → 1.0.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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright 2026 Jens Oliver Meiert
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,153 @@
1
- # Temporary Holding Version
1
+ # Sparkle MacSparkline, the SVG Sparkline Generator
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/sparklemacsparkline.svg)](https://www.npmjs.com/package/sparklemacsparkline) [![Build status](https://github.com/j9t/sparklemacsparkline/workflows/Tests/badge.svg)](https://github.com/j9t/sparklemacsparkline/actions) [![Socket](https://badge.socket.dev/npm/package/sparklemacsparkline)](https://socket.dev/npm/package/sparklemacsparkline) [![GitHub Sponsors](https://badgen.net/static/Support/Open%20Source/cyan)](https://github.com/sponsors/j9t)
4
+
5
+ Sparkle MacSparkline turns a series of numbers into a word-sized SVG sparkline—a small line without axes, meant to sit inside running text rather than to be studied on its own. It runs without dependencies and without a browser, which makes it a fit for build steps (like static site generators) and the command line.
6
+
7
+ Each sparkline describes itself to assistive technology, follows the surrounding text color (and with it dark mode and forced colors), and comes as compact markup ready to be inlined.
8
+
9
+ ## Example
10
+
11
+ ```shell
12
+ $ npx sparklemacsparkline --stdout --labels 2006,2007,2008,2009,2010 4,42,50,34,13
13
+ ```
14
+
15
+ ```html
16
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 16" width="48" height="16" role="img" class="sparkline"><title>Sparkline of 5 values from 2006 to 2010: rising from 4 to a peak of 50 in 2008, then falling to 13</title><path class="sparkline-line" d="M1.44 13.51L12.72 3.54 24 1.44 35.28 5.64 46.56 11.15" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"/><circle class="sparkline-dot" cx="46.56" cy="11.15" r="1.44" fill="currentColor"/></svg>
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### Programmatic Use
22
+
23
+ Install Sparkle MacSparkline in your project, e.g., via `npm i -D sparklemacsparkline`, then import and use it:
24
+
25
+ ```js
26
+ import { sparkline } from 'sparklemacsparkline';
27
+
28
+ const svg = sparkline([4, 42, 50, 34, 13], { title: 'Posts per year' });
29
+ ```
30
+
31
+ `sparkline()` returns the markup as a string. It takes an array of at least two finite numbers, and an options object:
32
+
33
+ ```js
34
+ {
35
+ accent: 'red', // color of the end dot (defaults to `foreground`)
36
+ axis: true, // set to `false` to leave out the axis drawn where a series crosses zero
37
+ background: '#fff', // background color (none by default)
38
+ classes: true, // set to `false` to leave out class names
39
+ decorative: false, // set to `true` to hide the chart from assistive technology
40
+ foreground: 'currentColor', // line color
41
+ height: 16, // height
42
+ labels: ['2006', …], // one label per value, naming the range and the peak in the description
43
+ style: 'inline', // set to `external` to leave all presentation to a style sheet
44
+ tight: false, // set to `true` to scale to the data range instead of starting at zero
45
+ title: 'Posts per year', // lead of the description (none by default)
46
+ width: 48 // width (defaults to 4 per value, from 48 to 160)
47
+ }
48
+ ```
49
+
50
+ Invalid input throws: a `RangeError` for too few values, mismatched labels, an unknown style, or a size that isn’t a positive number; a `TypeError` for values that aren’t finite numbers, colors that don’t look like CSS colors, or colors combined with the external style.
51
+
52
+ `describeSeries(values, { labels, title })` returns the description `sparkline()` uses as the accessible name—for a visible caption or an `img` element’s `alt` text, for example.
53
+
54
+ #### Example: Eleventy
55
+
56
+ As the work happens in memory, there’s no need for files or caching. A filter could look like this:
57
+
58
+ ```js
59
+ import { sparkline } from 'sparklemacsparkline';
60
+
61
+ eleventyConfig.addFilter('sparkline', values => sparkline(values, { decorative: true, width: 160, height: 20 }));
62
+ ```
63
+
64
+ ### CLI
65
+
66
+ ```shell
67
+ npx sparklemacsparkline [options] <values>
68
+ … | npx sparklemacsparkline [options]
69
+ ```
70
+
71
+ Values are separated by commas or whitespace, so both `4,42,50` and a column of numbers piped in work. A series starting with a negative value needs `--` before it, after all options (`npx sparklemacsparkline --tight --stdout -- -10,5,-3,8`).
72
+
73
+ | Option | Description |
74
+ | --- | --- |
75
+ | `--labels <list>` | Comma-separated labels, one per value |
76
+ | `--title <text>` | Title (leads the description, names the default file) |
77
+ | `--tight` | Scale to the data range instead of starting at zero |
78
+ | `--no-axis` | Leave out the axis drawn where a series crosses zero |
79
+ | `--decorative` | Hide the chart from assistive technology |
80
+ | `--no-class` | Leave out class names |
81
+ | `--width <number>` | Width (defaults to 4 per value, from 48 to 160) |
82
+ | `--height <number>` | Height (defaults to 16) |
83
+ | `--style <style>` | `inline` (default) or `external` |
84
+ | `--foreground <css>` | Line color (defaults to `currentColor`) |
85
+ | `--background <css>` | Background color (none by default) |
86
+ | `--accent <css>` | Color of the end dot (defaults to the foreground color) |
87
+ | `--output <path>` | File to write, overwriting it |
88
+ | `--stdout` | Print the markup instead of writing a file |
89
+ | `--version` | Show the version |
90
+ | `--help` | Show usage information |
91
+
92
+ Without `--output` or `--stdout`, the sparkline is written to a file named after the title—“Posts per year” becomes posts-per-year.svg, and sparkline.svg stands in without a title. As that name is guessed rather than given, an existing file is never overwritten; the name gets a number instead. `--output` overwrites, so that regenerating into a fixed path stays idempotent.
93
+
94
+ Exit code is `0` on success, `1` without usable data (no values, or just one), and `2` on malformed input or options.
95
+
96
+ ## How It Works
97
+
98
+ ### Accessibility
99
+
100
+ Each sparkline carries `role="img"` and a `title` element describing the shape of the line—where it starts and ends, and the peak or low in between (e.g., “rising from 4 to a peak of 50 in 2008, then falling to 13”). That element serves as the accessible name and as the tooltip, so the description isn’t repeated in an `aria-label`. A title leads the description and (on the command line) names the file.
101
+
102
+ The description is in English, with numbers formatted accordingly (“1,234.57”).
103
+
104
+ The description only applies to inlined markup. Referenced as an image (`<img src="sparkline.svg">`), an SVG file’s own labeling is ignored, and the `img` element needs an `alt` attribute instead—`describeSeries()` can provide its text.
105
+
106
+ `decorative` replaces `role="img"` with `aria-hidden="true"`—the tooltip stays—for charts that repeat what the surrounding page already says—inside a heading, for example, where a description would otherwise become part of the heading’s accessible name. Use it only where the data is available elsewhere.
107
+
108
+ ### Scale
109
+
110
+ The vertical scale starts at zero by default. Scaling to the range of the data instead makes every series fill the box, which exaggerates variation on a high floor—a run of 80 to 89 would look like the same mountain as a run of 4 to 89. Use `tight` when the shape matters more than the magnitude.
111
+
112
+ A series that crosses zero gets a faint axis at zero, as the sign of a value is otherwise invisible. An all-positive series doesn’t get one, as zero is the floor there already.
113
+
114
+ ### Presentation
115
+
116
+ Presentation is inline by default: Colors are set as presentation attributes on the elements, which keeps the output valid as a standalone file and, unlike an embedded `style` element, cannot leak rules into a page it’s inlined in. As the default color is `currentColor`, an inlined sparkline still follows the surrounding text color, dark mode, and forced-colors mode. (Custom colors don’t adapt to forced-colors mode.)
117
+
118
+ With the external style, the elements carry class names only (`sparkline`, `sparkline-line`, `sparkline-dot`, `sparkline-axis`), leaving all presentation to a style sheet. Without classes, the elements can be selected by context, as in `h2 svg path`.
119
+
120
+ ## Working on Sparkle MacSparkline
121
+
122
+ Note: This section assumes working with dependencies installed (`npm i`).
123
+
124
+ ### Tests
125
+
126
+ ```shell
127
+ npm test
128
+ ```
129
+
130
+ Runs the type tests (`tsc`, against `test/types.test.ts`) and then the suites in `test/`: `sparkline.test.js` (the API) and `cli.test.js` (the command line, exit codes, file output).
131
+
132
+ `npm run lint` (or `lint:fix`) covers the rest.
133
+
134
+ ### Layout
135
+
136
+ ```text
137
+ bin/
138
+ sparklemacsparkline.js Executable entry point—wiring only
139
+
140
+ src/
141
+ index.js Public API (re-exports only)
142
+ index.d.ts Type definitions
143
+ sparkline.js Drawing and description
144
+ cli.js The command line
145
+ ```
146
+
147
+ ***
148
+
149
+ You might like some of my other work:
150
+
151
+ * Optimization tools: [hihtml](https://github.com/j9t/hihtml) · [HTML Minifier](https://github.com/j9t/html-minifier) · [CSS Dedup](https://github.com/j9t/css-dedup) · [Image Guard](https://github.com/j9t/image-guard) · [more](https://github.com/j9t?tab=repositories)
152
+ * Defense tools: [AWAGAM TLD, Domain, and URL Blocker](https://iadefensa.com/solutions/awagam-chromium/) · [Middleman Alerter](https://iadefensa.com/solutions/middleman-alerter-chromium/) · [New Tab Traffic Randomizer](https://iadefensa.com/solutions/new-tab-traffic-randomizer-chromium/) · [Searcher](https://iadefensa.com/solutions/searcher-chromium/) · [more](https://iadefensa.com/solutions/)
153
+ * Resources for quality web development: [Articles](https://meiert.com/topics/development/) · [Books](https://meiert.com/topics/books/) · [News](https://dxsrc.org/) · [Terminology](https://webglossary.info/)
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { runCli } from '../src/cli.js';
4
+
5
+ process.exitCode = await runCli(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
+ "author": "Jens Oliver Meiert",
3
+ "bin": {
4
+ "sparklemacsparkline": "bin/sparklemacsparkline.js"
5
+ },
6
+ "description": "Dependency-free SVG sparkline generator for build steps and the command line",
7
+ "devDependencies": {
8
+ "@eslint/js": "^10.0.1",
9
+ "eslint": "^10.15.0",
10
+ "globals": "^17.14.0",
11
+ "typescript": "^7.0.2"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./src/index.d.ts",
16
+ "default": "./src/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "bin",
21
+ "src"
22
+ ],
23
+ "funding": "https://github.com/j9t/sparklemacsparkline?sponsor=1",
24
+ "homepage": "https://github.com/j9t/sparklemacsparkline",
25
+ "keywords": [
26
+ "accessibility",
27
+ "charts",
28
+ "sparklemacsparkline",
29
+ "sparklines",
30
+ "static-site-generators",
31
+ "svg",
32
+ "visualization"
33
+ ],
34
+ "license": "MIT",
2
35
  "name": "sparklemacsparkline",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/j9t/sparklemacsparkline.git"
39
+ },
40
+ "scripts": {
41
+ "lint": "eslint .",
42
+ "lint:fix": "eslint . --fix",
43
+ "prepare": "git config core.hooksPath .githooks || true",
44
+ "start": "node ./bin/sparklemacsparkline.js",
45
+ "test": "npm run test:types && node --test \"test/**/*.test.js\"",
46
+ "test:types": "tsc"
47
+ },
48
+ "type": "module",
49
+ "types": "src/index.d.ts",
50
+ "version": "1.0.0"
6
51
  }
package/src/cli.js ADDED
@@ -0,0 +1,178 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { parseArgs } from 'node:util';
3
+ import { sparkline } from './sparkline.js';
4
+
5
+ const help = `Usage:
6
+ sparklemacsparkline [options] <values>
7
+ … | sparklemacsparkline [options]
8
+
9
+ Turns a comma- or whitespace-separated series of numbers into an SVG sparkline.
10
+ A series starting with a negative value needs \`--\` before it, after all options.
11
+
12
+ Options:
13
+ --labels <list> Comma-separated labels, one per value, for the description
14
+ --title <text> Title (leads the description, names the default file)
15
+ --tight Scale to the data range instead of starting at zero
16
+ --no-axis Leave out the axis drawn where a series crosses zero
17
+ --decorative Hide the chart from assistive technology
18
+ --no-class Leave out class names
19
+ --width <number> Width (defaults to 4 per value, from 48 to 160)
20
+ --height <number> Height (defaults to 16)
21
+ --style <style> “inline” (default) or “external” (class names only)
22
+ --foreground <css> Line color (defaults to currentColor)
23
+ --background <css> Background color (none by default)
24
+ --accent <css> Color of the end dot (defaults to the foreground)
25
+ --output <path> File to write, overwriting it
26
+ --stdout Print the markup instead of writing a file
27
+ --version Show the version
28
+ --help Show this help
29
+
30
+ Without \`--output\` or \`--stdout\`, the file is named after the title
31
+ (“sparkline.svg” without one), and a number is added rather than overwriting.
32
+
33
+ Exit codes: 0 success, 1 no usable data, 2 error`;
34
+
35
+ const options = {
36
+ accent: { type: 'string' },
37
+ background: { type: 'string' },
38
+ decorative: { type: 'boolean', default: false },
39
+ foreground: { type: 'string' },
40
+ height: { type: 'string' },
41
+ help: { type: 'boolean', default: false },
42
+ labels: { type: 'string' },
43
+ 'no-axis': { type: 'boolean', default: false },
44
+ 'no-class': { type: 'boolean', default: false },
45
+ output: { type: 'string' },
46
+ stdout: { type: 'boolean', default: false },
47
+ style: { type: 'string' },
48
+ tight: { type: 'boolean', default: false },
49
+ title: { type: 'string' },
50
+ version: { type: 'boolean', default: false },
51
+ width: { type: 'string' }
52
+ };
53
+
54
+ // German umlauts and the sharp s spell themselves out rather than losing the
55
+ // letter—“ß” has no decomposition, so stripping marks alone would drop it
56
+ const foldingsGerman = { 'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss' };
57
+
58
+ // “Posts per year” → “posts-per-year”
59
+ export function slugify(text) {
60
+ const slug = text
61
+ .toLowerCase()
62
+ .replace(/[äöüß]/g, character => foldingsGerman[character])
63
+ .normalize('NFKD')
64
+ .replace(/[̀-ͯ]/g, '')
65
+ .replace(/[^a-z0-9]+/g, '-')
66
+ .replace(/^-+|-+$/g, '');
67
+ return slug || 'sparkline';
68
+ }
69
+
70
+ // “chart.svg” taken becomes “chart-2.svg”, then “chart-3.svg”
71
+ function findFreePath(base) {
72
+ if (!existsSync(`${base}.svg`)) return `${base}.svg`;
73
+ for (let suffix = 2; ; suffix++) {
74
+ const candidate = `${base}-${suffix}.svg`;
75
+ if (!existsSync(candidate)) return candidate;
76
+ }
77
+ }
78
+
79
+ // Split on commas or whitespace, so both `4,42,50` and a column of numbers work
80
+ export function parseSeries(input) {
81
+ return input
82
+ .split(/[,\s]+/)
83
+ .filter(Boolean)
84
+ .map(Number);
85
+ }
86
+
87
+ // Reading fd 0 synchronously fails with EAGAIN on a non-blocking pipe, so
88
+ // consume the stream instead
89
+ async function readStdin() {
90
+ const chunks = [];
91
+ for await (const chunk of process.stdin) chunks.push(chunk);
92
+ return Buffer.concat(chunks).toString('utf8');
93
+ }
94
+
95
+ // Strings stay strings so that `sparkline()` rejects them with its own message
96
+ function toNumber(value) {
97
+ return value === undefined || value.trim() === '' ? value : Number(value);
98
+ }
99
+
100
+ // Returns the exit code rather than exiting, so that output gets flushed
101
+ export async function runCli(args) {
102
+ const fail = (message, code = 2) => {
103
+ console.error(`❌ ${message}`);
104
+ return code;
105
+ };
106
+
107
+ let parsed;
108
+ try {
109
+ parsed = parseArgs({ args, allowPositionals: true, options });
110
+ } catch (err) {
111
+ return fail(err.message);
112
+ }
113
+ const { values: flags, positionals } = parsed;
114
+
115
+ if (flags.help) {
116
+ console.log(help);
117
+ return 0;
118
+ }
119
+ if (flags.version) {
120
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
121
+ console.log(version);
122
+ return 0;
123
+ }
124
+ if (flags.stdout && flags.output !== undefined) {
125
+ return fail('`--stdout` and `--output` ask for different things—pick one.');
126
+ }
127
+
128
+ const input = positionals.length
129
+ ? positionals.join(',')
130
+ : (process.stdin.isTTY ? '' : await readStdin());
131
+ const series = parseSeries(input);
132
+ if (!series.length) {
133
+ return fail('No data—pass a comma-separated list of values, or pipe them in.', 1);
134
+ }
135
+ if (series.some(Number.isNaN)) {
136
+ return fail('Every value has to be a number.');
137
+ }
138
+ if (series.length < 2) {
139
+ return fail('A sparkline needs at least two values.', 1);
140
+ }
141
+
142
+ let svg;
143
+ try {
144
+ svg = sparkline(series, {
145
+ accent: flags.accent,
146
+ axis: !flags['no-axis'],
147
+ background: flags.background,
148
+ classes: !flags['no-class'],
149
+ decorative: flags.decorative,
150
+ foreground: flags.foreground,
151
+ height: toNumber(flags.height),
152
+ labels: flags.labels?.split(',').map(label => label.trim()),
153
+ style: flags.style,
154
+ tight: flags.tight,
155
+ title: flags.title,
156
+ width: toNumber(flags.width)
157
+ });
158
+ } catch (err) {
159
+ return fail(err.message);
160
+ }
161
+
162
+ if (flags.stdout) {
163
+ process.stdout.write(svg + '\n');
164
+ return 0;
165
+ }
166
+
167
+ // An explicit path is taken as given, overwriting included—only the guessed
168
+ // name steps aside for an existing file. No trailing newline, since the byte
169
+ // would become stray whitespace wherever the markup is inlined.
170
+ const pathOutput = flags.output ?? findFreePath(slugify(flags.title ?? 'sparkline'));
171
+ try {
172
+ writeFileSync(pathOutput, svg);
173
+ } catch (err) {
174
+ return fail(`Could not write to “${pathOutput}”.\n ${err.message}`);
175
+ }
176
+ console.error(`✅ Wrote “${pathOutput}”.`);
177
+ return 0;
178
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ export interface DescribeOptions {
2
+ /** One label per value, e.g., years; names the range and the peak */
3
+ labels?: string[];
4
+ /** What the data is; leads the description */
5
+ title?: string;
6
+ }
7
+
8
+ export interface SparklineOptions extends DescribeOptions {
9
+ /** Color of the end dot (defaults to `foreground`) */
10
+ accent?: string;
11
+ /** Set to `false` to leave out the axis drawn where a series crosses zero (defaults to `true`) */
12
+ axis?: boolean;
13
+ /** Background color (none by default) */
14
+ background?: string;
15
+ /** Set to `false` to leave out class names (defaults to `true`) */
16
+ classes?: boolean;
17
+ /** Set to `true` to hide the chart from assistive technology (defaults to `false`) */
18
+ decorative?: boolean;
19
+ /** Line color (defaults to `currentColor`) */
20
+ foreground?: string;
21
+ /** Height (defaults to 16) */
22
+ height?: number;
23
+ /** `inline` (default) for presentation attributes, `external` for class names only */
24
+ style?: 'inline' | 'external';
25
+ /** Set to `true` to scale to the data range instead of starting at zero */
26
+ tight?: boolean;
27
+ /** Width (defaults to 4 per value, from 48 to 160) */
28
+ width?: number;
29
+ }
30
+
31
+ /** Returns the sparkline as SVG markup */
32
+ export function sparkline(values: number[], options?: SparklineOptions): string;
33
+
34
+ /** Returns the text description used as the sparkline’s accessible name */
35
+ export function describeSeries(values: number[], options?: DescribeOptions): string;
package/src/index.js ADDED
@@ -0,0 +1 @@
1
+ export { describeSeries, sparkline } from './sparkline.js';
@@ -0,0 +1,221 @@
1
+ const heightDefault = 16; // One rem at a typical root size
2
+ const stepDefault = 4; // Horizontal distance per data point
3
+ const widthMin = 48;
4
+ const widthMax = 160; // Past roughly this a sparkline wants to be a real chart
5
+ const widthStroke = 1.25; // Hairline at any size, which is the point of a sparkline
6
+ const radiusDotMin = 1.25;
7
+ const radiusDotMax = 4;
8
+ const ratioDot = .09; // Dot radius as a share of the height
9
+ const widthAxis = .5; // The axis stays recessive against the data
10
+ const opacityAxis = .35;
11
+
12
+ export const styles = ['inline', 'external'];
13
+
14
+ // Permissive enough for hex, functional notation, keywords, and `var(…)`, while
15
+ // keeping out the quotes and angle brackets that could break out of an attribute
16
+ const patternColor = /^[\w#(),.%/ +*-]+$/;
17
+
18
+ // Trim the leading zero of a decimal, the way a minifier would: `0.5` → `.5`
19
+ function format(number) {
20
+ return String(number).replace(/^(-?)0\./, '$1.');
21
+ }
22
+
23
+ // For the description: `1234.567` → “1,234.57”, without float artifacts
24
+ // like `0.30000000000000004`
25
+ function formatNumber(number) {
26
+ return number.toLocaleString('en-US', { maximumFractionDigits: 2 });
27
+ }
28
+
29
+ function round(number) {
30
+ return Math.round(number * 100) / 100;
31
+ }
32
+
33
+ function escapeAttribute(value) {
34
+ return String(value)
35
+ .replace(/&/g, '&amp;')
36
+ .replace(/</g, '&lt;')
37
+ .replace(/>/g, '&gt;')
38
+ .replace(/"/g, '&quot;');
39
+ }
40
+
41
+ function checkValues(values) {
42
+ if (!Array.isArray(values) || values.some(value => typeof value !== 'number' || !Number.isFinite(value))) {
43
+ throw new TypeError('Every value has to be a finite number.');
44
+ }
45
+ if (values.length < 2) {
46
+ throw new RangeError('A sparkline needs at least two values.');
47
+ }
48
+ }
49
+
50
+ function checkLabels(labels, values) {
51
+ if (labels === undefined) return;
52
+ if (!Array.isArray(labels)) {
53
+ throw new TypeError('`labels` has to be an array.');
54
+ }
55
+ if (labels.length !== values.length) {
56
+ throw new RangeError(`Got ${labels.length} labels for ${values.length} values—they have to match.`);
57
+ }
58
+ }
59
+
60
+ function checkColor(value, name) {
61
+ if (value === undefined) return;
62
+ if (typeof value !== 'string' || !patternColor.test(value)) {
63
+ throw new TypeError(`\`${value}\` does not look like a CSS color (\`${name}\`).`);
64
+ }
65
+ }
66
+
67
+ function checkSize(value, name) {
68
+ if (value === undefined) return;
69
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
70
+ throw new RangeError(`\`${value}\` is not a positive number (\`${name}\`).`);
71
+ }
72
+ }
73
+
74
+ // One pass rather than `Math.min(...values)`, which overflows the argument
75
+ // stack somewhere past 100,000 values
76
+ function findExtent(values) {
77
+ let min = Infinity;
78
+ let max = -Infinity;
79
+ for (const value of values) {
80
+ if (value < min) min = value;
81
+ if (value > max) max = value;
82
+ }
83
+ return { min, max };
84
+ }
85
+
86
+ // Describes the shape of the line for anyone who cannot see it; a title says
87
+ // what the data is, which the shape alone never conveys, so it leads
88
+ export function describeSeries(values, { labels, title } = {}) {
89
+ checkValues(values);
90
+ checkLabels(labels, values);
91
+
92
+ const { min, max } = findExtent(values);
93
+ const first = values[0];
94
+ const last = values.at(-1);
95
+ const span = max - min;
96
+
97
+ // A turn is worth mentioning only once it covers part of the spread
98
+ const exceeds = difference => difference > span * .05;
99
+ const hasPeak = exceeds(max - first) && exceeds(max - last);
100
+ const hasLow = exceeds(first - min) && exceeds(last - min);
101
+ const at = value => {
102
+ const label = labels?.[values.indexOf(value)];
103
+ return label ? ` in ${label}` : '';
104
+ };
105
+
106
+ let shape;
107
+ if (span === 0) {
108
+ shape = `steady at ${formatNumber(first)}`;
109
+ } else if (hasPeak && hasLow) {
110
+ shape = `ranging from ${formatNumber(min)}${at(min)} to ${formatNumber(max)}${at(max)}, ending at ${formatNumber(last)}`;
111
+ } else if (hasPeak) {
112
+ shape = `rising from ${formatNumber(first)} to a peak of ${formatNumber(max)}${at(max)}, then falling to ${formatNumber(last)}`;
113
+ } else if (hasLow) {
114
+ shape = `falling from ${formatNumber(first)} to a low of ${formatNumber(min)}${at(min)}, then rising to ${formatNumber(last)}`;
115
+ } else {
116
+ // Without a turn between them, the ends are the extremes
117
+ shape = `${last > first ? 'rising' : 'falling'} from ${formatNumber(first)} to ${formatNumber(last)}`;
118
+ }
119
+
120
+ const scope = labels ? ` from ${labels[0]} to ${labels.at(-1)}` : '';
121
+ const lead = title ? `${title.replace(/[.\s]+$/, '')}—sparkline` : 'Sparkline';
122
+ return `${lead} of ${values.length} values${scope}: ${shape}`;
123
+ }
124
+
125
+ export function sparkline(values, options = {}) {
126
+ checkValues(values);
127
+
128
+ const {
129
+ accent,
130
+ axis = true,
131
+ background,
132
+ classes = true,
133
+ decorative = false,
134
+ foreground = 'currentColor',
135
+ height = heightDefault,
136
+ labels,
137
+ style = 'inline',
138
+ tight = false,
139
+ title,
140
+ width = Math.min(widthMax, Math.max(widthMin, (values.length - 1) * stepDefault))
141
+ } = options;
142
+
143
+ checkLabels(labels, values);
144
+ checkSize(height, 'height');
145
+ checkSize(width, 'width');
146
+ checkColor(foreground, 'foreground');
147
+ checkColor(background, 'background');
148
+ checkColor(accent, 'accent');
149
+ if (!styles.includes(style)) {
150
+ throw new RangeError(`Unknown style “${style}”—expected ${styles.map(name => `“${name}”`).join(' or ')}.`);
151
+ }
152
+
153
+ // A style sheet owns every color in external mode, so a color passed here
154
+ // would silently do nothing
155
+ const isInline = style === 'inline';
156
+ const colorsPassed = ['foreground', 'background', 'accent'].filter(name => options[name] !== undefined);
157
+ if (!isInline && colorsPassed.length) {
158
+ throw new TypeError(`\`${colorsPassed[0]}\` has no effect with the “external” style—colors come from the style sheet there.`);
159
+ }
160
+ const colorAccent = accent ?? foreground;
161
+
162
+ // Without class names the elements are addressed by type, e.g., “h2 svg path”
163
+ const naming = suffix => classes ? ` class="sparkline${suffix}"` : '';
164
+
165
+ // A zero baseline keeps the domain anchored, so a series on a high floor
166
+ // reads as high rather than as filling the box
167
+ const extent = findExtent(values);
168
+ const domainMin = tight ? extent.min : Math.min(0, extent.min);
169
+ const domainMax = tight ? extent.max : Math.max(0, extent.max);
170
+ const span = domainMax - domainMin || 1; // A flat series draws flat, not NaN
171
+
172
+ // The dot tracks the height, so that it stays visible on a tall chart without
173
+ // swelling on a short one; the stroke stays hairline either way
174
+ const radiusDot = round(Math.min(radiusDotMax, Math.max(radiusDotMin, height * ratioDot)));
175
+
176
+ const padding = Math.max(widthStroke, radiusDot); // Room for the stroke and the dot
177
+ const step = (width - padding * 2) / (values.length - 1);
178
+ const toY = value => round(height - padding - (value - domainMin) / span * (height - padding * 2));
179
+
180
+ const points = values.map((value, index) => [round(padding + index * step), toY(value)]);
181
+ const [pointLastX, pointLastY] = points.at(-1);
182
+
183
+ // After one “L”, further coordinate pairs are implicit linetos, so the
184
+ // command letter is only needed once
185
+ const [pointHead, ...pointsRest] = points.map(([x, y]) => `${format(x)} ${format(y)}`);
186
+ const d = `M${pointHead}L${pointsRest.join(' ')}`;
187
+
188
+ const attributesPath = isInline
189
+ ? ` fill="none" stroke="${escapeAttribute(foreground)}" stroke-width="${format(widthStroke)}"` +
190
+ ' stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"'
191
+ : '';
192
+ const attributesDot = isInline ? ` fill="${escapeAttribute(colorAccent)}"` : '';
193
+ const attributesAxis = isInline
194
+ ? ` stroke="${escapeAttribute(foreground)}" stroke-width="${format(widthAxis)}" opacity="${format(opacityAxis)}"`
195
+ : '';
196
+
197
+ const markupBackground = background
198
+ ? `<rect width="100%" height="100%" fill="${escapeAttribute(background)}"/>`
199
+ : '';
200
+
201
+ // Only worth drawing where the series actually crosses zero—with an
202
+ // all-positive series zero is the floor already
203
+ const crossesZero = domainMin < 0 && domainMax > 0;
204
+ const yZero = toY(0);
205
+ const markupAxis = axis && crossesZero
206
+ ? `<line${naming('-axis')} x1="0" y1="${format(yZero)}" x2="${width}" y2="${format(yZero)}"${attributesAxis}/>`
207
+ : '';
208
+
209
+ const markupPath = `<path${naming('-line')} d="${d}"${attributesPath}/>`;
210
+ const markupDot = `<circle${naming('-dot')} cx="${format(pointLastX)}" cy="${format(pointLastY)}" r="${format(radiusDot)}"${attributesDot}/>`;
211
+ // The title element names the chart and doubles as the tooltip, so the
212
+ // description isn’t repeated in `aria-label`. A decorative chart keeps the
213
+ // tooltip but is hidden from assistive technology, which is what a heading
214
+ // needs: A descendant name would otherwise be folded into the heading’s own.
215
+ const markupTitle = `<title>${escapeAttribute(describeSeries(values, { labels, title }))}</title>`;
216
+ const attributesRole = decorative ? ' aria-hidden="true"' : ' role="img"';
217
+
218
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}"` +
219
+ ` width="${width}" height="${height}"${attributesRole}${naming('')}>` +
220
+ `${markupTitle}${markupBackground}${markupAxis}${markupPath}${markupDot}</svg>`;
221
+ }