@aparte/plugin-chartjs 0.0.0-stage → 0.29.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aparté
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,224 @@
1
- # Temporary Holding Version
1
+ # @aparte/plugin-chartjs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Charts for [aparté](https://github.com/apartejs/aparte) via [Chart.js](https://www.chartjs.org).
4
+ A Chart.js config that a model writes in a ```` ```chartjs ```` fence, or that a tool returns, is
5
+ drawn as a chart — as it streams, whichever Markdown provider is installed, or none.
6
+
7
+ ```bash
8
+ npm install @aparte/plugin-chartjs @aparte/core chart.js
9
+ ```
10
+
11
+ ```ts
12
+ import { setupChartjs } from '@aparte/plugin-chartjs';
13
+
14
+ setupChartjs();
15
+ ```
16
+
17
+ `@aparte/core` and `chart.js` (4.4 or later, below 5) are **peer dependencies**. Chart.js is
18
+ loaded on the first chart, not before, and a chart is drawn only once it comes near the screen,
19
+ so reopening a long conversation stays fast.
20
+
21
+ ## The fence
22
+
23
+ The body is Chart.js' own config, `{ type, data, options }`, as JSON — nothing new for a model to
24
+ learn. Both ```` ```chartjs ```` and ```` ```chart.js ```` are drawn (`CHARTJS_LANGUAGES`).
25
+
26
+ ````md
27
+ ```chartjs
28
+ {
29
+ "type": "bar",
30
+ "data": {
31
+ "labels": ["Jan", "Feb", "Mar"],
32
+ "datasets": [{ "label": "Sales", "data": [12, 19, 7] }]
33
+ },
34
+ "options": { "plugins": { "title": { "display": true, "text": "Sales by month" } } }
35
+ }
36
+ ```
37
+ ````
38
+
39
+ While a reply streams, the chart is redrawn from the part of its JSON that has arrived — at most
40
+ every 300 ms, and only when what has arrived changes the chart — so its bars or points appear as
41
+ the model writes them. Before its first point it is a quiet box the size the chart will be. Once
42
+ the fence closes, a body that is not a chart shows a note and its source.
43
+
44
+ ## A tool that returns a chart
45
+
46
+ Name the tools whose result is a Chart.js config, and the chart is drawn in place of the tool's
47
+ row: its `structuredContent`, else its text read as JSON. A quiet box shows while the call runs;
48
+ a call refused or failed shows one line instead.
49
+
50
+ ```ts
51
+ setupChartjs({ tool: ['plot_sales', /^chart_/] });
52
+ ```
53
+
54
+ A tool that returns its own data rather than a chart takes a `map` — the result and the call's
55
+ input in, a Chart.js config out:
56
+
57
+ ```ts
58
+ setupChartjs({
59
+ tool: 'get_revenue',
60
+ map: (result, input) => {
61
+ const rows = result as Array<{ month: string; total: number }>;
62
+ return {
63
+ type: 'line',
64
+ data: {
65
+ labels: rows.map((r) => r.month),
66
+ datasets: [{ label: String(input.region ?? 'Revenue'), data: rows.map((r) => r.total) }],
67
+ },
68
+ };
69
+ },
70
+ });
71
+ ```
72
+
73
+ ## The chat's look
74
+
75
+ Wherever a config leaves them out, a chart takes the chat's tokens: text in `--aparte-text`, axis
76
+ ticks and titles in `--aparte-text-muted`, grid and axis lines in `--aparte-border`, the tooltip on
77
+ `--aparte-surface-1`, the chat's font, and a transparent background. Every value the config sets
78
+ itself wins. A light/dark switch (`data-aparte-theme`, or the system's colour scheme) re-themes
79
+ each chart in place, without drawing it again.
80
+
81
+ A dataset with no colour of its own is coloured by its series: `--aparte-primary` first, then a
82
+ fixed set of eight hues chosen to read on light and dark alike (blue, orange, aqua, yellow, magenta,
83
+ green, violet, red — `SERIES_HUES`). A hue the primary could be taken for is dropped, and each next
84
+ series is the first hue clearly apart from the one before it, under normal vision and under
85
+ simulated protanopia and deuteranopia. A series past the last hue is drawn in the muted text
86
+ colour rather than a recycled one: group such series ("Other") instead. `seriesPalette(primary)`
87
+ returns that list.
88
+
89
+ The same theming is a pure function, so you can check a config — or theme one for a chart of your
90
+ own — without a DOM:
91
+
92
+ ```ts
93
+ import { themeChartjsConfig, seriesPalette } from '@aparte/plugin-chartjs';
94
+
95
+ const config = { type: 'bar', data: { labels: ['Jan', 'Feb'], datasets: [{ data: [12, 19] }] } };
96
+ const themed = themeChartjsConfig(config, {
97
+ text: '#241f2b', muted: '#6d6479', border: '#e5ddce', surface: '#fffdf8',
98
+ background: '#f6f2ea', primary: '#b07d33', fontFamily: 'Inter, sans-serif',
99
+ });
100
+ seriesPalette('#b07d33'); // ['#b07d33', '#2a78d6', '#199e70', …]
101
+ ```
102
+
103
+ `ChartjsTokens` is the shape of that second argument.
104
+
105
+ ## Size
106
+
107
+ A chart fills the bubble's width, up to `40rem`, at a height of `18rem`. Set the height with the
108
+ `height` option, or with CSS on the custom properties the plugin reads:
109
+
110
+ ```css
111
+ .aparte-chartjs {
112
+ --aparte-chartjs-height: 22rem;
113
+ --aparte-chartjs-max-width: 48rem;
114
+ }
115
+ ```
116
+
117
+ A config that sets `aspectRatio` (held between 1:4 and 4:1) or `maintainAspectRatio: true` is as
118
+ tall as its width says instead. The plugin fits each chart to its frame itself, with one
119
+ `ResizeObserver` for all of them, and releases a chart (`chart.destroy()`) once it has left the
120
+ page — Chart.js' own `responsive` mode puts an observer on the whole document per chart and keeps a
121
+ chart taken off the page until it is destroyed. A chart whose message comes back later (a list
122
+ that virtualises its rows, a conversation reopened) is drawn again as soon as it has a size; the
123
+ last 32 released are watched for that. A config that says `responsive: false` keeps the size
124
+ Chart.js gives it.
125
+
126
+ ## Accessibility
127
+
128
+ A chart is a `figure` — the same shape as an `@aparte/plugin-echarts` chart — named by its title
129
+ (`options.plugins.title.text`), else "Chart" in the chat's language. In it, the canvas is
130
+ `role="img"` with the same name, and beside the canvas, visually hidden, is its data as a table — a
131
+ row per label, a column per dataset with data — for a screen reader. (Not inside the canvas as
132
+ fallback content: an image's children are presentational, so a screen reader would never reach a
133
+ table there.) The table stops at 50 dataset columns and 10 000 cells, whatever the config asks; a
134
+ last line, hidden too, says when it lists only part of the data. Under `prefers-reduced-motion`,
135
+ nothing animates. A chart still arriving never does, nor does the chart it settles into unless its
136
+ config asks for an animation — and no animation loops forever: `loop` is dropped from every
137
+ animation a config sets.
138
+
139
+ The words it draws read off the locale with defaults in ten languages; set any of them with
140
+ `extendLocale()`:
141
+
142
+ ```ts
143
+ aparteGlobalConfig.extendLocale({
144
+ chartjsChart: 'Figure', // the name of a chart with no title
145
+ chartjsError: 'This chart could not be drawn.', // the note over a fence that is not a chart
146
+ chartjsUnavailable: 'Chart not available', // a chart tool refused or failed
147
+ chartjsSeries: 'Series {n}', // a table column for a dataset with no label
148
+ chartjsTableCut: 'Only part of the data is listed.', // the table's last line, when it is cut
149
+ });
150
+ ```
151
+
152
+ ## Security
153
+
154
+ The config comes from a model or a tool, so it is treated as untrusted data:
155
+
156
+ - **Nothing in it becomes HTML.** Chart.js draws titles, labels and tooltips on the canvas. The
157
+ config reaches the page's markup once, as the escaped value of an attribute on the chart's
158
+ element (a fence hands core markup, not a node), and the data table is written with every value
159
+ escaped.
160
+ - **No code can arrive.** JSON carries no function, so no callback, scriptable option or tooltip
161
+ `external` handler can be passed — and where Chart.js CALLS what it finds, on every hover, a
162
+ string in its place goes: the tooltip's `external`, `filter`, `itemSort` and `callbacks`, the
163
+ legend labels' `generateLabels`, `filter` and `sort`, and a tooltip `position` other than
164
+ `average` or `nearest`. The config's own `plugins` list is dropped entirely: Chart.js runs each
165
+ entry's hooks, and an entry from JSON is an object with no function in it, so the list can do
166
+ nothing and is not handed over. Options for the plugins *you* registered
167
+ (`options.plugins.legend`, `.title`, `.tooltip`) are kept.
168
+ - **No image, no request.** A `pointStyle` is drawn as an image only when it is an
169
+ `HTMLImageElement` or a canvas, which only code can make. Keys Chart.js would call on such an
170
+ object (`toString`, `valueOf`) are dropped, as are `__proto__`, `prototype` and `constructor`.
171
+ - **Nothing the browser cannot allocate.** `options.devicePixelRatio` is dropped,
172
+ `options.aspectRatio` is held to 1:4–4:1, a scale's `ticks.count` and `ticks.maxTicksLimit` to
173
+ 100 (Chart.js makes as many ticks as `count` says), a chart may carry at most 5000 points — and
174
+ at most 5000 labels and 5000 datasets (`maxPoints` bounds all three) — and a locale `Intl`
175
+ refuses is dropped rather than left to throw on every tick.
176
+
177
+ A config Chart.js still refuses — a type your `Chart` has not registered, a time scale with no
178
+ date adapter — shows the note, and warns once in the console.
179
+
180
+ ## Options
181
+
182
+ `setupChartjs(options?, config?)` takes `ChartjsOptions`:
183
+
184
+ | option | default | |
185
+ | --- | --- | --- |
186
+ | `progressive` | `true` | `false` draws a chart once its fence has closed |
187
+ | `height` | `'18rem'` | the chart's height, as a CSS length |
188
+ | `tool` | — | tools whose result is drawn as a chart: a name, a RegExp, or a list |
189
+ | `map` | — | `(result, input) => config`, for a tool that returns its own data |
190
+ | `maxPoints` | `5000` | the most data points a chart may carry, all datasets together — and the most labels, and datasets |
191
+
192
+ `readChartConfig(value)` is the reader both paths use: the config copied and made harmless as
193
+ above, or `null` when it is not one Chart.js could draw. `ChartjsConfig` is its type.
194
+
195
+ ## Two entry points
196
+
197
+ `@aparte/plugin-chartjs` imports `chart.js/auto` — every chart type, scale and plugin registered —
198
+ on the first chart. To ship only what your charts use, register those parts on Chart.js' `Chart`
199
+ and hand it over through the entry that imports nothing from `chart.js`:
200
+
201
+ ```ts
202
+ import {
203
+ Chart, BarController, LineController, BarElement, LineElement, PointElement,
204
+ CategoryScale, LinearScale, Legend, Title, Tooltip,
205
+ } from 'chart.js';
206
+ import { setupChartjsWith } from '@aparte/plugin-chartjs/core';
207
+
208
+ Chart.register(
209
+ BarController, LineController, BarElement, LineElement, PointElement,
210
+ CategoryScale, LinearScale, Legend, Title, Tooltip,
211
+ );
212
+ setupChartjsWith(Chart, { tool: 'plot_sales' });
213
+ ```
214
+
215
+ `setupChartjsWith` takes the `Chart` class, or a `ChartjsLoader` — a function returning a promise
216
+ of it, or of a module carrying it (`() => import('chart.js/auto')`). Anything constructed like
217
+ `ChartjsConstructor` and returning a `ChartjsChart` (`options`, `data`, `update`, `resize`,
218
+ `destroy`) will do. A chart of a type you did not register shows the note. Both functions return a
219
+ disposer that unregisters the renderers and releases every chart drawn.
220
+
221
+ The plugin never touches `Chart.defaults`: other charts on your page are not the chat's, so each
222
+ chart gets the chat's look in its own config.
223
+
224
+ ESM only.
package/dist/core.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { type AparteConfig, type AparteToolMatcher } from '@aparte/core';
2
+ export { themeChartjsConfig, type ChartjsTokens } from './theme.js';
3
+ export { readChartConfig, type ChartjsConfig } from './source.js';
4
+ export { seriesPalette, SERIES_HUES } from './palette.js';
5
+ /**
6
+ * The part of a Chart.js chart this plugin calls. Structural, so this module imports
7
+ * nothing from `chart.js` — a bundle that hands over its own `Chart` carries one copy.
8
+ */
9
+ export interface ChartjsChart {
10
+ options: unknown;
11
+ data: unknown;
12
+ update(mode?: 'none'): void;
13
+ resize(width?: number, height?: number): void;
14
+ destroy(): void;
15
+ }
16
+ /** Chart.js' `Chart` class, or anything constructed the same way. */
17
+ export interface ChartjsConstructor {
18
+ new (canvas: HTMLCanvasElement, config: any): ChartjsChart;
19
+ }
20
+ /** A function that loads Chart.js on the first chart: the class, or a module carrying it. */
21
+ export type ChartjsLoader = () => Promise<ChartjsConstructor | {
22
+ Chart?: ChartjsConstructor;
23
+ default?: ChartjsConstructor;
24
+ }>;
25
+ export interface ChartjsOptions {
26
+ /**
27
+ * Redraw a chart while its fence arrives, from the part of its JSON that has arrived
28
+ * (default `true`). `false` draws it once the fence has closed.
29
+ */
30
+ progressive?: boolean;
31
+ /**
32
+ * The height of a chart, as a CSS length (default `18rem`). A config that sets `aspectRatio`, or
33
+ * `maintainAspectRatio: true`, is as tall as its width says instead.
34
+ */
35
+ height?: string;
36
+ /**
37
+ * Tools whose result is a Chart.js config, drawn as the chart in place of the tool's
38
+ * row: its `structuredContent`, else its text read as JSON. An exact name, a RegExp,
39
+ * or a list of them.
40
+ */
41
+ tool?: AparteToolMatcher | AparteToolMatcher[];
42
+ /**
43
+ * Turn a tool's own result into a Chart.js config — for a tool that returns data
44
+ * rather than a chart. Given the result (as `tool` reads it) and the call's input.
45
+ * The result is `any`, as in `@aparte/plugin-cards`: its shape is your tool's, and `map` is
46
+ * where you read it.
47
+ */
48
+ map?: (result: any, input: Record<string, unknown>) => unknown;
49
+ /** The most data points a chart may carry, all datasets together — and the most labels, and datasets (default 5000). */
50
+ maxPoints?: number;
51
+ }
52
+ /** The fence languages drawn as a chart. */
53
+ export declare const CHARTJS_LANGUAGES: readonly ["chartjs", "chart.js"];
54
+ /**
55
+ * Draw charts with a Chart.js you provide — its `Chart` class, or a function that loads
56
+ * it on the first chart. The entry point for a bundle that controls what it ships:
57
+ * `@aparte/plugin-chartjs` itself is this, with `() => import('chart.js/auto')`.
58
+ *
59
+ * Draws every ```` ```chartjs ```` (or ```` ```chart.js ````) fence whose body is a
60
+ * Chart.js config as JSON, and — with `options.tool` — the result of the tools named
61
+ * there. The chart takes the chat's colours and font wherever its config leaves them
62
+ * out (`themeChartjsConfig`), and follows a light/dark switch in place.
63
+ *
64
+ * @returns a disposer that unregisters the renderers, stops watching the theme and
65
+ * releases every chart drawn.
66
+ * @example
67
+ * import { Chart, BarController, BarElement, CategoryScale, LinearScale, Tooltip } from 'chart.js';
68
+ * import { setupChartjsWith } from '@aparte/plugin-chartjs/core';
69
+ * Chart.register(BarController, BarElement, CategoryScale, LinearScale, Tooltip);
70
+ * setupChartjsWith(Chart);
71
+ */
72
+ export declare function setupChartjsWith(chartjs: ChartjsConstructor | ChartjsLoader, options?: ChartjsOptions, config?: AparteConfig): () => void;
73
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAIH,KAAK,YAAY,EAGjB,KAAK,iBAAiB,EAEzB,MAAM,cAAc,CAAC;AAMtB,OAAO,EAAE,kBAAkB,EAAE,KAAK,aAAa,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE1D;;;GAGG;AACH,MAAM,WAAW,YAAY;IACzB,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;CACnB;AAED,qEAAqE;AACrE,MAAM,WAAW,kBAAkB;IAE/B,KAAK,MAAM,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,GAAG,YAAY,CAAC;CAC9D;AAED,6FAA6F;AAC7F,MAAM,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,kBAAkB,GAAG;IAAE,KAAK,CAAC,EAAE,kBAAkB,CAAC;IAAC,OAAO,CAAC,EAAE,kBAAkB,CAAA;CAAE,CAAC,CAAC;AAE7H,MAAM,WAAW,cAAc;IAC3B;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,IAAI,CAAC,EAAE,iBAAiB,GAAG,iBAAiB,EAAE,CAAC;IAC/C;;;;;OAKG;IAEH,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC;IAC/D,wHAAwH;IACxH,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,4CAA4C;AAC5C,eAAO,MAAM,iBAAiB,kCAAmC,CAAC;AA0ClE;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,gBAAgB,CAC5B,OAAO,EAAE,kBAAkB,GAAG,aAAa,EAC3C,OAAO,GAAE,cAAmB,EAC5B,MAAM,GAAE,YAAiC,GAC1C,MAAM,IAAI,CAWZ"}