@casoon/chartlet 0.1.0-alpha.7 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ The package carries the renderer compiled to WebAssembly, so it is all you insta
7
7
  Node.js 22.12 or newer.
8
8
 
9
9
  ```sh
10
- npm install @casoon/chartlet@alpha
10
+ npm install @casoon/chartlet
11
11
  ```
12
12
 
13
13
  ```astro
@@ -35,7 +35,8 @@ const { content, warnings } = renderChart(spec, { format: 'svg', idPrefix: 'reve
35
35
  ```
36
36
 
37
37
  Options: `format`, `table`, `idPrefix`, `variant` (`mobile` renders the mobile variant alone as
38
- SVG), `strict` and `manifest` (`true` adds a provenance `manifest` to the result: chartlet
38
+ SVG, `print` the chart as SVG with literal colors for PDF and print renderers, `social` the chart
39
+ on a 1200 × 630 canvas for Open Graph images), `strict` and `manifest` (`true` adds a provenance `manifest` to the result: chartlet
39
40
  version, SHA-256 of the canonical specification and of `content`, format, variant, ID prefix and
40
41
  warnings, without a timestamp). `warnings` holds the lines the CLI would write; an invalid specification
41
42
  throws with the CLI's message. The output is byte-identical to the `chartlet` CLI.
@@ -64,6 +65,22 @@ Astro takes the hashes without quotes: per page through
64
65
  `Astro.csp?.insertStyleHash(hash.slice(1, -1))`, or for all pages in
65
66
  `security.csp.styleDirective.hashes`. `createRenderer` returns the same field.
66
67
 
68
+ ## Interactive module
69
+
70
+ `@casoon/chartlet/interactive` is an optional browser module without dependencies for charts
71
+ rendered with `hooks: true`: crosshair with values (pointer and keyboard), series toggles, scroll
72
+ stations and playback. Import only the features a page uses:
73
+
74
+ ```js
75
+ import { enhance, crosshair, toggle } from '@casoon/chartlet/interactive';
76
+
77
+ enhance(document.querySelector('figure.chartlet-figure'), { crosshair, toggle });
78
+ ```
79
+
80
+ It reads values from the data table and geometry from `data-*` hooks, needs no inline script and
81
+ sets styles only through the CSSOM. See
82
+ [Interaction](https://github.com/casoon/chartlet/blob/main/docs/guides/interaction.md#optional-javascript).
83
+
67
84
  ## Cloudflare Workers and Vite
68
85
 
69
86
  Runtimes that cannot compile WebAssembly from bytes, such as workerd, import the module and pass
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casoon/chartlet",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0",
4
4
  "description": "Build-time SVG and HTML charts for static websites",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,6 +24,11 @@
24
24
  "import": "./src/wasm.mjs"
25
25
  },
26
26
  "./chartlet.wasm": "./src/chartlet.wasm",
27
+ "./chartlet.css": "./src/chartlet.css",
28
+ "./interactive": {
29
+ "types": "./src/interactive.d.mts",
30
+ "import": "./src/interactive.mjs"
31
+ },
27
32
  "./astro": "./src/Chart.astro"
28
33
  },
