enarratio-astro 0.0.0-stage → 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/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to enarratio-astro are recorded here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/). Before 1.0.0, a minor version may change the options;
6
+ every such change is listed here.
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] - 2026-10-24
11
+
12
+ ### Added
13
+
14
+ - `<Chart>`: bar, line, stacked area, scatter and heatmap charts drawn on the server by Enarratio
15
+ 0.3.1, from rows or from CSV, semicolon- or tab-separated text, with a required description, a
16
+ data table, and light and dark themes. The chart CSS is written once per page.
17
+ - Charts in Markdown: `chart` code blocks, with `satteriCharts()` for Sätteri and `remarkCharts`
18
+ for remark.
19
+ - `<Enhance />` and the `interactive` option: Enarratio's enhancement script, only on pages that
20
+ ask for it.
21
+ - `styles`: `"theme"` (default), `"base"` for sites whose tokens define the colors, or `"none"`.
22
+ - A note in place of a chart that cannot be drawn, saying why.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dustin Edwards
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,151 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # enarratio-astro
2
+
3
+ **Accessible charts for [Astro](https://astro.build): a `<Chart>` component and charts in Markdown,
4
+ drawn on the server by [Enarratio](https://github.com/DrDustinEdwards/enarratio).**
5
+
6
+ A chart arrives in the page as HTML and SVG: complete before any script runs, readable by screen
7
+ readers and search engines, with a data table, and in light and dark. It draws bar (stacked, side
8
+ by side, vertical or horizontal; counting rows when no value column is given), line, stacked area,
9
+ scatter (with an optional regression line and 95% band) and heatmap charts. A chart can be made
10
+ interactive (hover and focus details, keyboard navigation, click-to-filter) with Enarratio's small
11
+ enhancement script, which is added only to pages that ask for it.
12
+
13
+ Supports Astro 6 or later. Status: 0.x, so options may change before 1.0; every change is in the
14
+ [changelog](https://github.com/DrDustinEdwards/astro/blob/main/packages/enarratio-astro/CHANGELOG.md). For EmDash sites,
15
+ [enarratio-emdash](https://github.com/DrDustinEdwards/astro/tree/main/packages/enarratio-emdash#readme) adds the same charts as a block
16
+ in the editor.
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ npm install enarratio-astro
22
+ ```
23
+
24
+ ## In a page
25
+
26
+ ```astro
27
+ ---
28
+ import Chart from "enarratio-astro/Chart.astro";
29
+
30
+ const downloads = [
31
+ { year: 2024, package: "Core", downloads: 4100 },
32
+ { year: 2025, package: "Core", downloads: 5300 },
33
+ { year: 2026, package: "Core", downloads: 6100 },
34
+ { year: 2024, package: "Plugin", downloads: 1200 },
35
+ { year: 2025, package: "Plugin", downloads: 1900 },
36
+ { year: 2026, package: "Plugin", downloads: 2800 },
37
+ ];
38
+ ---
39
+ <Chart
40
+ type="line"
41
+ data={downloads}
42
+ x="year"
43
+ y="downloads"
44
+ series="package"
45
+ title="Downloads per year"
46
+ alt="Downloads per year, 2024 to 2026: the core grows from 4,100 to 6,100, the plugin from 1,200 to 2,800."
47
+ interactive
48
+ />
49
+ ```
50
+
51
+ `data` is rows as objects (from code, JSON or a content collection; dates become ISO dates) or
52
+ text: CSV, semicolon-separated, or pasted from a spreadsheet (tab-separated), first row naming the
53
+ columns. The chart CSS is written once per page, however many charts it has.
54
+
55
+ ## In Markdown
56
+
57
+ A code block whose language is `chart` becomes a chart: options, a line of three dashes, then the
58
+ data.
59
+
60
+ ~~~md
61
+ ```chart
62
+ type: bar
63
+ x: team
64
+ y: tickets
65
+ series: status
66
+ layout: grouped
67
+ alt: Support has the most open tickets; Platform has closed the most.
68
+ ---
69
+ team,status,tickets
70
+ Support,Open,14
71
+ Support,Closed,22
72
+ Platform,Open,5
73
+ Platform,Closed,31
74
+ ```
75
+ ~~~
76
+
77
+ Register the plugin for Astro's Markdown processor. Astro 7's default, Sätteri:
78
+
79
+ ```js
80
+ // astro.config.mjs
81
+ import { satteri } from "@astrojs/markdown-satteri";
82
+ import { satteriCharts } from "enarratio-astro/markdown";
83
+
84
+ export default defineConfig({
85
+ markdown: { processor: satteri({ mdastPlugins: [satteriCharts()] }) },
86
+ });
87
+ ```
88
+
89
+ With remark (Astro 6, or Astro 7's unified processor):
90
+
91
+ ```js
92
+ import { remarkCharts } from "enarratio-astro/markdown";
93
+
94
+ export default defineConfig({ markdown: { remarkPlugins: [remarkCharts] } });
95
+ ```
96
+
97
+ A Markdown chart with `interactive: true` is marked for the enhancement script; include it once in
98
+ the page's layout with `<Enhance />` from `enarratio-astro/Enhance.astro`. It finds every
99
+ interactive chart on the page and works with view transitions.
100
+
101
+ ## Options
102
+
103
+ The component's props and a Markdown block's keys are the same:
104
+
105
+ | Option | Used by | Notes |
106
+ |---|---|---|
107
+ | `type` | all | `bar` (default), `line`, `area` (stacked), `scatter` or `heatmap`. |
108
+ | `data` | all | The data (component only; in Markdown it follows the dashes). Up to 5000 rows and 50 columns. |
109
+ | `alt` | all | **Required.** What the chart shows and finds, in a sentence. It names the chart for screen readers. |
110
+ | `title`, `caption` | all | Optional. The caption is for source, method or caveats. |
111
+ | `x` | all | The column along the x axis. Column names match without regard to case. ISO dates make a time axis in line and area charts. |
112
+ | `y` | all | The value column. Bar charts count rows when it is missing. For a heatmap, the row column. |
113
+ | `series` | bar, line, area, scatter | Splits rows into series, told apart by color and by legend, labels or symbols. |
114
+ | `value` | heatmap | The cell value column. |
115
+ | `xLabel`, `yLabel` | all | Axis labels. |
116
+ | `layout` | bar | `stacked` (default) or `grouped`. |
117
+ | `orientation` | bar | `vertical` (default) or `horizontal`. |
118
+ | `scale` | line, scatter | `linear` (default) or `log`. |
119
+ | `regression` | scatter | A least-squares line with its 95% band. |
120
+ | `dataTable` | all | `details` (default; behind a "Data table" toggle) or `visually-hidden` (screen readers only). |
121
+ | `id` | all | The figure's id. |
122
+ | `interactive` | all | Adds the enhancement script. Off by default, so pages stay script-free. |
123
+
124
+ A chart that cannot be drawn (a column that is not in the data, text in a number column, a missing
125
+ `alt`) is replaced by a short note saying why, and the reason is logged, so one mistake never
126
+ breaks the page. All text is escaped.
127
+
128
+ ## Styles
129
+
130
+ The component takes `styles`, `theme` and `stylesheetOptions`; the Markdown plugins take the same
131
+ as options (`satteriCharts({ styles: "base" })`).
132
+
133
+ - `styles: "theme"` (default): an Enarratio theme (`theme`, default Enarratio's own), in light and
134
+ dark. Charts follow the page's `color-scheme`; for a site that switches with an attribute, pass
135
+ `stylesheetOptions={{ colorScheme: { dark: '[data-theme="dark"]' } }}`.
136
+ - `styles: "base"`: layout rules without colors or fonts, for a site whose own design tokens define
137
+ the `--enarratio-*` properties. [Capsomer](https://github.com/DrDustinEdwards/capsomer)'s tokens do.
138
+ - `styles: "none"`: nothing; the site includes Enarratio's stylesheet itself.
139
+
140
+ Enarratio's [README](https://github.com/DrDustinEdwards/enarratio#themes) covers themes and the
141
+ custom properties.
142
+
143
+ ## Rendering cost
144
+
145
+ Bar, line and area charts are drawn by `enarratio/lite`, which builds the SVG as a string with no
146
+ DOM, the cheapest render on Cloudflare Workers. Scatter plots and heatmaps load `enarratio/plot`
147
+ (Observable Plot and linkedom) only when a page has one.
148
+
149
+ ## License
150
+
151
+ [MIT](LICENSE). Copyright (c) 2026 Dustin Edwards.
@@ -0,0 +1,59 @@
1
+ /** The chart types a {@link ChartSpec} can draw. */
2
+ export declare const CHART_TYPES: readonly ["bar", "line", "area", "scatter", "heatmap"];
3
+ export type ChartType = (typeof CHART_TYPES)[number];
4
+ /**
5
+ * One chart, as an author writes it: in a component's props, a Markdown `chart` block, or an
6
+ * EmDash Chart block. Every field is checked when the chart is drawn, so a spec can come from
7
+ * content as easily as from code.
8
+ */
9
+ export interface ChartSpec {
10
+ /** Bar (default), line, area (stacked), scatter or heatmap. */
11
+ readonly type?: string | undefined;
12
+ /**
13
+ * The data: CSV, semicolon- or tab-separated text whose first row names the columns, or rows
14
+ * as objects (from JSON or a content collection) whose values are numbers, text, dates or empty.
15
+ */
16
+ readonly data: string | readonly Readonly<Record<string, unknown>>[];
17
+ /** Required: what the chart shows and finds, in a sentence. Names the chart for screen readers. */
18
+ readonly alt?: string | undefined;
19
+ readonly title?: string | undefined;
20
+ /** Source, method or caveats, below the chart. */
21
+ readonly caption?: string | undefined;
22
+ /** The column along the x axis. Column names match without regard to case. */
23
+ readonly x?: string | undefined;
24
+ /** The value column. Bar charts count rows without one; for a heatmap, the row column. */
25
+ readonly y?: string | undefined;
26
+ /** A column that splits rows into series. */
27
+ readonly series?: string | undefined;
28
+ /** Heatmap: the cell value column. */
29
+ readonly value?: string | undefined;
30
+ readonly xLabel?: string | undefined;
31
+ readonly yLabel?: string | undefined;
32
+ /** Bar: series stacked (default) or side by side ("grouped"). */
33
+ readonly layout?: string | undefined;
34
+ /** Bar: "vertical" (default) or "horizontal". */
35
+ readonly orientation?: string | undefined;
36
+ /** Line and scatter: "linear" (default) or "log" y axis. */
37
+ readonly scale?: string | undefined;
38
+ /** Scatter: a least-squares line with its 95% band. */
39
+ readonly regression?: boolean | undefined;
40
+ /** "details" (default): the data table behind a toggle; "visually-hidden": for screen readers only. */
41
+ readonly dataTable?: string | undefined;
42
+ /** The figure's id, reported as `chartId` in the enhancement layer's events. */
43
+ readonly id?: string | undefined;
44
+ }
45
+ /** A drawn chart's HTML, or why it could not be drawn, in words an author can act on. */
46
+ export type ChartResult = {
47
+ readonly ok: true;
48
+ readonly html: string;
49
+ } | {
50
+ readonly ok: false;
51
+ readonly error: string;
52
+ };
53
+ /**
54
+ * Draws a chart. Bar, line and area charts come from `enarratio/lite`, which builds the SVG as a
55
+ * string with no DOM, the cheapest render on a Worker; scatter plots and heatmaps load
56
+ * `enarratio/plot` (Observable Plot and linkedom) only when a page has one. Never throws: a chart
57
+ * that cannot be drawn returns the reason instead, so one mistake cannot break a page.
58
+ */
59
+ export declare function renderChart(spec: ChartSpec): Promise<ChartResult>;
package/dist/chart.js ADDED
@@ -0,0 +1,116 @@
1
+ import { areaChart, barChart, lineChart } from "enarratio/lite";
2
+ import { column, parseTable, tableFromRows } from "./data.js";
3
+ /** The chart types a {@link ChartSpec} can draw. */
4
+ export const CHART_TYPES = ["bar", "line", "area", "scatter", "heatmap"];
5
+ function text(value) {
6
+ const trimmed = value?.trim();
7
+ return trimmed ? trimmed : undefined;
8
+ }
9
+ /** Copies the rows with one column's numbers turned into text, for fields Enarratio reads as names. */
10
+ function asNames(table, name) {
11
+ return table.rows.map((row) => {
12
+ const copy = Object.assign(Object.create(null), row);
13
+ const v = copy[name];
14
+ if (typeof v === "number")
15
+ copy[name] = String(v);
16
+ return copy;
17
+ });
18
+ }
19
+ /** Checks that a column holds only numbers and empty cells. */
20
+ function numeric(table, name) {
21
+ const bad = table.rows.find((row) => typeof row[name] === "string");
22
+ if (bad)
23
+ throw new Error(`The column "${name}" should hold numbers, but has "${bad[name]}".`);
24
+ }
25
+ /** The options every chart type shares: text, the data table and the id. */
26
+ function figure(spec) {
27
+ const alt = text(spec.alt);
28
+ if (!alt)
29
+ throw new Error("Add a description (alt): one sentence on what the chart shows.");
30
+ const title = text(spec.title);
31
+ const caption = text(spec.caption);
32
+ const xLabel = text(spec.xLabel);
33
+ const yLabel = text(spec.yLabel);
34
+ const id = text(spec.id)?.replace(/[^A-Za-z0-9_-]/g, "");
35
+ return {
36
+ alt,
37
+ ...(title ? { title } : {}),
38
+ ...(caption ? { caption } : {}),
39
+ ...(xLabel ? { xLabel } : {}),
40
+ ...(yLabel ? { yLabel } : {}),
41
+ ...(id ? { id } : {}),
42
+ dataTable: spec.dataTable === "visually-hidden" ? "visually-hidden" : "details",
43
+ };
44
+ }
45
+ async function draw(spec) {
46
+ const type = (text(spec.type) ?? "bar").toLowerCase();
47
+ if (!CHART_TYPES.includes(type)) {
48
+ throw new Error(`There is no chart type "${spec.type}". Use one of: ${CHART_TYPES.join(", ")}.`);
49
+ }
50
+ const common = figure(spec);
51
+ const table = typeof spec.data === "string" ? parseTable(spec.data) : tableFromRows(spec.data);
52
+ const x = column(table, spec.x, "x axis");
53
+ const seriesName = text(spec.series) ? column(table, spec.series, "series") : undefined;
54
+ const data = seriesName ? asNames(table, seriesName) : [...table.rows];
55
+ const series = seriesName ? { series: seriesName } : {};
56
+ const log = spec.scale === "log" ? { yType: "log" } : {};
57
+ switch (type) {
58
+ case "bar": {
59
+ const y = text(spec.y) ? column(table, spec.y, "values") : undefined;
60
+ if (y)
61
+ numeric(table, y);
62
+ return barChart({
63
+ ...common,
64
+ data,
65
+ x,
66
+ ...(y ? { y } : {}),
67
+ ...series,
68
+ layout: spec.layout === "grouped" ? "grouped" : "stacked",
69
+ orientation: spec.orientation === "horizontal" ? "horizontal" : "vertical",
70
+ });
71
+ }
72
+ case "line":
73
+ case "area": {
74
+ const y = column(table, spec.y, "values");
75
+ numeric(table, y);
76
+ const options = { ...common, data, x, y, ...series };
77
+ return type === "line" ? lineChart({ ...options, ...log }) : areaChart(options);
78
+ }
79
+ case "scatter": {
80
+ const y = column(table, spec.y, "values");
81
+ numeric(table, x);
82
+ numeric(table, y);
83
+ const { scatterPlot } = await import("enarratio/plot");
84
+ return scatterPlot({
85
+ ...common,
86
+ data,
87
+ x,
88
+ y,
89
+ ...series,
90
+ ...log,
91
+ regression: spec.regression === true,
92
+ });
93
+ }
94
+ case "heatmap": {
95
+ const y = column(table, spec.y, "rows");
96
+ const value = column(table, spec.value, "cell values");
97
+ numeric(table, value);
98
+ const { heatmap } = await import("enarratio/plot");
99
+ return heatmap({ ...common, data, x, y, value });
100
+ }
101
+ }
102
+ }
103
+ /**
104
+ * Draws a chart. Bar, line and area charts come from `enarratio/lite`, which builds the SVG as a
105
+ * string with no DOM, the cheapest render on a Worker; scatter plots and heatmaps load
106
+ * `enarratio/plot` (Observable Plot and linkedom) only when a page has one. Never throws: a chart
107
+ * that cannot be drawn returns the reason instead, so one mistake cannot break a page.
108
+ */
109
+ export async function renderChart(spec) {
110
+ try {
111
+ return { ok: true, html: await draw(spec) };
112
+ }
113
+ catch (error) {
114
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
115
+ }
116
+ }
package/dist/data.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /** A cell after parsing: a number, text, or `null` for an empty cell. */
2
+ export type Cell = number | string | null;
3
+ /** A table parsed from the block's data field. */
4
+ export interface Table {
5
+ readonly columns: readonly string[];
6
+ readonly rows: ReadonlyArray<Readonly<Record<string, Cell>>>;
7
+ }
8
+ /** Limits that keep one chart's render bounded, whatever an editor pastes. */
9
+ export declare const MAX_ROWS = 5000;
10
+ export declare const MAX_COLUMNS = 50;
11
+ /**
12
+ * Parses the data an editor pasted or typed: CSV, semicolon-separated or tab-separated text
13
+ * whose first row names the columns. Throws an Error whose message an editor can act on.
14
+ */
15
+ export declare function parseTable(text: string): Table;
16
+ /**
17
+ * The column an editor named, matched without regard to case or surrounding space. Throws when
18
+ * there is none, listing the columns there are.
19
+ */
20
+ export declare function column(table: Table, name: string | undefined, role: string): string;
21
+ /** Reads rows given as objects (from JSON or a content collection) into a table. */
22
+ export declare function tableFromRows(input: readonly Readonly<Record<string, unknown>>[]): Table;
package/dist/data.js ADDED
@@ -0,0 +1,161 @@
1
+ /** Limits that keep one chart's render bounded, whatever an editor pastes. */
2
+ export const MAX_ROWS = 5000;
3
+ export const MAX_COLUMNS = 50;
4
+ const NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
5
+ const GROUPED_NUMBER = /^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/;
6
+ /** Reads a cell: numbers (including "1,234") become numbers, an empty cell `null`, the rest text. */
7
+ function cell(raw) {
8
+ const text = raw.trim();
9
+ if (text === "")
10
+ return null;
11
+ if (NUMBER.test(text))
12
+ return Number(text);
13
+ if (GROUPED_NUMBER.test(text))
14
+ return Number(text.replaceAll(",", ""));
15
+ return text;
16
+ }
17
+ /**
18
+ * The delimiter of pasted data: a tab when the header row has one (a spreadsheet paste),
19
+ * otherwise whichever of comma and semicolon appears more often outside quotes in that row.
20
+ */
21
+ function delimiter(text) {
22
+ const header = text.slice(0, text.search(/\r?\n|$/));
23
+ if (header.includes("\t"))
24
+ return "\t";
25
+ const unquoted = header.replace(/"[^"]*"/g, "");
26
+ const count = (c) => unquoted.split(c).length - 1;
27
+ return count(";") > count(",") ? ";" : ",";
28
+ }
29
+ /** Splits delimited text into records, following RFC 4180 quoting ("" is a literal quote). */
30
+ function records(text, sep) {
31
+ const out = [];
32
+ let record = [];
33
+ let field = "";
34
+ let quoted = false;
35
+ for (let i = 0; i < text.length; i++) {
36
+ const c = text[i];
37
+ if (quoted) {
38
+ if (c === '"' && text[i + 1] === '"') {
39
+ field += '"';
40
+ i++;
41
+ }
42
+ else if (c === '"') {
43
+ quoted = false;
44
+ }
45
+ else {
46
+ field += c;
47
+ }
48
+ }
49
+ else if (c === '"' && field.trim() === "") {
50
+ quoted = true;
51
+ field = "";
52
+ }
53
+ else if (c === sep) {
54
+ record.push(field);
55
+ field = "";
56
+ }
57
+ else if (c === "\n" || c === "\r") {
58
+ if (c === "\r" && text[i + 1] === "\n")
59
+ i++;
60
+ record.push(field);
61
+ out.push(record);
62
+ record = [];
63
+ field = "";
64
+ }
65
+ else {
66
+ field += c;
67
+ }
68
+ }
69
+ if (quoted)
70
+ throw new Error("The data has a quote that is never closed.");
71
+ record.push(field);
72
+ out.push(record);
73
+ return out.filter((r) => r.some((f) => f.trim() !== ""));
74
+ }
75
+ /**
76
+ * Parses the data an editor pasted or typed: CSV, semicolon-separated or tab-separated text
77
+ * whose first row names the columns. Throws an Error whose message an editor can act on.
78
+ */
79
+ export function parseTable(text) {
80
+ const all = records(text, delimiter(text));
81
+ const [header, ...body] = all;
82
+ if (!header || body.length === 0) {
83
+ throw new Error("Add data: a first row naming the columns, then at least one row of values.");
84
+ }
85
+ const columns = header.map((name) => name.trim());
86
+ if (columns.length > MAX_COLUMNS)
87
+ throw new Error(`The data has more than ${MAX_COLUMNS} columns.`);
88
+ if (body.length > MAX_ROWS)
89
+ throw new Error(`The data has more than ${MAX_ROWS} rows.`);
90
+ const seen = new Set();
91
+ for (const name of columns) {
92
+ if (name === "")
93
+ throw new Error("Every column in the first row needs a name.");
94
+ const key = name.toLowerCase();
95
+ if (seen.has(key))
96
+ throw new Error(`Two columns are named "${name}".`);
97
+ seen.add(key);
98
+ }
99
+ const rows = body.map((record, n) => {
100
+ if (record.slice(columns.length).some((f) => f.trim() !== "")) {
101
+ throw new Error(`Row ${n + 2} has more values than there are columns.`);
102
+ }
103
+ // No prototype, so a column named "__proto__" is an ordinary field.
104
+ const row = Object.create(null);
105
+ columns.forEach((name, i) => {
106
+ row[name] = cell(record[i] ?? "");
107
+ });
108
+ return row;
109
+ });
110
+ return { columns, rows };
111
+ }
112
+ /**
113
+ * The column an editor named, matched without regard to case or surrounding space. Throws when
114
+ * there is none, listing the columns there are.
115
+ */
116
+ export function column(table, name, role) {
117
+ const wanted = name?.trim().toLowerCase() ?? "";
118
+ if (wanted === "")
119
+ throw new Error(`Name the ${role} column.`);
120
+ const found = table.columns.find((c) => c.toLowerCase() === wanted);
121
+ if (!found) {
122
+ throw new Error(`There is no column "${name?.trim()}" for the ${role}. The columns are: ${table.columns.join(", ")}.`);
123
+ }
124
+ return found;
125
+ }
126
+ /** Reads one value from a row given as an object: dates as ISO text, true and false as text. */
127
+ function value(raw) {
128
+ if (raw === null || raw === undefined || raw === "")
129
+ return null;
130
+ if (typeof raw === "number")
131
+ return Number.isFinite(raw) ? raw : null;
132
+ if (typeof raw === "string")
133
+ return raw;
134
+ if (raw instanceof Date)
135
+ return raw.toISOString();
136
+ if (typeof raw === "boolean")
137
+ return String(raw);
138
+ throw new Error(`A value in the data is ${Array.isArray(raw) ? "a list" : "an object"}; use numbers or text.`);
139
+ }
140
+ /** Reads rows given as objects (from JSON or a content collection) into a table. */
141
+ export function tableFromRows(input) {
142
+ if (input.length === 0)
143
+ throw new Error("Add data: at least one row.");
144
+ if (input.length > MAX_ROWS)
145
+ throw new Error(`The data has more than ${MAX_ROWS} rows.`);
146
+ const columns = [];
147
+ for (const row of input) {
148
+ for (const key of Object.keys(row))
149
+ if (!columns.includes(key))
150
+ columns.push(key);
151
+ }
152
+ if (columns.length > MAX_COLUMNS)
153
+ throw new Error(`The data has more than ${MAX_COLUMNS} columns.`);
154
+ const rows = input.map((source) => {
155
+ const row = Object.create(null);
156
+ for (const name of columns)
157
+ row[name] = value(source[name]);
158
+ return row;
159
+ });
160
+ return { columns, rows };
161
+ }
@@ -0,0 +1,6 @@
1
+ import type { ChartResult } from "./chart.js";
2
+ /**
3
+ * The markup that goes on the page for a drawn chart, or for one that could not be drawn: the
4
+ * chart in a wrapper (marked when it is interactive), or a note saying why.
5
+ */
6
+ export declare function chartMarkup(result: ChartResult, interactive: boolean): string;
package/dist/figure.js ADDED
@@ -0,0 +1,12 @@
1
+ import { escapeHtml } from "enarratio";
2
+ /**
3
+ * The markup that goes on the page for a drawn chart, or for one that could not be drawn: the
4
+ * chart in a wrapper (marked when it is interactive), or a note saying why.
5
+ */
6
+ export function chartMarkup(result, interactive) {
7
+ if (!result.ok) {
8
+ return `<p class="enarratio-chart-error" role="note">This chart could not be drawn. ${escapeHtml(result.error)}</p>`;
9
+ }
10
+ const mark = interactive ? " data-enarratio-interactive-chart" : "";
11
+ return `<div class="enarratio-chart"${mark}>${result.html}</div>`;
12
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Enarratio charts for Astro: a `<Chart>` component (`enarratio-astro/Chart.astro`), charts in
3
+ * Markdown (`enarratio-astro/markdown`), and the functions under both, drawn on the server by
4
+ * Enarratio as accessible HTML and SVG.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ export { CHART_TYPES, type ChartResult, type ChartSpec, type ChartType, renderChart, } from "./chart.js";
9
+ export { type Cell, parseTable, type Table, tableFromRows } from "./data.js";
10
+ export { chartMarkup } from "./figure.js";
11
+ export { chartStyles, type StyleOptions, type Styles } from "./styles.js";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Enarratio charts for Astro: a `<Chart>` component (`enarratio-astro/Chart.astro`), charts in
3
+ * Markdown (`enarratio-astro/markdown`), and the functions under both, drawn on the server by
4
+ * Enarratio as accessible HTML and SVG.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ export { CHART_TYPES, renderChart, } from "./chart.js";
9
+ export { parseTable, tableFromRows } from "./data.js";
10
+ export { chartMarkup } from "./figure.js";
11
+ export { chartStyles } from "./styles.js";
@@ -0,0 +1,67 @@
1
+ import { type ChartSpec } from "./chart.js";
2
+ import { type StyleOptions } from "./styles.js";
3
+ /** Options for the Markdown plugins: how charts are styled. */
4
+ export type MarkdownChartOptions = StyleOptions;
5
+ /**
6
+ * Reads a `chart` code block: `key: value` lines, a line of three dashes, then the data.
7
+ *
8
+ * ```chart
9
+ * type: line
10
+ * x: month
11
+ * y: visitors
12
+ * alt: Monthly visitors rise from 820 to 1,190.
13
+ * ---
14
+ * month,visitors
15
+ * 2026-01-01,820
16
+ * ```
17
+ */
18
+ export declare function parseChartBlock(source: string): ChartSpec & {
19
+ readonly interactive: boolean;
20
+ };
21
+ /** The parts of a Markdown code node the plugins read. */
22
+ interface CodeNode {
23
+ readonly type: "code";
24
+ readonly lang?: string | null | undefined;
25
+ readonly value: string;
26
+ }
27
+ /** The parts of the Sätteri visitor context the plugin uses. */
28
+ interface SatteriContext {
29
+ replaceNode(node: Readonly<CodeNode>, content: {
30
+ type: "html";
31
+ value: string;
32
+ }): void;
33
+ }
34
+ /**
35
+ * Charts in Markdown for Astro's default Markdown processor, Sätteri (Astro 7 and later): every
36
+ * code block whose language is `chart` becomes a chart, drawn when the site builds or renders.
37
+ *
38
+ * @example
39
+ * // astro.config.mjs
40
+ * import { satteri } from "@astrojs/markdown-satteri";
41
+ * import { satteriCharts } from "enarratio-astro/markdown";
42
+ * export default defineConfig({ markdown: { processor: satteri({ mdastPlugins: [satteriCharts()] }) } });
43
+ */
44
+ export declare function satteriCharts(options?: MarkdownChartOptions): {
45
+ name: string;
46
+ before(): void;
47
+ code(node: Readonly<CodeNode>, ctx: SatteriContext): Promise<void>;
48
+ };
49
+ interface MdastParent {
50
+ children: Array<{
51
+ type: string;
52
+ lang?: string | null | undefined;
53
+ value?: string | undefined;
54
+ children?: unknown[] | undefined;
55
+ }>;
56
+ }
57
+ /**
58
+ * Charts in Markdown for the unified (remark) processor, Astro 6's default and an option in
59
+ * Astro 7: every code block whose language is `chart` becomes a chart.
60
+ *
61
+ * @example
62
+ * // astro.config.mjs, Astro 6
63
+ * import { remarkCharts } from "enarratio-astro/markdown";
64
+ * export default defineConfig({ markdown: { remarkPlugins: [remarkCharts] } });
65
+ */
66
+ export declare function remarkCharts(options?: MarkdownChartOptions): (tree: MdastParent) => Promise<void>;
67
+ export {};