sparklemacsparkline 0.0.0-stage → 1.0.1
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 +21 -0
- package/README.md +154 -2
- package/bin/sparklemacsparkline.js +5 -0
- package/package.json +49 -3
- package/src/cli.js +178 -0
- package/src/index.d.ts +35 -0
- package/src/index.js +1 -0
- package/src/sparkline.js +276 -0
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,155 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Sparkle MacSparkline, the SVG Sparkline Generator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/sparklemacsparkline) [](https://github.com/j9t/sparklemacsparkline/actions) [](https://socket.dev/npm/package/sparklemacsparkline) [](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.51 12.72 3.54 24 1.44l11.28 4.2 11.28 5.51" 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
|
+
The markup is as short as valid SVG allows: Path data uses the shortest of absolute and relative commands per segment, numbers are rounded to two decimals without leading zeros, and default attributes are left out. What remains is needed for a standalone file (`xmlns`, quoted attributes)—a minifier can still drop that when the sparkline is inlined in HTML.
|
|
119
|
+
|
|
120
|
+
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`.
|
|
121
|
+
|
|
122
|
+
## Working on Sparkle MacSparkline
|
|
123
|
+
|
|
124
|
+
Note: This section assumes working with dependencies installed (`npm i`).
|
|
125
|
+
|
|
126
|
+
### Tests
|
|
127
|
+
|
|
128
|
+
```shell
|
|
129
|
+
npm test
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
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).
|
|
133
|
+
|
|
134
|
+
`npm run lint` (or `lint:fix`) covers the rest.
|
|
135
|
+
|
|
136
|
+
### Layout
|
|
137
|
+
|
|
138
|
+
```text
|
|
139
|
+
bin/
|
|
140
|
+
sparklemacsparkline.js Executable entry point—wiring only
|
|
141
|
+
|
|
142
|
+
src/
|
|
143
|
+
index.js Public API (re-exports only)
|
|
144
|
+
index.d.ts Type definitions
|
|
145
|
+
sparkline.js Drawing and description
|
|
146
|
+
cli.js The command line
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
***
|
|
150
|
+
|
|
151
|
+
You might like some of my other work:
|
|
152
|
+
|
|
153
|
+
* 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)
|
|
154
|
+
* 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/)
|
|
155
|
+
* 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/)
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
|
+
"author": "Jens Oliver Meiert",
|
|
3
|
+
"bin": {
|
|
4
|
+
"sparklemacsparkline": "bin/sparklemacsparkline.js"
|
|
5
|
+
},
|
|
6
|
+
"description": "Non-British SVG sparkline generator for build steps and the command line, as seen on dxsrc.org and meiert.com",
|
|
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
|
+
"data-visualization",
|
|
29
|
+
"sparklemacsparkline",
|
|
30
|
+
"sparklines",
|
|
31
|
+
"static-site-generators",
|
|
32
|
+
"svg",
|
|
33
|
+
"visualization"
|
|
34
|
+
],
|
|
35
|
+
"license": "MIT",
|
|
2
36
|
"name": "sparklemacsparkline",
|
|
3
|
-
"
|
|
4
|
-
|
|
5
|
-
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/j9t/sparklemacsparkline.git"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"lint": "eslint .",
|
|
43
|
+
"lint:fix": "eslint . --fix",
|
|
44
|
+
"prepare": "git config core.hooksPath .githooks || true",
|
|
45
|
+
"start": "node ./bin/sparklemacsparkline.js",
|
|
46
|
+
"test": "npm run test:types && node --test \"test/**/*.test.js\"",
|
|
47
|
+
"test:types": "tsc"
|
|
48
|
+
},
|
|
49
|
+
"type": "module",
|
|
50
|
+
"types": "src/index.d.ts",
|
|
51
|
+
"version": "1.0.1"
|
|
6
52
|
}
|
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';
|
package/src/sparkline.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
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
|
+
// A minus sign or a second decimal point already separates two numbers
|
|
34
|
+
function needsSpace(previous, next) {
|
|
35
|
+
return !(next.startsWith('-') || (next.startsWith('.') && previous.includes('.')));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The shortest path data through the points: per segment, the shortest of
|
|
39
|
+
// absolute and relative lineto (and their horizontal and vertical forms),
|
|
40
|
+
// repeating command letters only where the command changes. Relative coordinates
|
|
41
|
+
// come from the rounded points, so they add up to exactly the same positions.
|
|
42
|
+
function makePath(points) {
|
|
43
|
+
// Per state—the current command and whether the last number has a decimal
|
|
44
|
+
// point—the shortest path so far, as its length and its last part, which
|
|
45
|
+
// links back to the ones before (no nested arrays, as series can be long)
|
|
46
|
+
let states = new Map();
|
|
47
|
+
const [xStart, yStart] = points[0].map(format);
|
|
48
|
+
const textStart = `${xStart}${needsSpace(xStart, yStart) ? ' ' : ''}${yStart}`;
|
|
49
|
+
// `m` from the origin is absolute, too, but makes the coordinates after it relative
|
|
50
|
+
for (const command of ['L', 'l']) {
|
|
51
|
+
const text = `${command === 'L' ? 'M' : 'm'}${textStart}`;
|
|
52
|
+
states.set(command + yStart.includes('.'), { command, last: yStart, length: text.length, part: { text } });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
for (let index = 1; index < points.length; index++) {
|
|
56
|
+
const [x0, y0] = points[index - 1];
|
|
57
|
+
const [x1, y1] = points[index];
|
|
58
|
+
const dx = round(x1 - x0);
|
|
59
|
+
const dy = round(y1 - y0);
|
|
60
|
+
const options = [['L', [x1, y1]], ['l', [dx, dy]]];
|
|
61
|
+
if (dy === 0) options.push(['H', [x1]], ['h', [dx]]);
|
|
62
|
+
// Only in dense or narrow charts, where neighboring points round to the same x
|
|
63
|
+
if (dx === 0) options.push(['V', [y1]], ['v', [dy]]);
|
|
64
|
+
|
|
65
|
+
const statesNext = new Map();
|
|
66
|
+
for (const state of states.values()) {
|
|
67
|
+
for (const [command, numbers] of options) {
|
|
68
|
+
let text = command === state.command ? '' : command;
|
|
69
|
+
let last = text ? null : state.last;
|
|
70
|
+
for (const number of numbers.map(format)) {
|
|
71
|
+
if (last !== null && needsSpace(last, number)) text += ' ';
|
|
72
|
+
text += number;
|
|
73
|
+
last = number;
|
|
74
|
+
}
|
|
75
|
+
const key = command + last.includes('.');
|
|
76
|
+
const length = state.length + text.length;
|
|
77
|
+
if (!statesNext.has(key) || length < statesNext.get(key).length) {
|
|
78
|
+
statesNext.set(key, { command, last, length, part: { previous: state.part, text } });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
states = statesNext;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const parts = [];
|
|
86
|
+
let { part } = [...states.values()].reduce((a, b) => (b.length < a.length ? b : a));
|
|
87
|
+
for (; part; part = part.previous) parts.push(part.text);
|
|
88
|
+
return parts.reverse().join('');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function escapeAttribute(value) {
|
|
92
|
+
return String(value)
|
|
93
|
+
.replace(/&/g, '&')
|
|
94
|
+
.replace(/</g, '<')
|
|
95
|
+
.replace(/>/g, '>')
|
|
96
|
+
.replace(/"/g, '"');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function checkValues(values) {
|
|
100
|
+
if (!Array.isArray(values) || values.some(value => typeof value !== 'number' || !Number.isFinite(value))) {
|
|
101
|
+
throw new TypeError('Every value has to be a finite number.');
|
|
102
|
+
}
|
|
103
|
+
if (values.length < 2) {
|
|
104
|
+
throw new RangeError('A sparkline needs at least two values.');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function checkLabels(labels, values) {
|
|
109
|
+
if (labels === undefined) return;
|
|
110
|
+
if (!Array.isArray(labels)) {
|
|
111
|
+
throw new TypeError('`labels` has to be an array.');
|
|
112
|
+
}
|
|
113
|
+
if (labels.length !== values.length) {
|
|
114
|
+
throw new RangeError(`Got ${labels.length} labels for ${values.length} values—they have to match.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function checkColor(value, name) {
|
|
119
|
+
if (value === undefined) return;
|
|
120
|
+
if (typeof value !== 'string' || !patternColor.test(value)) {
|
|
121
|
+
throw new TypeError(`\`${value}\` does not look like a CSS color (\`${name}\`).`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function checkSize(value, name) {
|
|
126
|
+
if (value === undefined) return;
|
|
127
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
|
128
|
+
throw new RangeError(`\`${value}\` is not a positive number (\`${name}\`).`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// One pass rather than `Math.min(...values)`, which overflows the argument
|
|
133
|
+
// stack somewhere past 100,000 values
|
|
134
|
+
function findExtent(values) {
|
|
135
|
+
let min = Infinity;
|
|
136
|
+
let max = -Infinity;
|
|
137
|
+
for (const value of values) {
|
|
138
|
+
if (value < min) min = value;
|
|
139
|
+
if (value > max) max = value;
|
|
140
|
+
}
|
|
141
|
+
return { min, max };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Describes the shape of the line for anyone who cannot see it; a title says
|
|
145
|
+
// what the data is, which the shape alone never conveys, so it leads
|
|
146
|
+
export function describeSeries(values, { labels, title } = {}) {
|
|
147
|
+
checkValues(values);
|
|
148
|
+
checkLabels(labels, values);
|
|
149
|
+
|
|
150
|
+
const { min, max } = findExtent(values);
|
|
151
|
+
const first = values[0];
|
|
152
|
+
const last = values.at(-1);
|
|
153
|
+
const span = max - min;
|
|
154
|
+
|
|
155
|
+
// A turn is worth mentioning only once it covers part of the spread
|
|
156
|
+
const exceeds = difference => difference > span * .05;
|
|
157
|
+
const hasPeak = exceeds(max - first) && exceeds(max - last);
|
|
158
|
+
const hasLow = exceeds(first - min) && exceeds(last - min);
|
|
159
|
+
const at = value => {
|
|
160
|
+
const label = labels?.[values.indexOf(value)];
|
|
161
|
+
return label ? ` in ${label}` : '';
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
let shape;
|
|
165
|
+
if (span === 0) {
|
|
166
|
+
shape = `steady at ${formatNumber(first)}`;
|
|
167
|
+
} else if (hasPeak && hasLow) {
|
|
168
|
+
shape = `ranging from ${formatNumber(min)}${at(min)} to ${formatNumber(max)}${at(max)}, ending at ${formatNumber(last)}`;
|
|
169
|
+
} else if (hasPeak) {
|
|
170
|
+
shape = `rising from ${formatNumber(first)} to a peak of ${formatNumber(max)}${at(max)}, then falling to ${formatNumber(last)}`;
|
|
171
|
+
} else if (hasLow) {
|
|
172
|
+
shape = `falling from ${formatNumber(first)} to a low of ${formatNumber(min)}${at(min)}, then rising to ${formatNumber(last)}`;
|
|
173
|
+
} else {
|
|
174
|
+
// Without a turn between them, the ends are the extremes
|
|
175
|
+
shape = `${last > first ? 'rising' : 'falling'} from ${formatNumber(first)} to ${formatNumber(last)}`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const scope = labels ? ` from ${labels[0]} to ${labels.at(-1)}` : '';
|
|
179
|
+
const lead = title ? `${title.replace(/[.\s]+$/, '')}—sparkline` : 'Sparkline';
|
|
180
|
+
return `${lead} of ${values.length} values${scope}: ${shape}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function sparkline(values, options = {}) {
|
|
184
|
+
checkValues(values);
|
|
185
|
+
|
|
186
|
+
const {
|
|
187
|
+
accent,
|
|
188
|
+
axis = true,
|
|
189
|
+
background,
|
|
190
|
+
classes = true,
|
|
191
|
+
decorative = false,
|
|
192
|
+
foreground = 'currentColor',
|
|
193
|
+
height = heightDefault,
|
|
194
|
+
labels,
|
|
195
|
+
style = 'inline',
|
|
196
|
+
tight = false,
|
|
197
|
+
title,
|
|
198
|
+
width = Math.min(widthMax, Math.max(widthMin, (values.length - 1) * stepDefault))
|
|
199
|
+
} = options;
|
|
200
|
+
|
|
201
|
+
checkLabels(labels, values);
|
|
202
|
+
checkSize(height, 'height');
|
|
203
|
+
checkSize(width, 'width');
|
|
204
|
+
checkColor(foreground, 'foreground');
|
|
205
|
+
checkColor(background, 'background');
|
|
206
|
+
checkColor(accent, 'accent');
|
|
207
|
+
if (!styles.includes(style)) {
|
|
208
|
+
throw new RangeError(`Unknown style “${style}”—expected ${styles.map(name => `“${name}”`).join(' or ')}.`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// A style sheet owns every color in external mode, so a color passed here
|
|
212
|
+
// would silently do nothing
|
|
213
|
+
const isInline = style === 'inline';
|
|
214
|
+
const colorsPassed = ['foreground', 'background', 'accent'].filter(name => options[name] !== undefined);
|
|
215
|
+
if (!isInline && colorsPassed.length) {
|
|
216
|
+
throw new TypeError(`\`${colorsPassed[0]}\` has no effect with the “external” style—colors come from the style sheet there.`);
|
|
217
|
+
}
|
|
218
|
+
const colorAccent = accent ?? foreground;
|
|
219
|
+
|
|
220
|
+
// Without class names the elements are addressed by type, e.g., “h2 svg path”
|
|
221
|
+
const naming = suffix => classes ? ` class="sparkline${suffix}"` : '';
|
|
222
|
+
|
|
223
|
+
// A zero baseline keeps the domain anchored, so a series on a high floor
|
|
224
|
+
// reads as high rather than as filling the box
|
|
225
|
+
const extent = findExtent(values);
|
|
226
|
+
const domainMin = tight ? extent.min : Math.min(0, extent.min);
|
|
227
|
+
const domainMax = tight ? extent.max : Math.max(0, extent.max);
|
|
228
|
+
const span = domainMax - domainMin || 1; // A flat series draws flat, not NaN
|
|
229
|
+
|
|
230
|
+
// The dot tracks the height, so that it stays visible on a tall chart without
|
|
231
|
+
// swelling on a short one; the stroke stays hairline either way
|
|
232
|
+
const radiusDot = round(Math.min(radiusDotMax, Math.max(radiusDotMin, height * ratioDot)));
|
|
233
|
+
|
|
234
|
+
const padding = Math.max(widthStroke, radiusDot); // Room for the stroke and the dot
|
|
235
|
+
const step = (width - padding * 2) / (values.length - 1);
|
|
236
|
+
const toY = value => round(height - padding - (value - domainMin) / span * (height - padding * 2));
|
|
237
|
+
|
|
238
|
+
const points = values.map((value, index) => [round(padding + index * step), toY(value)]);
|
|
239
|
+
const [pointLastX, pointLastY] = points.at(-1);
|
|
240
|
+
|
|
241
|
+
const d = makePath(points);
|
|
242
|
+
|
|
243
|
+
const attributesPath = isInline
|
|
244
|
+
? ` fill="none" stroke="${escapeAttribute(foreground)}" stroke-width="${format(widthStroke)}"` +
|
|
245
|
+
' stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"'
|
|
246
|
+
: '';
|
|
247
|
+
const attributesDot = isInline ? ` fill="${escapeAttribute(colorAccent)}"` : '';
|
|
248
|
+
const attributesAxis = isInline
|
|
249
|
+
? ` stroke="${escapeAttribute(foreground)}" stroke-width="${format(widthAxis)}" opacity="${format(opacityAxis)}"`
|
|
250
|
+
: '';
|
|
251
|
+
|
|
252
|
+
const markupBackground = background
|
|
253
|
+
? `<rect width="100%" height="100%" fill="${escapeAttribute(background)}"/>`
|
|
254
|
+
: '';
|
|
255
|
+
|
|
256
|
+
// Only worth drawing where the series actually crosses zero—with an
|
|
257
|
+
// all-positive series zero is the floor already
|
|
258
|
+
const crossesZero = domainMin < 0 && domainMax > 0;
|
|
259
|
+
const yZero = toY(0);
|
|
260
|
+
const markupAxis = axis && crossesZero
|
|
261
|
+
? `<line${naming('-axis')} y1="${format(yZero)}" x2="${format(width)}" y2="${format(yZero)}"${attributesAxis}/>`
|
|
262
|
+
: '';
|
|
263
|
+
|
|
264
|
+
const markupPath = `<path${naming('-line')} d="${d}"${attributesPath}/>`;
|
|
265
|
+
const markupDot = `<circle${naming('-dot')} cx="${format(pointLastX)}" cy="${format(pointLastY)}" r="${format(radiusDot)}"${attributesDot}/>`;
|
|
266
|
+
// The title element names the chart and doubles as the tooltip, so the
|
|
267
|
+
// description isn’t repeated in `aria-label`. A decorative chart keeps the
|
|
268
|
+
// tooltip but is hidden from assistive technology, which is what a heading
|
|
269
|
+
// needs: A descendant name would otherwise be folded into the heading’s own.
|
|
270
|
+
const markupTitle = `<title>${escapeAttribute(describeSeries(values, { labels, title }))}</title>`;
|
|
271
|
+
const attributesRole = decorative ? ' aria-hidden="true"' : ' role="img"';
|
|
272
|
+
|
|
273
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${format(width)} ${format(height)}"` +
|
|
274
|
+
` width="${format(width)}" height="${format(height)}"${attributesRole}${naming('')}>` +
|
|
275
|
+
`${markupTitle}${markupBackground}${markupAxis}${markupPath}${markupDot}</svg>`;
|
|
276
|
+
}
|