29
34
  "peerDependencies": {
package/src/Chart.astro CHANGED
@@ -7,6 +7,10 @@ export interface Props {
7
7
  format?: 'svg' | 'html';
8
8
  table?: 'details' | 'visible';
9
9
  strict?: boolean;
10
+ allowWarnings?: string[];
11
+ styles?: 'inline' | 'external';
12
+ /** Add the `data-*` hooks for `@casoon/chartlet/interactive`. */
13
+ hooks?: boolean;
10
14
  binary?: string;
11
15
  }
12
16
 
@@ -16,6 +20,9 @@ const {
16
20
  format = 'html',
17
21
  table = 'details',
18
22
  strict = false,
23
+ allowWarnings,
24
+ styles,
25
+ hooks = false,
19
26
  binary,
20
27
  } = Astro.props;
21
28
 
@@ -27,6 +34,9 @@ const rendered = renderChart(spec, {
27
34
  format,
28
35
  table,
29
36
  strict,
37
+ allowWarnings,
38
+ styles,
39
+ hooks,
30
40
  binary,
31
41
  idPrefix: id,
32
42
  });
@@ -0,0 +1 @@
1
+ .chartlet-root{--chartlet-text:#172033;--chartlet-muted:#344054;--chartlet-grid:#d9dee8;--chartlet-zero:#667085;--chartlet-accent:#2563eb;--chartlet-background:#fff;--chartlet-color-1:#2563eb;--chartlet-color-2:#c2410c;--chartlet-color-3:#475569;--chartlet-color-4:#111827;max-width:100%;height:auto;font-family:Inter,ui-sans-serif,system-ui,sans-serif;color:var(--chartlet-text)}.chartlet-root .chartlet-title{font-size:22px;font-weight:650;fill:var(--chartlet-text)}.chartlet-root .chartlet-label,.chartlet-root .chartlet-tick,.chartlet-root .chartlet-value,.chartlet-root .chartlet-value-inverse,.chartlet-root .chartlet-axis-title{font-size:12px;fill:var(--chartlet-muted)}.chartlet-root .chartlet-value,.chartlet-root .chartlet-value-inverse{font-weight:600}.chartlet-root .chartlet-value{fill:var(--chartlet-text)}.chartlet-root .chartlet-value-inverse{fill:var(--chartlet-background)}.chartlet-root .chartlet-axis-title{font-weight:600}.chartlet-root .chartlet-grid{stroke:var(--chartlet-grid);stroke-width:1}.chartlet-root .chartlet-zero{stroke:var(--chartlet-zero);stroke-width:1.5}.chartlet-root .chartlet-bar,.chartlet-root .chartlet-point{fill:var(--chartlet-accent)}.chartlet-root .chartlet-line{fill:none;stroke:var(--chartlet-accent);stroke-width:3;stroke-linecap:round;stroke-linejoin:round}.chartlet-root .chartlet-background{fill:var(--chartlet-background)}.chartlet-root.chartlet-theme-dark{--chartlet-text:#e8edf6;--chartlet-muted:#a9b4c7;--chartlet-grid:#2a3342;--chartlet-zero:#7b8697;--chartlet-accent:#7ea6ff;--chartlet-background:#0e131c;--chartlet-color-1:#7ea6ff;--chartlet-color-2:#ff9c72;--chartlet-color-3:#9aa7bd;--chartlet-color-4:#e2e8f4}.chartlet-type-bar .chartlet-legend{font-size:12px;fill:var(--chartlet-muted)}.chartlet-type-bar .chartlet-series-1{fill:var(--chartlet-color-1)}.chartlet-type-bar .chartlet-series-2{fill:var(--chartlet-color-2)}.chartlet-type-bar .chartlet-series-3{fill:var(--chartlet-color-3)}.chartlet-type-bar .chartlet-series-4{fill:var(--chartlet-color-4)}.chartlet-wrapper{display:inline-block;max-width:100%}.chartlet-filter{border:none;padding:0;margin:0 0 12px 0}.chartlet-filter legend{font-size:14px;font-weight:650;margin-bottom:4px}.chartlet-filter label{display:inline-flex;align-items:center;min-height:44px;font-size:13px;margin-right:14px;cursor:pointer;white-space:nowrap}.chartlet-filter input{margin-right:4px}.chartlet-filter input:focus-visible{outline:2px solid #2563eb;outline-offset:2px}.chartlet-wrapper:has(.chartlet-filter input.series-0:not(:checked)) .chartlet-root [data-series="0"]{display:none}.chartlet-wrapper:has(.chartlet-filter input.series-1:not(:checked)) .chartlet-root [data-series="1"]{display:none}.chartlet-wrapper:has(.chartlet-filter input.series-2:not(:checked)) .chartlet-root [data-series="2"]{display:none}.chartlet-wrapper:has(.chartlet-filter input.series-3:not(:checked)) .chartlet-root [data-series="3"]{display:none}.chartlet-type-line .chartlet-legend{font-size:12px;fill:var(--chartlet-muted)}.chartlet-type-line .chartlet-line-series-1{stroke:var(--chartlet-color-1)}.chartlet-type-line .chartlet-line-series-2{stroke:var(--chartlet-color-2)}.chartlet-type-line .chartlet-line-series-3{stroke:var(--chartlet-color-3)}.chartlet-type-line .chartlet-line-series-4{stroke:var(--chartlet-color-4)}.chartlet-type-line .chartlet-hit{fill:transparent;stroke:none}.chartlet-type-time .chartlet-legend{font-size:12px;fill:var(--chartlet-muted)}.chartlet-type-time .chartlet-line-series-1{stroke:var(--chartlet-color-1)}.chartlet-type-time .chartlet-line-series-2{stroke:var(--chartlet-color-2)}.chartlet-type-time .chartlet-line-series-3{stroke:var(--chartlet-color-3)}.chartlet-type-time .chartlet-line-series-4{stroke:var(--chartlet-color-4)}.chartlet-type-time .chartlet-hit{fill:transparent;stroke:none}.chartlet-type-multiples .chartlet-legend{font-size:12px;fill:var(--chartlet-muted)}.chartlet-type-multiples .chartlet-line-series-1{stroke:var(--chartlet-color-1)}.chartlet-type-multiples .chartlet-line-series-2{stroke:var(--chartlet-color-2)}.chartlet-type-multiples .chartlet-line-series-3{stroke:var(--chartlet-color-3)}.chartlet-type-multiples .chartlet-line-series-4{stroke:var(--chartlet-color-4)}.chartlet-type-multiples .chartlet-hit{fill:transparent;stroke:none}.chartlet-type-line .chartlet-band{stroke:none;fill-opacity:.18}.chartlet-type-line .chartlet-band-series-1{fill:var(--chartlet-color-1)}.chartlet-type-line .chartlet-band-series-2{fill:var(--chartlet-color-2)}.chartlet-type-line .chartlet-band-series-3{fill:var(--chartlet-color-3)}.chartlet-type-line .chartlet-band-series-4{fill:var(--chartlet-color-4)}.chartlet-type-line .chartlet-hatch{stroke:none}.chartlet-type-line .chartlet-hatch-line{stroke-width:1.2;opacity:.75}.chartlet-type-line .chartlet-line-modeled{stroke-dasharray:7 5}.chartlet-type-line .chartlet-line-thin{stroke-width:1}.chartlet-type-line .chartlet-point-series-2{fill:var(--chartlet-color-2)}.chartlet-type-line .chartlet-point-series-3{fill:var(--chartlet-color-3)}.chartlet-type-line .chartlet-point-series-4{fill:var(--chartlet-color-4)}.chartlet-type-line .chartlet-rule{fill:none;stroke:var(--chartlet-zero);stroke-width:1.5;stroke-dasharray:5 4}.chartlet-type-line .chartlet-rule-label{font-size:12px;font-weight:600;fill:var(--chartlet-text);paint-order:stroke;stroke:var(--chartlet-background);stroke-width:3px;stroke-linejoin:round}.chartlet-type-time .chartlet-band{stroke:none;fill-opacity:.18}.chartlet-type-time .chartlet-band-series-1{fill:var(--chartlet-color-1)}.chartlet-type-time .chartlet-band-series-2{fill:var(--chartlet-color-2)}.chartlet-type-time .chartlet-band-series-3{fill:var(--chartlet-color-3)}.chartlet-type-time .chartlet-band-series-4{fill:var(--chartlet-color-4)}.chartlet-type-time .chartlet-hatch{stroke:none}.chartlet-type-time .chartlet-hatch-line{stroke-width:1.2;opacity:.75}.chartlet-type-time .chartlet-line-modeled{stroke-dasharray:7 5}.chartlet-type-time .chartlet-line-thin{stroke-width:1}.chartlet-type-time .chartlet-point-series-2{fill:var(--chartlet-color-2)}.chartlet-type-time .chartlet-point-series-3{fill:var(--chartlet-color-3)}.chartlet-type-time .chartlet-point-series-4{fill:var(--chartlet-color-4)}.chartlet-type-time .chartlet-rule{fill:none;stroke:var(--chartlet-zero);stroke-width:1.5;stroke-dasharray:5 4}.chartlet-type-time .chartlet-rule-label{font-size:12px;font-weight:600;fill:var(--chartlet-text);paint-order:stroke;stroke:var(--chartlet-background);stroke-width:3px;stroke-linejoin:round}.chartlet-type-multiples .chartlet-band{stroke:none;fill-opacity:.18}.chartlet-type-multiples .chartlet-band-series-1{fill:var(--chartlet-color-1)}.chartlet-type-multiples .chartlet-band-series-2{fill:var(--chartlet-color-2)}.chartlet-type-multiples .chartlet-band-series-3{fill:var(--chartlet-color-3)}.chartlet-type-multiples .chartlet-band-series-4{fill:var(--chartlet-color-4)}.chartlet-type-multiples .chartlet-hatch{stroke:none}.chartlet-type-multiples .chartlet-hatch-line{stroke-width:1.2;opacity:.75}.chartlet-type-multiples .chartlet-line-modeled{stroke-dasharray:7 5}.chartlet-type-multiples .chartlet-line-thin{stroke-width:1}.chartlet-type-multiples .chartlet-point-series-2{fill:var(--chartlet-color-2)}.chartlet-type-multiples .chartlet-point-series-3{fill:var(--chartlet-color-3)}.chartlet-type-multiples .chartlet-point-series-4{fill:var(--chartlet-color-4)}.chartlet-type-multiples .chartlet-rule{fill:none;stroke:var(--chartlet-zero);stroke-width:1.5;stroke-dasharray:5 4}.chartlet-type-multiples .chartlet-rule-label{font-size:12px;font-weight:600;fill:var(--chartlet-text);paint-order:stroke;stroke:var(--chartlet-background);stroke-width:3px;stroke-linejoin:round}.chartlet-type-line .chartlet-area{stroke:none;fill-opacity:.18}.chartlet-type-line .chartlet-line-dashed{stroke-dasharray:7 5}.chartlet-type-line .chartlet-line-dotted{stroke-dasharray:0 7}.chartlet-type-line .chartlet-line-thin.chartlet-line-dotted{stroke-dasharray:1 3}.chartlet-type-line .chartlet-line-bold{stroke-width:4.5}.chartlet-type-line.chartlet-multiples .chartlet-line-bold{stroke-width:3}.chartlet-type-time .chartlet-area{stroke:none;fill-opacity:.18}.chartlet-type-time .chartlet-line-dashed{stroke-dasharray:7 5}.chartlet-type-time .chartlet-line-dotted{stroke-dasharray:0 7}.chartlet-type-time .chartlet-line-thin.chartlet-line-dotted{stroke-dasharray:1 3}.chartlet-type-time .chartlet-line-bold{stroke-width:4.5}.chartlet-type-time.chartlet-multiples .chartlet-line-bold{stroke-width:3}.chartlet-type-multiples .chartlet-area{stroke:none;fill-opacity:.18}.chartlet-type-multiples .chartlet-line-dashed{stroke-dasharray:7 5}.chartlet-type-multiples .chartlet-line-dotted{stroke-dasharray:0 7}.chartlet-type-multiples .chartlet-line-thin.chartlet-line-dotted{stroke-dasharray:1 3}.chartlet-type-multiples .chartlet-line-bold{stroke-width:4.5}.chartlet-type-multiples.chartlet-multiples .chartlet-line-bold{stroke-width:3}.chartlet-type-time .chartlet-zone{fill:var(--chartlet-zero);fill-opacity:.14;stroke:none}.chartlet-type-time .chartlet-marker{fill:var(--chartlet-text);stroke:var(--chartlet-background);stroke-width:1.5;stroke-linejoin:round}.chartlet-type-multiples .chartlet-zone{fill:var(--chartlet-zero);fill-opacity:.14;stroke:none}.chartlet-type-multiples .chartlet-marker{fill:var(--chartlet-text);stroke:var(--chartlet-background);stroke-width:1.5;stroke-linejoin:round}.chartlet-type-multiples.chartlet-multiples .chartlet-line{stroke-width:2}.chartlet-type-multiples .chartlet-panel-title{font-size:13px;font-weight:650;fill:var(--chartlet-text)}.chartlet-root{--chartlet-diverging-0:#033761;--chartlet-diverging-1:#064f89;--chartlet-diverging-2:#0f66ac;--chartlet-diverging-3:#347ec4;--chartlet-diverging-4:#5b97d3;--chartlet-diverging-5:#81afdf;--chartlet-diverging-6:#a7c8ea;--chartlet-diverging-7:#cde0f5;--chartlet-diverging-8:#eeeeee;--chartlet-diverging-9:#f8d5d0;--chartlet-diverging-10:#f1b2aa;--chartlet-diverging-11:#e88f85;--chartlet-diverging-12:#dd6b60;--chartlet-diverging-13:#cd443d;--chartlet-diverging-14:#b32322;--chartlet-diverging-15:#901114;--chartlet-diverging-16:#690509}.chartlet-type-stripes .chartlet-diverging-0{fill:var(--chartlet-diverging-0)}.chartlet-type-stripes .chartlet-diverging-1{fill:var(--chartlet-diverging-1)}.chartlet-type-stripes .chartlet-diverging-2{fill:var(--chartlet-diverging-2)}.chartlet-type-stripes .chartlet-diverging-3{fill:var(--chartlet-diverging-3)}.chartlet-type-stripes .chartlet-diverging-4{fill:var(--chartlet-diverging-4)}.chartlet-type-stripes .chartlet-diverging-5{fill:var(--chartlet-diverging-5)}.chartlet-type-stripes .chartlet-diverging-6{fill:var(--chartlet-diverging-6)}.chartlet-type-stripes .chartlet-diverging-7{fill:var(--chartlet-diverging-7)}.chartlet-type-stripes .chartlet-diverging-8{fill:var(--chartlet-diverging-8)}.chartlet-type-stripes .chartlet-diverging-9{fill:var(--chartlet-diverging-9)}.chartlet-type-stripes .chartlet-diverging-10{fill:var(--chartlet-diverging-10)}.chartlet-type-stripes .chartlet-diverging-11{fill:var(--chartlet-diverging-11)}.chartlet-type-stripes .chartlet-diverging-12{fill:var(--chartlet-diverging-12)}.chartlet-type-stripes .chartlet-diverging-13{fill:var(--chartlet-diverging-13)}.chartlet-type-stripes .chartlet-diverging-14{fill:var(--chartlet-diverging-14)}.chartlet-type-stripes .chartlet-diverging-15{fill:var(--chartlet-diverging-15)}.chartlet-type-stripes .chartlet-diverging-16{fill:var(--chartlet-diverging-16)}.chartlet-root{--chartlet-diverging-0:#033761;--chartlet-diverging-1:#064f89;--chartlet-diverging-2:#0f66ac;--chartlet-diverging-3:#347ec4;--chartlet-diverging-4:#5b97d3;--chartlet-diverging-5:#81afdf;--chartlet-diverging-6:#a7c8ea;--chartlet-diverging-7:#cde0f5;--chartlet-diverging-8:#eeeeee;--chartlet-diverging-9:#f8d5d0;--chartlet-diverging-10:#f1b2aa;--chartlet-diverging-11:#e88f85;--chartlet-diverging-12:#dd6b60;--chartlet-diverging-13:#cd443d;--chartlet-diverging-14:#b32322;--chartlet-diverging-15:#901114;--chartlet-diverging-16:#690509}.chartlet-type-calendar .chartlet-diverging-0{fill:var(--chartlet-diverging-0)}.chartlet-type-calendar .chartlet-diverging-1{fill:var(--chartlet-diverging-1)}.chartlet-type-calendar .chartlet-diverging-2{fill:var(--chartlet-diverging-2)}.chartlet-type-calendar .chartlet-diverging-3{fill:var(--chartlet-diverging-3)}.chartlet-type-calendar .chartlet-diverging-4{fill:var(--chartlet-diverging-4)}.chartlet-type-calendar .chartlet-diverging-5{fill:var(--chartlet-diverging-5)}.chartlet-type-calendar .chartlet-diverging-6{fill:var(--chartlet-diverging-6)}.chartlet-type-calendar .chartlet-diverging-7{fill:var(--chartlet-diverging-7)}.chartlet-type-calendar .chartlet-diverging-8{fill:var(--chartlet-diverging-8)}.chartlet-type-calendar .chartlet-diverging-9{fill:var(--chartlet-diverging-9)}.chartlet-type-calendar .chartlet-diverging-10{fill:var(--chartlet-diverging-10)}.chartlet-type-calendar .chartlet-diverging-11{fill:var(--chartlet-diverging-11)}.chartlet-type-calendar .chartlet-diverging-12{fill:var(--chartlet-diverging-12)}.chartlet-type-calendar .chartlet-diverging-13{fill:var(--chartlet-diverging-13)}.chartlet-type-calendar .chartlet-diverging-14{fill:var(--chartlet-diverging-14)}.chartlet-type-calendar .chartlet-diverging-15{fill:var(--chartlet-diverging-15)}.chartlet-type-calendar .chartlet-diverging-16{fill:var(--chartlet-diverging-16)}.chartlet-type-calendar .chartlet-calendar-empty{fill:none;stroke:var(--chartlet-grid);stroke-width:1}.chartlet-type-rangebar .chartlet-range{fill:var(--chartlet-accent);fill-opacity:.3;stroke:var(--chartlet-accent);stroke-width:1}.chartlet-type-rangebar .chartlet-range-hatch{stroke:none}.chartlet-type-rangebar .chartlet-hatch-line{stroke:var(--chartlet-accent);stroke-width:1.2;opacity:.75}.chartlet-type-rangebar .chartlet-range-mid{stroke:var(--chartlet-text);stroke-width:3}.chartlet-type-rangebar .chartlet-legend{font-size:12px;fill:var(--chartlet-muted)}.chartlet-type-bar .chartlet-rule{fill:none;stroke:var(--chartlet-zero);stroke-width:1.5;stroke-dasharray:5 4}.chartlet-type-bar .chartlet-rule-label{font-size:12px;font-weight:600;fill:var(--chartlet-text);paint-order:stroke;stroke:var(--chartlet-background);stroke-width:3px;stroke-linejoin:round}.chartlet-type-bar .chartlet-outline{fill:var(--chartlet-background);stroke-width:2}.chartlet-type-bar .chartlet-series-2.chartlet-outline{stroke:var(--chartlet-color-2)}.chartlet-type-bar .chartlet-series-4.chartlet-outline{stroke:var(--chartlet-color-4)}.chartlet-root{--chartlet-sea:#f2efe8;--chartlet-quiet:#fff}.chartlet-root.chartlet-theme-dark{--chartlet-sea:#131a24;--chartlet-quiet:#1e2836}.chartlet-type-topicmap .chartlet-sea{fill:var(--chartlet-sea)}.chartlet-type-topicmap .chartlet-graticule{stroke:var(--chartlet-grid);stroke-width:1;opacity:.7}.chartlet-type-topicmap .chartlet-compass-ring{fill:var(--chartlet-background);stroke:var(--chartlet-grid);stroke-width:1}.chartlet-type-topicmap .chartlet-compass-needle{fill:var(--chartlet-muted);opacity:.55}.chartlet-type-topicmap .chartlet-compass-north{fill:var(--chartlet-accent)}.chartlet-type-topicmap .chartlet-compass-label{font-size:11px;font-weight:650;fill:var(--chartlet-muted)}.chartlet-type-topicmap .chartlet-cartouche{fill:var(--chartlet-background);stroke:var(--chartlet-grid);stroke-width:1}.chartlet-type-topicmap .chartlet-cartouche-frame{fill:none;stroke:var(--chartlet-grid);stroke-width:1}.chartlet-type-topicmap .chartlet-cartouche-heading{font-weight:650;fill:var(--chartlet-text)}.chartlet-type-topicmap .chartlet-cartouche-meta{fill:var(--chartlet-muted)}.chartlet-type-topicmap .chartlet-topic-area{fill:var(--chartlet-accent)}.chartlet-type-topicmap .chartlet-topic-halo{fill:none;stroke:var(--chartlet-accent);stroke-width:10;stroke-linejoin:round;opacity:.16}.chartlet-type-topicmap .chartlet-topic-band{fill:none;stroke:var(--chartlet-grid);stroke-width:1;stroke-dasharray:3 6;stroke-linejoin:round}.chartlet-type-topicmap .chartlet-topic-link{fill:none;stroke:var(--chartlet-grid);stroke-width:1.5;stroke-dasharray:4 5;stroke-linecap:round}.chartlet-type-topicmap .chartlet-topic-leader{stroke:var(--chartlet-zero);stroke-width:1}.chartlet-type-topicmap .chartlet-topic-point{fill:var(--chartlet-background);opacity:.6}.chartlet-type-topicmap .chartlet-topic-label{font-weight:650;fill:var(--chartlet-background)}.chartlet-type-topicmap .chartlet-topic-value{fill:var(--chartlet-background)}.chartlet-type-topicmap .chartlet-topic-outside{font-weight:650;fill:var(--chartlet-text)}.chartlet-type-topicmap .chartlet-topic-outside-value{fill:var(--chartlet-muted)}.chartlet-root{--chartlet-sea:#f2efe8;--chartlet-quiet:#fff}.chartlet-type-atlas .chartlet-sea{fill:var(--chartlet-sea)}.chartlet-root.chartlet-theme-dark{--chartlet-sea:#131a24;--chartlet-quiet:#1e2836}.chartlet-type-atlas [class^='chartlet-atlas-realm-']{fill:var(--chartlet-quiet);stroke:var(--chartlet-grid);stroke-width:1.2;stroke-linejoin:round}.chartlet-type-atlas .chartlet-atlas-realm-1{opacity:.94}.chartlet-type-atlas .chartlet-atlas-realm-2{opacity:.88}.chartlet-type-atlas .chartlet-atlas-realm-3{opacity:.82}.chartlet-type-atlas .chartlet-atlas-realm-4{opacity:.76}.chartlet-type-atlas .chartlet-atlas-realm-5{opacity:.7}.chartlet-type-atlas .chartlet-atlas-realm-6{opacity:.64}.chartlet-type-atlas .chartlet-atlas-realm-7{opacity:.58}.chartlet-type-atlas .chartlet-atlas-place{fill:var(--chartlet-text);opacity:.5}.chartlet-type-atlas .chartlet-atlas-contour{fill:none;stroke:var(--chartlet-grid);stroke-width:.55;stroke-linejoin:round;opacity:.5}.chartlet-type-atlas .chartlet-atlas-region{fill:none;stroke:var(--chartlet-grid);stroke-width:.8;stroke-linejoin:round;opacity:.75}.chartlet-type-atlas .chartlet-atlas-coast{fill:none;stroke:var(--chartlet-accent);stroke-width:1.6;stroke-linejoin:round;opacity:.55}.chartlet-type-atlas .chartlet-atlas-label{font-weight:650;fill:var(--chartlet-text)}.chartlet-type-atlas .chartlet-atlas-realm-label{font-weight:650;fill:var(--chartlet-muted);letter-spacing:.08em;opacity:.55}.chartlet-root{--chartlet-rise:#0a4f49;--chartlet-fall:#d03a0f}.chartlet-root.chartlet-theme-dark{--chartlet-rise:#99f6e4;--chartlet-fall:#e5484d}.chartlet-type-time .chartlet-wick{stroke-width:1.5}.chartlet-type-time .chartlet-wick-rise{stroke:var(--chartlet-rise)}.chartlet-type-time .chartlet-wick-fall{stroke:var(--chartlet-fall)}.chartlet-type-time .chartlet-candle{stroke-width:1.5}.chartlet-type-time .chartlet-candle-rise{fill:var(--chartlet-background);stroke:var(--chartlet-rise)}.chartlet-type-time .chartlet-candle-fall{fill:var(--chartlet-fall);stroke:var(--chartlet-fall)}
package/src/chartlet.wasm CHANGED
Binary file
@@ -0,0 +1,94 @@
1
+ /** A pane's plot as its hook describes it: `[domain, range]` per axis. */
2
+ export interface ChartPlot {
3
+ pane: number;
4
+ x: [number[], number[]];
5
+ y: [number[], number[]];
6
+ }
7
+
8
+ /** A value column of the data table. */
9
+ export interface ChartColumn {
10
+ name: string;
11
+ /** The series: its index among the data layers, or among the series of a category chart. */
12
+ series: number;
13
+ pane: number;
14
+ part: "value" | "lower" | "upper" | "open" | "high" | "low" | "close";
15
+ }
16
+
17
+ /** A row of the data table. */
18
+ export interface ChartRow {
19
+ /** Unix seconds on a time axis, the row index otherwise. */
20
+ x: number;
21
+ label: string;
22
+ /** Each value as the chart writes it. */
23
+ text: string[];
24
+ /** Each value unformatted; `null` where it is missing. */
25
+ value: (number | null)[];
26
+ }
27
+
28
+ /** What a chart rendered with `hooks: true` holds, as `readChart` reads it. */
29
+ export interface Chart {
30
+ root: Element;
31
+ /** The ID prefix the chart was rendered with. */
32
+ id: string | undefined;
33
+ svgs: SVGSVGElement[];
34
+ table: HTMLTableElement | null;
35
+ columns: ChartColumn[];
36
+ rows: ChartRow[];
37
+ plots: Map<SVGSVGElement, ChartPlot[]>;
38
+ /** Series switched off, by `ChartColumn.series`. */
39
+ hidden: Set<number>;
40
+ /** Registers a listener for `changed()`. */
41
+ on(listener: () => void): void;
42
+ /** Tells every feature that the chart's state changed, such as a series switched off. */
43
+ changed(): void;
44
+ }
45
+
46
+ /** A feature: enhances the chart and returns what undoes it. */
47
+ export type ChartFeature = (chart: Chart) => (() => void) | undefined | void;
48
+
49
+ /** Maps `value` from `domain` onto `range`, piecewise linear between neighbouring pairs. */
50
+ export declare function toPixel(domain: number[], range: number[], value: number): number;
51
+ /** The inverse of `toPixel`: the value at `pixel`. */
52
+ export declare function toValue(domain: number[], range: number[], pixel: number): number;
53
+
54
+ /** Reads a chart rendered with `hooks: true` from its figure, its SVG or an element around either. */
55
+ export declare function readChart(root: Element): Chart;
56
+
57
+ /**
58
+ * Enhances the chart in `root` (its figure, its SVG, or an element around either) with the
59
+ * features passed in, e.g. `enhance(figure, { crosshair, toggle })`. Give a feature options with
60
+ * a function: `{ play: (chart) => play(chart, { interval: 400 }) }`.
61
+ */
62
+ export declare function enhance(
63
+ root: Element,
64
+ features?: Partial<Record<"crosshair" | "toggle" | "steps" | "play", ChartFeature>>,
65
+ ): { chart: Chart; destroy(): void };
66
+
67
+ /** A vertical rule with the values of one observation, by pointer and keyboard. */
68
+ export declare function crosshair(chart: Chart): () => void;
69
+
70
+ export interface ToggleOptions {
71
+ /** The legend of the checkbox group; `"Series"` by default. */
72
+ legend?: string;
73
+ }
74
+ /** One checkbox per named series of a time chart or small multiples. */
75
+ export declare function toggle(chart: Chart, options?: ToggleOptions): (() => void) | undefined;
76
+
77
+ /** Shows only the data between `from` and `to` (axis values), or everything without arguments. */
78
+ export declare function reveal(chart: Chart, from?: number | null, to?: number | null): void;
79
+
80
+ export interface StepsOptions {
81
+ /** The stations on the page; `[data-chartlet-step]` by default. */
82
+ selector?: string;
83
+ }
84
+ /** Scroll stations that set the chart to the state they describe. */
85
+ export declare function steps(chart: Chart, options?: StepsOptions): (() => void) | undefined;
86
+
87
+ export interface PlayOptions {
88
+ /** Milliseconds per observation; by default the whole chart plays in about six seconds. */
89
+ interval?: number;
90
+ /** Button and group labels, for charts in other languages. */
91
+ labels?: Partial<Record<"group" | "play" | "pause" | "back" | "forward" | "all", string>>;
92
+ }
93
+ /** Reveals the data one observation at a time, with pause, steps and a way to show all. */
94
+ export declare function play(chart: Chart, options?: PlayOptions): (() => void) | undefined;
@@ -0,0 +1,440 @@
1
+ // The optional interactive layer for charts rendered with `hooks: true`. It reads what the static
2
+ // output already holds — the plot geometry from the `data-*` hooks, the values from the data
3
+ // table or, in the SVG profile, from the JSON data block — and never lays anything out again.
4
+ // No dependencies, no inline script, no `eval`; styles are set through the CSSOM only.
5
+
6
+ const SVG = "http://www.w3.org/2000/svg";
7
+ const numbers = (text) => (text ?? "").trim().split(/\s+/).filter(Boolean).map(Number);
8
+
9
+ // Maps `value` from `domain` onto `range`, linear between neighbouring pairs and beyond the ends.
10
+ // Both lists have the same length; `domain` ascends.
11
+ export function toPixel(domain, range, value) {
12
+ return interpolate(domain, range, value);
13
+ }
14
+
15
+ // The inverse of `toPixel`: the value at `pixel`. `range` may ascend or descend.
16
+ export function toValue(domain, range, pixel) {
17
+ return interpolate(range, domain, pixel);
18
+ }
19
+
20
+ function interpolate(from, to, value) {
21
+ const last = from.length - 1;
22
+ if (last < 1) return to[0];
23
+ const direction = Math.sign(from[last] - from[0]) || 1;
24
+ let index = 1;
25
+ while (index < last && (value - from[index]) * direction > 0) index++;
26
+ const [a, b] = [from[index - 1], from[index]];
27
+ return to[index - 1] + (b === a ? 0 : ((value - a) / (b - a)) * (to[index] - to[index - 1]));
28
+ }
29
+
30
+ // What a chart holds: its SVGs with their plots, and the data table as columns and rows.
31
+ export function readChart(root) {
32
+ const svgs = root.matches?.("svg[data-chartlet-type]")
33
+ ? [root]
34
+ : [...root.querySelectorAll("svg[data-chartlet-type]")];
35
+ const table = root.querySelector?.("table[data-chartlet-table]");
36
+ let columns;
37
+ let rows;
38
+ if (table) {
39
+ columns = [...table.tHead.rows[0].cells].slice(1).map((cell) => ({
40
+ name: cell.textContent.trim(),
41
+ series: Number(cell.dataset.series),
42
+ pane: Number(cell.dataset.pane),
43
+ part: cell.dataset.part,
44
+ }));
45
+ rows = [...table.tBodies[0].rows].map((row) => {
46
+ const cells = [...row.cells].slice(1);
47
+ return {
48
+ x: Number(row.dataset.x),
49
+ label: row.cells[0].textContent.trim(),
50
+ text: cells.map((cell) => cell.textContent.trim()),
51
+ value: cells.map((cell) => (cell.dataset.value == null ? null : Number(cell.dataset.value))),
52
+ };
53
+ });
54
+ } else {
55
+ const block = svgs[0]?.querySelector("script[data-chartlet-data]");
56
+ ({ columns, rows } = block ? JSON.parse(block.textContent) : { columns: [], rows: [] });
57
+ }
58
+ const plots = new Map(
59
+ svgs.map((svg) => [
60
+ svg,
61
+ [...svg.querySelectorAll("[data-chartlet-plot]")].map((plot) => {
62
+ // A logarithmic value axis is linear in the logarithm of its values.
63
+ const log = plot.dataset.yScale === "log";
64
+ const yDomain = numbers(plot.dataset.yDomain);
65
+ return {
66
+ pane: Number(plot.dataset.pane),
67
+ x: [numbers(plot.dataset.xDomain), numbers(plot.dataset.xRange)],
68
+ y: [log ? yDomain.map(Math.log10) : yDomain, numbers(plot.dataset.yRange)],
69
+ log,
70
+ };
71
+ }),
72
+ ]),
73
+ );
74
+ const listeners = [];
75
+ return {
76
+ root,
77
+ id: table?.dataset.chartletTable ?? svgs[0]?.dataset.chartletId,
78
+ svgs,
79
+ table,
80
+ columns,
81
+ rows,
82
+ plots,
83
+ // The language of the chart's texts, for the controls this module adds.
84
+ words: WORDS[svgs[0]?.dataset.chartletLocale] ?? WORDS.en,
85
+ // Series switched off, by their index among the data layers.
86
+ hidden: new Set(),
87
+ on: (listener) => listeners.push(listener),
88
+ changed: () => listeners.forEach((listener) => listener()),
89
+ };
90
+ }
91
+
92
+ // Enhances the chart in `root` — its figure, its SVG, or an element around either — with the
93
+ // features passed in, such as `{ crosshair, toggle }`. A feature is a function of the chart; pass
94
+ // `(chart) => play(chart, { interval: 400 })` to give it options. Returns `destroy()`.
95
+ export function enhance(root, features = {}) {
96
+ const chart = readChart(root);
97
+ const cleanups = Object.values(features)
98
+ .filter((feature) => typeof feature === "function")
99
+ .map((feature) => feature(chart));
100
+ return {
101
+ chart,
102
+ destroy: () => cleanups.forEach((cleanup) => cleanup?.()),
103
+ };
104
+ }
105
+
106
+ // The rows a plot shows: a zoom step covers only part of the table.
107
+ function visibleRows(chart, plot) {
108
+ const [domain] = plot.x;
109
+ const [low, high] = [domain[0], domain[domain.length - 1]];
110
+ return chart.rows.map((_, index) => index).filter((index) => {
111
+ const { x } = chart.rows[index];
112
+ return x >= low && x <= high;
113
+ });
114
+ }
115
+
116
+ function element(name, attributes = {}, namespace) {
117
+ const node = namespace ? document.createElementNS(namespace, name) : document.createElement(name);
118
+ for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value);
119
+ return node;
120
+ }
121
+
122
+ // Where an SVG's user units lie on the screen.
123
+ function screenScale(svg) {
124
+ const box = svg.getBoundingClientRect();
125
+ return { box, scale: box.width / svg.viewBox.baseVal.width };
126
+ }
127
+
128
+ // A vertical rule and the values of one observation, by pointer and keyboard, synchronized over
129
+ // every pane. The values appear in an HTML overlay beside the chart that screen readers announce
130
+ // politely; it stays while hovered or focused and closes with Escape (WCAG 1.4.13).
131
+ export function crosshair(chart) {
132
+ const cleanups = [];
133
+ for (const svg of chart.svgs) {
134
+ const plots = chart.plots.get(svg);
135
+ if (!plots.length) continue;
136
+ const rows = visibleRows(chart, plots[0]);
137
+ const layer = svg.appendChild(
138
+ element("g", { class: "chartlet-crosshair", "aria-hidden": "true", "pointer-events": "none" }, SVG),
139
+ );
140
+ const overlay = element("div", { class: "chartlet-crosshair-value", role: "status", "aria-atomic": "true" });
141
+ Object.assign(overlay.style, {
142
+ position: "absolute",
143
+ zIndex: 1,
144
+ padding: "4px 8px",
145
+ font: "13px/1.4 system-ui, sans-serif",
146
+ background: "Canvas",
147
+ color: "CanvasText",
148
+ border: "1px solid GrayText",
149
+ borderRadius: "4px",
150
+ whiteSpace: "nowrap",
151
+ });
152
+ overlay.hidden = true;
153
+ const parent = svg.parentElement;
154
+ if (getComputedStyle(parent).position === "static") parent.style.position = "relative";
155
+ svg.after(overlay);
156
+ if (!svg.hasAttribute("tabindex")) svg.setAttribute("tabindex", "0");
157
+ svg.setAttribute("aria-keyshortcuts", "ArrowLeft ArrowRight Home End Escape");
158
+ let active = -1;
159
+ let current = plots[0];
160
+
161
+ const show = (position) => {
162
+ active = position;
163
+ layer.replaceChildren();
164
+ overlay.replaceChildren();
165
+ if (position < 0) {
166
+ overlay.hidden = true;
167
+ return;
168
+ }
169
+ const row = chart.rows[rows[position]];
170
+ const left = toPixel(...current.x, row.x);
171
+ const top = current.y[1][1];
172
+ for (const plot of plots) {
173
+ const x = toPixel(...plot.x, row.x);
174
+ const [bottom, upper] = plot.y[1];
175
+ layer.append(element("line", { x1: x, x2: x, y1: bottom, y2: upper, stroke: "currentColor", "stroke-width": 1 }, SVG));
176
+ chart.columns.forEach((column, index) => {
177
+ const value = row.value[index];
178
+ if (column.pane !== plot.pane || chart.hidden.has(column.series) || value == null) return;
179
+ if (column.part !== "value" && column.part !== "close") return;
180
+ const y = toPixel(...plot.y, plot.log ? Math.log10(value) : value);
181
+ layer.append(element("circle", { cx: x, cy: y, r: 4, fill: "Canvas", stroke: "currentColor", "stroke-width": 2 }, SVG));
182
+ });
183
+ }
184
+ const heading = element("strong");
185
+ heading.textContent = row.label;
186
+ overlay.append(heading);
187
+ // Small multiples list the panel under the pointer; a time chart's panes share one list.
188
+ const multiples = svg.dataset.chartletType === "multiples";
189
+ chart.columns.forEach((column, index) => {
190
+ if (chart.hidden.has(column.series) || (multiples && column.pane !== current.pane)) return;
191
+ const line = element("div");
192
+ line.textContent = `${column.name}: ${row.text[index]}`;
193
+ overlay.append(line);
194
+ });
195
+ overlay.hidden = false;
196
+ const { box, scale } = screenScale(svg);
197
+ const origin = parent.getBoundingClientRect();
198
+ const offset = box.left - origin.left + left * scale;
199
+ const right = left > svg.viewBox.baseVal.width / 2;
200
+ overlay.style.top = `${box.top - origin.top + top * scale}px`;
201
+ overlay.style.left = right ? "" : `${offset + 12}px`;
202
+ overlay.style.right = right ? `${origin.width - offset + 12}px` : "";
203
+ };
204
+
205
+ // The observation nearest the pointer, in the pane under it.
206
+ const onPointer = (event) => {
207
+ const { box, scale } = screenScale(svg);
208
+ const x = (event.clientX - box.left) / scale;
209
+ const y = (event.clientY - box.top) / scale;
210
+ const plot = plots.find(({ x: [, range], y: [, height] }) =>
211
+ x >= Math.min(...range) - 8 && x <= Math.max(...range) + 8 &&
212
+ y >= Math.min(...height) && y <= Math.max(...height));
213
+ if (!plot || !rows.length) return;
214
+ current = plot;
215
+ let nearest = 0;
216
+ rows.forEach((index, position) => {
217
+ const distance = (row) => Math.abs(toPixel(...plot.x, chart.rows[row].x) - x);
218
+ if (distance(index) < distance(rows[nearest])) nearest = position;
219
+ });
220
+ if (nearest !== active) show(nearest);
221
+ };
222
+ const onKey = (event) => {
223
+ const last = rows.length - 1;
224
+ const next = {
225
+ ArrowRight: active < 0 ? 0 : Math.min(active + 1, last),
226
+ ArrowLeft: active < 0 ? last : Math.max(active - 1, 0),
227
+ Home: 0,
228
+ End: last,
229
+ Escape: -1,
230
+ }[event.key];
231
+ if (next === undefined || (event.key === "Escape" && active < 0)) return;
232
+ event.preventDefault();
233
+ show(next);
234
+ };
235
+ const onLeave = (event) => {
236
+ if (!overlay.contains(event.relatedTarget) && event.relatedTarget !== svg && document.activeElement !== svg) show(-1);
237
+ };
238
+ const onEscape = (event) => event.key === "Escape" && active >= 0 && show(-1);
239
+ const listeners = [
240
+ [svg, "pointermove", onPointer],
241
+ [svg, "pointerdown", onPointer],
242
+ [svg, "keydown", onKey],
243
+ [svg, "pointerleave", onLeave],
244
+ [overlay, "pointerleave", onLeave],
245
+ [svg, "blur", () => show(-1)],
246
+ [document, "keydown", onEscape],
247
+ ];
248
+ for (const [target, type, listener] of listeners) target.addEventListener(type, listener);
249
+ chart.on(() => active >= 0 && show(active));
250
+ cleanups.push(() => {
251
+ for (const [target, type, listener] of listeners) target.removeEventListener(type, listener);
252
+ layer.remove();
253
+ overlay.remove();
254
+ });
255
+ }
256
+ return () => cleanups.forEach((cleanup) => cleanup());
257
+ }
258
+
259
+ // The controls' words in the languages chartlet writes; `labels` and `legend` options override
260
+ // them.
261
+ const WORDS = {
262
+ en: {
263
+ series: "Series",
264
+ playback: { group: "Playback", play: "Play", pause: "Pause", back: "Step back", forward: "Step forward", all: "Show all" },
265
+ },
266
+ de: {
267
+ series: "Reihen",
268
+ playback: { group: "Wiedergabe", play: "Abspielen", pause: "Pause", back: "Schritt zurück", forward: "Schritt vor", all: "Alles zeigen" },
269
+ },
270
+ };
271
+
272
+ // The groups that draw data layers, by name.
273
+ const named = (chart) => chart.svgs.flatMap((svg) => [...svg.querySelectorAll("g[data-series][data-name]")]);
274
+
275
+ // One checkbox per named series of a time chart or small multiples, the way the series filter of
276
+ // a bar chart works: switching one off hides its lines, bands and markers; the axes stay.
277
+ export function toggle(chart, { legend = chart.words.series } = {}) {
278
+ const groups = named(chart).sort((a, b) => a.dataset.series - b.dataset.series);
279
+ const names = [...new Set(groups.map((group) => group.dataset.name))];
280
+ if (names.length < 2 || chart.root.querySelector?.(".chartlet-filter")) return undefined;
281
+ const fieldset = element("fieldset", { class: "chartlet-filter" });
282
+ const caption = element("legend");
283
+ caption.textContent = legend;
284
+ fieldset.append(caption);
285
+ for (const name of names) {
286
+ const label = element("label");
287
+ const input = element("input", { type: "checkbox" });
288
+ input.checked = true;
289
+ input.addEventListener("change", () => {
290
+ for (const group of named(chart)) {
291
+ if (group.dataset.name !== name) continue;
292
+ if (input.checked) group.removeAttribute("display");
293
+ else group.setAttribute("display", "none");
294
+ chart.hidden[input.checked ? "delete" : "add"](Number(group.dataset.series));
295
+ }
296
+ chart.changed();
297
+ });
298
+ label.append(input, ` ${name}`);
299
+ fieldset.append(label);
300
+ }
301
+ const anchor = chart.root.closest?.("figure") ?? chart.root;
302
+ anchor.before(fieldset);
303
+ return () => fieldset.remove();
304
+ }
305
+
306
+ // Shows only the data between `from` and `to` (axis values; `null` for either end of the plot)
307
+ // by clipping the data layers of every pane, or shows everything again without arguments.
308
+ export function reveal(chart, from, to) {
309
+ for (const svg of chart.svgs) {
310
+ for (const plot of chart.plots.get(svg)) {
311
+ const id = `${svg.id}-reveal-${plot.pane}`;
312
+ let clip = svg.querySelector(`[id="${id}"]`);
313
+ const targets = svg.querySelector("g[data-series]")
314
+ ? svg.querySelectorAll(`g[data-series][data-pane="${plot.pane}"]`)
315
+ : svg.querySelectorAll(".chartlet-line,.chartlet-point,.chartlet-value");
316
+ if (from === undefined) {
317
+ clip?.remove();
318
+ targets.forEach((target) => target.removeAttribute("clip-path"));
319
+ continue;
320
+ }
321
+ if (!clip) {
322
+ clip = svg.appendChild(element("clipPath", { id }, SVG));
323
+ clip.append(element("rect", { y: 0, height: svg.viewBox.baseVal.height }, SVG));
324
+ }
325
+ const [domain, range] = plot.x;
326
+ const start = from == null ? 0 : toPixel(domain, range, from) - 2;
327
+ const end = to == null ? svg.viewBox.baseVal.width : toPixel(domain, range, to) + 2;
328
+ clip.firstChild.setAttribute("x", start);
329
+ clip.firstChild.setAttribute("width", Math.max(0, end - start));
330
+ targets.forEach((target) => target.setAttribute("clip-path", `url(#${id})`));
331
+ }
332
+ }
333
+ }
334
+
335
+ // A year, a date or a number, as a position on the axis: Unix seconds on a time axis.
336
+ function axisValue(chart, text) {
337
+ if (chart.svgs[0]?.dataset.chartletType !== "time" && chart.svgs[0]?.dataset.chartletType !== "multiples") {
338
+ return Number(text);
339
+ }
340
+ return /^\d{4}$/.test(text) ? Date.UTC(Number(text), 0, 1) / 1000 : Date.parse(text) / 1000;
341
+ }
342
+
343
+ // Scroll stations: elements of the page with `data-chartlet-step` (empty, or the chart's ID)
344
+ // set the chart to the state they describe once they reach the middle of the viewport —
345
+ // `data-chartlet-highlight` (a series name), `data-chartlet-annotation` (an annotation's layer
346
+ // index), `data-chartlet-range` ("from to") and `data-chartlet-zoom` (a zoom step's index or
347
+ // label). States only emphasize, hide or switch what is rendered.
348
+ export function steps(chart, { selector = "[data-chartlet-step]" } = {}) {
349
+ if (typeof IntersectionObserver === "undefined") return undefined;
350
+ const stations = [...document.querySelectorAll(selector)].filter(
351
+ (station) => !station.dataset.chartletStep || station.dataset.chartletStep === chart.id,
352
+ );
353
+ const dim = (groups, keep) =>
354
+ groups.forEach((group) => (keep(group) ? group.removeAttribute("opacity") : group.setAttribute("opacity", "0.25")));
355
+ const apply = (station) => {
356
+ const { chartletHighlight: highlight, chartletAnnotation: annotation, chartletRange: range, chartletZoom: zoom } =
357
+ station.dataset;
358
+ for (const svg of chart.svgs) {
359
+ dim([...svg.querySelectorAll("g[data-series]")], (group) => !highlight || group.dataset.name === highlight);
360
+ dim([...svg.querySelectorAll("g[data-annotation]")], (group) => !annotation || group.dataset.annotation === annotation);
361
+ }
362
+ if (range) {
363
+ const [from, to] = range.split(/\s+/).map((part) => axisValue(chart, part));
364
+ reveal(chart, from, to);
365
+ } else {
366
+ reveal(chart);
367
+ }
368
+ if (zoom != null) {
369
+ const radios = [...(chart.root.closest?.(".chartlet-wrapper") ?? chart.root).querySelectorAll(".chartlet-zoom input")];
370
+ const radio =
371
+ radios.find((input) => input.parentElement.textContent.trim() === zoom) ?? radios[Number(zoom)];
372
+ if (radio) radio.checked = true;
373
+ }
374
+ };
375
+ const observer = new IntersectionObserver(
376
+ (entries) => entries.forEach((entry) => entry.isIntersecting && apply(entry.target)),
377
+ { rootMargin: "-50% 0px -50% 0px" },
378
+ );
379
+ stations.forEach((station) => observer.observe(station));
380
+ return () => observer.disconnect();
381
+ }
382
+
383
+ // Reveals the data one observation at a time, with play and pause, a step back and forward and
384
+ // a button that shows everything again (WCAG 2.2.2). With `prefers-reduced-motion: reduce`
385
+ // there is no playback, only the step buttons.
386
+ export function play(chart, { interval, labels = {} } = {}) {
387
+ const plot = chart.plots.get(chart.svgs[0])?.[0];
388
+ if (!plot) return undefined;
389
+ const rows = visibleRows(chart, plot);
390
+ const text = { ...chart.words.playback, ...labels };
391
+ const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
392
+ const group = element("div", { class: "chartlet-play", role: "group", "aria-label": text.group });
393
+ const status = element("span", { role: "status" });
394
+ let position = -1;
395
+ let timer;
396
+ const button = (label, action) => {
397
+ const node = element("button", { type: "button" });
398
+ node.textContent = label;
399
+ node.addEventListener("click", action);
400
+ group.append(node);
401
+ return node;
402
+ };
403
+ const go = (next) => {
404
+ position = next;
405
+ if (next < 0 || next >= rows.length - 1) {
406
+ position = -1;
407
+ stop();
408
+ reveal(chart);
409
+ status.textContent = "";
410
+ return;
411
+ }
412
+ reveal(chart, null, chart.rows[rows[next]].x);
413
+ status.textContent = timer ? "" : chart.rows[rows[next]].label;
414
+ };
415
+ const stop = () => {
416
+ clearInterval(timer);
417
+ timer = undefined;
418
+ if (toggleButton) toggleButton.textContent = text.play;
419
+ if (position >= 0) status.textContent = chart.rows[rows[position]].label;
420
+ };
421
+ const toggleButton = still
422
+ ? undefined
423
+ : button(text.play, () => {
424
+ if (timer) return stop();
425
+ toggleButton.textContent = text.pause;
426
+ timer = setInterval(() => go(position + 1), interval ?? Math.max(40, 6000 / rows.length));
427
+ if (position < 0) go(0);
428
+ });
429
+ button(text.back, () => (stop(), go(Math.max(position < 0 ? rows.length - 2 : position - 1, 0))));
430
+ button(text.forward, () => (stop(), go(position + 1)));
431
+ button(text.all, () => (stop(), go(-1)));
432
+ group.append(status);
433
+ const anchor = chart.root.closest?.("figure") ?? chart.root;
434
+ anchor.after(group);
435
+ return () => {
436
+ stop();
437
+ reveal(chart);
438
+ group.remove();
439
+ };
440
+ }
package/src/render.d.mts CHANGED
@@ -1,16 +1,36 @@
1
1
  export type ChartFormat = "svg" | "html";
2
2
  export type TableMode = "details" | "visible";
3
- /** Which layout the SVG profile renders; `mobile` needs a `mobile` field in the spec. */
4
- export type ChartVariant = "desktop" | "mobile";
3
+ /**
4
+ * Which layout the SVG profile renders; `mobile` needs a `mobile` field in the spec, `print`
5
+ * draws the chart with literal colors for print and PDF renderers, `social` draws it on a
6
+ * 1200 × 630 canvas for link previews such as Open Graph images.
7
+ */
8
+ export type ChartVariant = "desktop" | "mobile" | "print" | "social";
5
9
 
6
10
  export interface RenderChartOptions {
7
11
  format?: ChartFormat;
8
12
  table?: TableMode;
9
13
  idPrefix?: string;
10
14
  variant?: ChartVariant;
15
+ /** Fail on any warning, except those whose code is listed in `allowWarnings`. */
11
16
  strict?: boolean;
17
+ /** Warning codes that `strict` lets through, such as `"dense_chart"`. They are still reported. */
18
+ allowWarnings?: string[];
12
19
  /** Also return a provenance manifest of the render in `manifest`. */
13
20
  manifest?: boolean;
21
+ /**
22
+ * `inline` (default): every chart carries its whole stylesheet. `external`: the page loads
23
+ * `@casoon/chartlet/chartlet.css` once, and a chart carries only its own declared colors.
24
+ */
25
+ styles?: "inline" | "external";
26
+ /** Also return the chart's text alternative in `alternative`. */
27
+ alternative?: boolean;
28
+ /**
29
+ * Add the `data-*` hooks that `@casoon/chartlet/interactive` reads: plot geometry, layer
30
+ * groups and unformatted values on the data table (or in a JSON data block in the SVG
31
+ * profile). Off by default; without it the output is unchanged.
32
+ */
33
+ hooks?: boolean;
14
34
  /** A `chartlet` executable to render with instead of the bundled WebAssembly build. */
15
35
  binary?: string;
16
36
  }
@@ -50,8 +70,33 @@ export interface RenderChartResult {
50
70
  warnings: string[];
51
71
  /** Present when `options.manifest` is set. */
52
72
  manifest?: ChartManifest;
73
+ /** Present when `options.alternative` is set. */
74
+ alternative?: ChartTextAlternative;
53
75
  }
54
76
 
77
+ /**
78
+ * What a chart says without its graphic: the description its SVG carries and its data table, as
79
+ * text, for a host that builds its own accessible wrapper around the SVG.
80
+ */
81
+ export interface ChartTextAlternative {
82
+ description: string;
83
+ table: {
84
+ caption: string;
85
+ /** The column heads; the first names the categories. */
86
+ columns: string[];
87
+ /** One row per category, starting with the category; values as the chart writes them. */
88
+ rows: string[][];
89
+ };
90
+ }
91
+
92
+ export interface StylesheetOptions {
93
+ /** Only the rules of these chart types, such as `["bar", "time"]`; all types when absent. */
94
+ types?: string[];
95
+ }
96
+
97
+ /** The shared stylesheet that charts rendered with `styles: "external"` rely on. */
98
+ export declare function stylesheet(options?: StylesheetOptions): string;
99
+
55
100
  export declare function renderChart(
56
101
  spec: Record<string, unknown>,
57
102
  options?: RenderChartOptions,
@@ -72,6 +117,8 @@ export interface RenderChartDetailedSuccess {
72
117
  warnings: ChartDiagnostic[];
73
118
  /** Present when `options.manifest` is set. */
74
119
  manifest?: ChartManifest;
120
+ /** Present when `options.alternative` is set. */
121
+ alternative?: ChartTextAlternative;
75
122
  }
76
123
 
77
124
  export interface RenderChartDetailedFailure {
package/src/render.mjs CHANGED
@@ -15,12 +15,34 @@ let renderer;
15
15
  export function renderChart(spec, options = {}) {
16
16
  const binary = options.binary ?? process.env.CHARTLET_BIN;
17
17
  if (!binary) {
18
- renderer ??= createRenderer(new WebAssembly.Module(readWasm()));
19
- return renderer.renderChart(spec, options);
18
+ return wasmRenderer().renderChart(spec, options);
20
19
  }
21
20
  return renderWithCli(binary, spec, options);
22
21
  }
23
22
 
23
+ function wasmRenderer() {
24
+ renderer ??= createRenderer(new WebAssembly.Module(readWasm()));
25
+ return renderer;
26
+ }
27
+
28
+ // The CLI writes no text alternative; the bundled WebAssembly build derives the same one.
29
+ function withAlternative(rendered, spec, options) {
30
+ if (options.alternative) {
31
+ rendered.alternative = wasmRenderer().renderChartDetailed(spec, {
32
+ format: "svg",
33
+ alternative: true,
34
+ }).alternative;
35
+ }
36
+ return rendered;
37
+ }
38
+
39
+ // The shared stylesheet that charts rendered with `styles: "external"` rely on, for every chart
40
+ // type or for those in `options.types`. The package also ships the full one as
41
+ // `@casoon/chartlet/chartlet.css`.
42
+ export function stylesheet(options = {}) {
43
+ return wasmRenderer().stylesheet(options);
44
+ }
45
+
24
46
  // Resolved by package name, not relative to this file: bundlers such as Vite copy this module
25
47
  // into a server chunk elsewhere, but leave the package where Node can resolve it.
26
48
  function readWasm() {
@@ -42,8 +64,7 @@ function readWasm() {
42
64
  export function renderChartDetailed(spec, options = {}) {
43
65
  const binary = options.binary ?? process.env.CHARTLET_BIN;
44
66
  if (!binary) {
45
- renderer ??= createRenderer(new WebAssembly.Module(readWasm()));
46
- return renderer.renderChartDetailed(spec, options);
67
+ return wasmRenderer().renderChartDetailed(spec, options);
47
68
  }
48
69
  const { result, manifest } = runCli(
49
70
  binary,
@@ -65,7 +86,7 @@ export function renderChartDetailed(spec, options = {}) {
65
86
  if (manifest) {
66
87
  rendered.manifest = manifest;
67
88
  }
68
- return rendered;
89
+ return withAlternative(rendered, spec, options);
69
90
  }
70
91
 
71
92
  function renderWithCli(binary, spec, options) {
@@ -86,7 +107,7 @@ function renderWithCli(binary, spec, options) {
86
107
  if (manifest) {
87
108
  rendered.manifest = manifest;
88
109
  }
89
- return rendered;
110
+ return withAlternative(rendered, spec, options);
90
111
  }
91
112
 
92
113
  // Runs `chartlet render` on `input` and returns the process result with the manifest it wrote.
@@ -101,9 +122,18 @@ function runCli(binary, input, options, extraArgs) {
101
122
  if (options.variant) {
102
123
  args.push("--variant", options.variant);
103
124
  }
125
+ if (options.styles) {
126
+ args.push("--styles", options.styles);
127
+ }
128
+ if (options.hooks) {
129
+ args.push("--hooks");
130
+ }
104
131
  if (options.strict) {
105
132
  args.push("--strict");
106
133
  }
134
+ for (const code of options.allowWarnings ?? []) {
135
+ args.push("--allow-warning", code);
136
+ }
107
137
  args.push(...extraArgs);
108
138
  // The CLI writes the manifest to a file; it is read back and removed with its directory.
109
139
  const manifestDirectory = options.manifest
package/src/wasm.d.mts CHANGED
@@ -2,6 +2,7 @@ import type {
2
2
  RenderChartDetailedResult,
3
3
  RenderChartOptions,
4
4
  RenderChartResult,
5
+ StylesheetOptions,
5
6
  } from "./render.mjs";
6
7
 
7
8
  export interface ChartRenderer {
@@ -12,6 +13,8 @@ export interface ChartRenderer {
12
13
  spec: Record<string, unknown> | string,
13
14
  options?: RenderChartOptions,
14
15
  ): RenderChartDetailedResult;
16
+ /** The shared stylesheet that charts rendered with `styles: "external"` rely on. */
17
+ stylesheet(options?: StylesheetOptions): string;
15
18
  }
16
19
 
17
20
  /** Instantiates the renderer from the compiled `@casoon/chartlet/chartlet.wasm` module. */
package/src/wasm.mjs CHANGED
@@ -10,20 +10,8 @@ export function createRenderer(module) {
10
10
  .exports;
11
11
 
12
12
  // Sends one request to the renderer and returns its parsed JSON response.
13
- function respond(spec, options) {
14
- const request = encoder.encode(
15
- JSON.stringify({
16
- spec,
17
- options: {
18
- format: options.format ?? "html",
19
- table: options.table ?? "details",
20
- idPrefix: options.idPrefix || undefined,
21
- variant: options.variant,
22
- strict: options.strict ?? false,
23
- manifest: options.manifest ?? false,
24
- },
25
- }),
26
- );
13
+ function send(message) {
14
+ const request = encoder.encode(JSON.stringify(message));
27
15
  const input = alloc(request.length);
28
16
  new Uint8Array(memory.buffer, input, request.length).set(request);
29
17
  const output = render(input, request.length);
@@ -34,6 +22,25 @@ export function createRenderer(module) {
34
22
  return response;
35
23
  }
36
24
 
25
+ // Renders one chart and returns the renderer's response.
26
+ function respond(spec, options) {
27
+ return send({
28
+ spec,
29
+ options: {
30
+ format: options.format ?? "html",
31
+ table: options.table ?? "details",
32
+ idPrefix: options.idPrefix || undefined,
33
+ variant: options.variant,
34
+ strict: options.strict ?? false,
35
+ allowWarnings: options.allowWarnings ?? [],
36
+ manifest: options.manifest ?? false,
37
+ alternative: options.alternative ?? false,
38
+ styles: options.styles ?? "inline",
39
+ hooks: options.hooks ?? false,
40
+ },
41
+ });
42
+ }
43
+
37
44
  return {
38
45
  renderChart(spec, options = {}) {
39
46
  const response = respond(JSON.stringify(spec), options);
@@ -51,13 +58,26 @@ export function createRenderer(module) {
51
58
  if (response.manifest) {
52
59
  result.manifest = response.manifest;
53
60
  }
61
+ if (response.alternative) {
62
+ result.alternative = response.alternative;
63
+ }
54
64
  return result;
55
65
  },
56
66
 
57
- // The renderer's response as it is: `ok`, `error` or `content`, `styleHashes` and
58
- // `manifest`, and the warnings as `{ code, path, message }`. A string is taken as JSON text.
67
+ // The renderer's response as it is: `ok`, `error` or `content`, `styleHashes`, `manifest`
68
+ // and `alternative`, and the warnings as `{ code, path, message }`. A string is taken as JSON text.
59
69
  renderChartDetailed(spec, options = {}) {
60
70
  return respond(typeof spec === "string" ? spec : JSON.stringify(spec), options);
61
71
  },
72
+
73
+ // The shared stylesheet that charts rendered with `styles: "external"` rely on, for every
74
+ // chart type or for those in `options.types`.
75
+ stylesheet(options = {}) {
76
+ const response = send({ stylesheet: true, types: options.types });
77
+ if (!response.ok) {
78
+ throw new Error(`chartlet: ${response.error.message}`);
79
+ }
80
+ return response.stylesheet;
81
+ },
62
82
  };
63
83
  }