@lightblues/jig 0.1.3 → 0.1.5
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 +2 -0
- package/dist/canvas/artifact/assets/katex.css +1 -0
- package/dist/canvas/artifact/assets/manifest.json +13 -0
- package/dist/canvas/artifact/assets/runtime.js +382 -0
- package/dist/canvas/artifact/css.d.ts +29 -0
- package/dist/canvas/artifact/css.js +159 -0
- package/dist/canvas/artifact/entry.d.ts +1 -0
- package/dist/canvas/artifact/entry.js +10 -0
- package/dist/canvas/artifact/icons.d.ts +13 -0
- package/dist/canvas/artifact/icons.js +67 -0
- package/dist/canvas/artifact/icons.json +1 -0
- package/dist/canvas/artifact/index.d.ts +54 -0
- package/dist/canvas/artifact/index.js +111 -0
- package/dist/canvas/artifact/instructions.d.ts +2 -0
- package/dist/canvas/artifact/instructions.js +16 -0
- package/dist/canvas/artifact/kit.d.ts +32 -0
- package/dist/canvas/artifact/kit.js +88 -0
- package/dist/canvas/artifact/modules.d.ts +3 -0
- package/dist/canvas/artifact/modules.js +33 -0
- package/dist/canvas/artifact/names.d.ts +6 -0
- package/dist/canvas/artifact/names.js +30 -0
- package/dist/canvas/artifact/ui.d.ts +76 -0
- package/dist/canvas/artifact/ui.js +156 -0
- package/dist/canvas/build.d.ts +14 -0
- package/dist/canvas/build.js +27 -0
- package/dist/canvas/compile.d.ts +8 -0
- package/dist/canvas/compile.js +19 -4
- package/dist/canvas/kit/blocks.d.ts +118 -0
- package/dist/canvas/kit/blocks.js +276 -0
- package/dist/canvas/kit/charts.d.ts +66 -0
- package/dist/canvas/kit/charts.js +319 -0
- package/dist/canvas/kit/context.d.ts +33 -0
- package/dist/canvas/kit/context.js +38 -0
- package/dist/canvas/kit/index.d.ts +25 -0
- package/dist/canvas/kit/index.js +44 -0
- package/dist/canvas/kit/theme.d.ts +88 -0
- package/dist/canvas/kit/theme.js +63 -0
- package/dist/canvas/kit/ui.d.ts +55 -0
- package/dist/canvas/kit/ui.js +100 -0
- package/dist/canvas/runtime.d.ts +6 -1
- package/dist/canvas/runtime.js +4 -3
- package/dist/markdown/mermaid.js +8 -4
- package/package.json +34 -2
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/** Size limits of the four blocks. Over a limit, the block is invalid (the 0.1.0 fallback: source + errors). */
|
|
2
|
+
export const KIT_BLOCK_LIMITS = {
|
|
3
|
+
title: 200,
|
|
4
|
+
caption: 500,
|
|
5
|
+
columns: 12,
|
|
6
|
+
header: 80,
|
|
7
|
+
rows: 200,
|
|
8
|
+
cell: 500,
|
|
9
|
+
stats: 12,
|
|
10
|
+
statValue: 40,
|
|
11
|
+
statLabel: 80,
|
|
12
|
+
statDetail: 160,
|
|
13
|
+
categories: 100,
|
|
14
|
+
category: 60,
|
|
15
|
+
series: 8,
|
|
16
|
+
seriesName: 60,
|
|
17
|
+
slices: 20,
|
|
18
|
+
referenceLines: 5,
|
|
19
|
+
affix: 8,
|
|
20
|
+
minHeight: 120,
|
|
21
|
+
maxHeight: 480,
|
|
22
|
+
calloutBody: 4000,
|
|
23
|
+
};
|
|
24
|
+
const L = KIT_BLOCK_LIMITS;
|
|
25
|
+
const TONES = ['success', 'danger', 'warning', 'info', 'neutral'];
|
|
26
|
+
const ALIGNS = ['left', 'center', 'right'];
|
|
27
|
+
/** A small strict reader: each check records `path: message` and returns a value or undefined. */
|
|
28
|
+
class Reader {
|
|
29
|
+
errors = [];
|
|
30
|
+
fail(path, msg) {
|
|
31
|
+
if (this.errors.length < 20)
|
|
32
|
+
this.errors.push(path ? `${path}: ${msg}` : msg);
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
obj(v, path, allowed) {
|
|
36
|
+
if (typeof v !== 'object' || v === null || Array.isArray(v))
|
|
37
|
+
return this.fail(path, 'expected a mapping');
|
|
38
|
+
const o = v;
|
|
39
|
+
for (const k of Object.keys(o))
|
|
40
|
+
if (!allowed.includes(k))
|
|
41
|
+
this.fail(path ? `${path}.${k}` : k, `unknown field (allowed: ${allowed.join(', ')})`);
|
|
42
|
+
return o;
|
|
43
|
+
}
|
|
44
|
+
/** A string; numbers are read as their text (YAML `2024` in a label). */
|
|
45
|
+
str(v, path, max, opts = {}) {
|
|
46
|
+
if (v === undefined || v === null)
|
|
47
|
+
return opts.required ? this.fail(path, 'required') : undefined;
|
|
48
|
+
if (typeof v === 'number' && Number.isFinite(v))
|
|
49
|
+
v = String(v);
|
|
50
|
+
if (typeof v !== 'string')
|
|
51
|
+
return this.fail(path, 'expected text');
|
|
52
|
+
if (v.length > max)
|
|
53
|
+
return this.fail(path, `longer than ${max} characters`);
|
|
54
|
+
if (opts.required && v.trim() === '')
|
|
55
|
+
return this.fail(path, 'must not be empty');
|
|
56
|
+
return v;
|
|
57
|
+
}
|
|
58
|
+
num(v, path, opts = {}) {
|
|
59
|
+
if (v === undefined || v === null)
|
|
60
|
+
return opts.required ? this.fail(path, 'required') : undefined;
|
|
61
|
+
if (typeof v !== 'number' || !Number.isFinite(v))
|
|
62
|
+
return this.fail(path, 'expected a number');
|
|
63
|
+
if (opts.min !== undefined && v < opts.min)
|
|
64
|
+
return this.fail(path, `must be at least ${opts.min}`);
|
|
65
|
+
if (opts.max !== undefined && v > opts.max)
|
|
66
|
+
return this.fail(path, `must be at most ${opts.max}`);
|
|
67
|
+
return v;
|
|
68
|
+
}
|
|
69
|
+
bool(v, path) {
|
|
70
|
+
if (v === undefined || v === null)
|
|
71
|
+
return undefined;
|
|
72
|
+
if (typeof v !== 'boolean')
|
|
73
|
+
return this.fail(path, 'expected true or false');
|
|
74
|
+
return v;
|
|
75
|
+
}
|
|
76
|
+
oneOf(v, path, options, required = false) {
|
|
77
|
+
if (v === undefined || v === null)
|
|
78
|
+
return required ? this.fail(path, `required (${options.join(', ')})`) : undefined;
|
|
79
|
+
if (typeof v !== 'string' || !options.includes(v))
|
|
80
|
+
return this.fail(path, `expected one of ${options.join(', ')}`);
|
|
81
|
+
return v;
|
|
82
|
+
}
|
|
83
|
+
list(v, path, min, max) {
|
|
84
|
+
if (v === undefined || v === null)
|
|
85
|
+
return min > 0 ? this.fail(path, 'required') : undefined;
|
|
86
|
+
if (!Array.isArray(v))
|
|
87
|
+
return this.fail(path, 'expected a list');
|
|
88
|
+
if (v.length < min)
|
|
89
|
+
return this.fail(path, `needs at least ${min} entr${min === 1 ? 'y' : 'ies'}`);
|
|
90
|
+
if (v.length > max)
|
|
91
|
+
return this.fail(path, `more than ${max} entries`);
|
|
92
|
+
return v;
|
|
93
|
+
}
|
|
94
|
+
done(value) {
|
|
95
|
+
return this.errors.length ? { ok: false, errors: this.errors } : { ok: true, value };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Drops keys whose value is undefined, so a value carries only what was written. */
|
|
99
|
+
function clean(o) {
|
|
100
|
+
for (const k of Object.keys(o))
|
|
101
|
+
if (o[k] === undefined)
|
|
102
|
+
delete o[k];
|
|
103
|
+
return o;
|
|
104
|
+
}
|
|
105
|
+
export function parseTable(raw) {
|
|
106
|
+
const r = new Reader();
|
|
107
|
+
const o = r.obj(raw, '', ['title', 'headers', 'rows', 'align', 'tone', 'caption']);
|
|
108
|
+
if (!o)
|
|
109
|
+
return r.done(null);
|
|
110
|
+
const headers = (r.list(o.headers, 'headers', 1, L.columns) ?? []).map((h, i) => r.str(h, `headers[${i}]`, L.header, { required: true }) ?? '');
|
|
111
|
+
const rows = (r.list(o.rows, 'rows', 0, L.rows) ?? []).map((row, i) => {
|
|
112
|
+
const cells = r.list(row, `rows[${i}]`, 0, Math.max(1, headers.length));
|
|
113
|
+
if (!cells)
|
|
114
|
+
return [];
|
|
115
|
+
const out = cells.map((c, j) => {
|
|
116
|
+
if (c === null || typeof c === 'boolean')
|
|
117
|
+
return c;
|
|
118
|
+
if (typeof c === 'number')
|
|
119
|
+
return Number.isFinite(c) ? c : (r.fail(`rows[${i}][${j}]`, 'not a finite number') ?? null);
|
|
120
|
+
if (typeof c === 'string')
|
|
121
|
+
return c.length > L.cell ? (r.fail(`rows[${i}][${j}]`, `longer than ${L.cell} characters`) ?? null) : c;
|
|
122
|
+
return r.fail(`rows[${i}][${j}]`, 'expected text, a number, true/false or null') ?? null;
|
|
123
|
+
});
|
|
124
|
+
while (out.length < headers.length)
|
|
125
|
+
out.push(null);
|
|
126
|
+
return out;
|
|
127
|
+
});
|
|
128
|
+
const align = r.list(o.align, 'align', 0, L.columns)?.map((a, i) => (a === null ? null : (r.oneOf(a, `align[${i}]`, ALIGNS) ?? null)));
|
|
129
|
+
const tone = r.list(o.tone, 'tone', 0, L.rows)?.map((a, i) => (a === null ? null : (r.oneOf(a, `tone[${i}]`, TONES) ?? null)));
|
|
130
|
+
return r.done(clean({ title: r.str(o.title, 'title', L.title), headers, rows, align, tone, caption: r.str(o.caption, 'caption', L.caption) }));
|
|
131
|
+
}
|
|
132
|
+
export function parseStats(raw) {
|
|
133
|
+
const r = new Reader();
|
|
134
|
+
let title;
|
|
135
|
+
let list = raw;
|
|
136
|
+
if (!Array.isArray(raw)) {
|
|
137
|
+
const o = r.obj(raw, '', ['title', 'items']);
|
|
138
|
+
if (!o)
|
|
139
|
+
return r.done(null);
|
|
140
|
+
title = r.str(o.title, 'title', L.title);
|
|
141
|
+
list = o.items;
|
|
142
|
+
}
|
|
143
|
+
const items = (r.list(list, Array.isArray(raw) ? '' : 'items', 1, L.stats) ?? []).map((it, i) => {
|
|
144
|
+
const p = Array.isArray(raw) ? `[${i}]` : `items[${i}]`;
|
|
145
|
+
const o = r.obj(it, p, ['value', 'label', 'tone', 'detail']);
|
|
146
|
+
if (!o)
|
|
147
|
+
return { value: '', label: '' };
|
|
148
|
+
let value;
|
|
149
|
+
if (typeof o.value === 'number')
|
|
150
|
+
value = r.num(o.value, `${p}.value`);
|
|
151
|
+
else
|
|
152
|
+
value = r.str(o.value, `${p}.value`, L.statValue, { required: true });
|
|
153
|
+
return clean({ value: value ?? '', label: r.str(o.label, `${p}.label`, L.statLabel, { required: true }) ?? '', tone: r.oneOf(o.tone, `${p}.tone`, TONES), detail: r.str(o.detail, `${p}.detail`, L.statDetail) });
|
|
154
|
+
});
|
|
155
|
+
return r.done(clean({ title, items }));
|
|
156
|
+
}
|
|
157
|
+
const AXIS_FIELDS = ['type', 'title', 'caption', 'height', 'categories', 'series', 'valuePrefix', 'valueSuffix', 'beginAtZero', 'yMin', 'yMax', 'referenceLines', 'showValues'];
|
|
158
|
+
const CHART_FIELDS = {
|
|
159
|
+
bar: [...AXIS_FIELDS, 'stacked', 'horizontal', 'normalized'],
|
|
160
|
+
line: [...AXIS_FIELDS, 'fill'],
|
|
161
|
+
pie: ['type', 'title', 'caption', 'height', 'data', 'donut'],
|
|
162
|
+
};
|
|
163
|
+
export function parseChart(raw) {
|
|
164
|
+
const r = new Reader();
|
|
165
|
+
const peek = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw.type : undefined;
|
|
166
|
+
const type = r.oneOf(peek, 'type', ['bar', 'line', 'pie'], true);
|
|
167
|
+
if (!type)
|
|
168
|
+
return r.done(null);
|
|
169
|
+
const o = r.obj(raw, '', CHART_FIELDS[type]);
|
|
170
|
+
if (!o)
|
|
171
|
+
return r.done(null);
|
|
172
|
+
const common = { title: r.str(o.title, 'title', L.title), caption: r.str(o.caption, 'caption', L.caption), height: r.num(o.height, 'height', { min: L.minHeight, max: L.maxHeight }) };
|
|
173
|
+
if (type === 'pie') {
|
|
174
|
+
const data = (r.list(o.data, 'data', 1, L.slices) ?? []).map((d, i) => {
|
|
175
|
+
const s = r.obj(d, `data[${i}]`, ['label', 'value', 'tone']);
|
|
176
|
+
if (!s)
|
|
177
|
+
return { label: '', value: 0 };
|
|
178
|
+
return clean({ label: r.str(s.label, `data[${i}].label`, L.category, { required: true }) ?? '', value: r.num(s.value, `data[${i}].value`, { required: true, min: 0 }) ?? 0, tone: r.oneOf(s.tone, `data[${i}].tone`, TONES) });
|
|
179
|
+
});
|
|
180
|
+
return r.done(clean({ type, ...common, data, donut: r.bool(o.donut, 'donut') }));
|
|
181
|
+
}
|
|
182
|
+
const categories = (r.list(o.categories, 'categories', 1, L.categories) ?? []).map((c, i) => r.str(c, `categories[${i}]`, L.category, { required: true }) ?? '');
|
|
183
|
+
const series = (r.list(o.series, 'series', 1, L.series) ?? []).map((s, i) => {
|
|
184
|
+
const so = r.obj(s, `series[${i}]`, ['name', 'data', 'tone']);
|
|
185
|
+
if (!so)
|
|
186
|
+
return { name: '', data: [] };
|
|
187
|
+
const data = (r.list(so.data, `series[${i}].data`, 1, L.categories) ?? []).map((v, j) => r.num(v, `series[${i}].data[${j}]`, { required: true }) ?? 0);
|
|
188
|
+
if (categories.length && data.length && data.length !== categories.length)
|
|
189
|
+
r.fail(`series[${i}].data`, `has ${data.length} values for ${categories.length} categories`);
|
|
190
|
+
return clean({ name: r.str(so.name, `series[${i}].name`, L.seriesName, { required: true }) ?? '', data, tone: r.oneOf(so.tone, `series[${i}].tone`, TONES) });
|
|
191
|
+
});
|
|
192
|
+
const referenceLines = r.list(o.referenceLines, 'referenceLines', 0, L.referenceLines)?.map((x, i) => {
|
|
193
|
+
const lo = r.obj(x, `referenceLines[${i}]`, ['value', 'label', 'tone']);
|
|
194
|
+
if (!lo)
|
|
195
|
+
return { value: 0 };
|
|
196
|
+
return clean({ value: r.num(lo.value, `referenceLines[${i}].value`, { required: true }) ?? 0, label: r.str(lo.label, `referenceLines[${i}].label`, L.category), tone: r.oneOf(lo.tone, `referenceLines[${i}].tone`, TONES) });
|
|
197
|
+
});
|
|
198
|
+
const yMin = r.num(o.yMin, 'yMin');
|
|
199
|
+
const yMax = r.num(o.yMax, 'yMax');
|
|
200
|
+
if (yMin !== undefined && yMax !== undefined && yMin >= yMax)
|
|
201
|
+
r.fail('yMax', 'must be greater than yMin');
|
|
202
|
+
const axis = {
|
|
203
|
+
...common, categories, series, referenceLines, yMin, yMax,
|
|
204
|
+
valuePrefix: r.str(o.valuePrefix, 'valuePrefix', L.affix), valueSuffix: r.str(o.valueSuffix, 'valueSuffix', L.affix),
|
|
205
|
+
beginAtZero: r.bool(o.beginAtZero, 'beginAtZero'), showValues: r.bool(o.showValues, 'showValues'),
|
|
206
|
+
};
|
|
207
|
+
if (type === 'line')
|
|
208
|
+
return r.done(clean({ type, ...axis, fill: r.bool(o.fill, 'fill') }));
|
|
209
|
+
return r.done(clean({ type, ...axis, stacked: r.bool(o.stacked, 'stacked'), horizontal: r.bool(o.horizontal, 'horizontal'), normalized: r.bool(o.normalized, 'normalized') }));
|
|
210
|
+
}
|
|
211
|
+
export function parseCallout(raw) {
|
|
212
|
+
const r = new Reader();
|
|
213
|
+
// A bare string is the body: ```callout\nRemember to save.\n```
|
|
214
|
+
if (typeof raw === 'string')
|
|
215
|
+
raw = { body: raw };
|
|
216
|
+
const o = r.obj(raw, '', ['tone', 'title', 'body']);
|
|
217
|
+
if (!o)
|
|
218
|
+
return r.done(null);
|
|
219
|
+
const v = clean({ tone: r.oneOf(o.tone, 'tone', TONES), title: r.str(o.title, 'title', L.title), body: r.str(o.body, 'body', L.calloutBody) });
|
|
220
|
+
if (!v.title && !v.body)
|
|
221
|
+
r.fail('', 'needs a title or a body');
|
|
222
|
+
return r.done(v);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* The four specs, to spread into `createMarkdown({ yaml, blocks: { ...kitBlocks, ...yours } })`. Markdown fields:
|
|
226
|
+
* `table.caption`, `chart.caption` (inline), `callout.body`.
|
|
227
|
+
*/
|
|
228
|
+
export const kitBlocks = {
|
|
229
|
+
table: { parse: parseTable, mdInline: ['caption'] },
|
|
230
|
+
stats: { parse: parseStats },
|
|
231
|
+
chart: { parse: parseChart, mdInline: ['caption'] },
|
|
232
|
+
callout: { parse: parseCallout, md: ['body'] },
|
|
233
|
+
};
|
|
234
|
+
/** Text for a host's system prompt: when and how to write the four blocks. Append your own blocks' text after it. */
|
|
235
|
+
export const KIT_BLOCKS_INSTRUCTIONS = `You can show data as blocks: a fenced code block whose language is the block name and whose body is YAML. Use them only for real data, keep the prose around them, and never put code in them.
|
|
236
|
+
|
|
237
|
+
\`\`\`table
|
|
238
|
+
title: Model comparison # optional
|
|
239
|
+
headers: [Model, Accuracy, Cost per 1k]
|
|
240
|
+
align: [left, right, right] # optional, per column
|
|
241
|
+
rows:
|
|
242
|
+
- [Small, 0.71, "$0.10"]
|
|
243
|
+
- [Large, 0.86, "$1.20"]
|
|
244
|
+
caption: Accuracy on the **dev** set. # optional, Markdown
|
|
245
|
+
\`\`\`
|
|
246
|
+
|
|
247
|
+
\`\`\`stats
|
|
248
|
+
- { value: "86%", label: Accuracy, tone: success, detail: "+4 pts" }
|
|
249
|
+
- { value: 1.2, label: Cost per 1k ($) }
|
|
250
|
+
\`\`\`
|
|
251
|
+
|
|
252
|
+
\`\`\`chart
|
|
253
|
+
type: bar # bar | line | pie
|
|
254
|
+
title: Revenue by quarter
|
|
255
|
+
categories: [Q1, Q2, Q3, Q4]
|
|
256
|
+
series:
|
|
257
|
+
- { name: "2025", data: [12, 15, 14, 18] }
|
|
258
|
+
- { name: "2026", data: [14, 17, 19, 22] }
|
|
259
|
+
valueSuffix: "k" # optional; also valuePrefix, stacked, horizontal (bar), fill (line)
|
|
260
|
+
\`\`\`
|
|
261
|
+
|
|
262
|
+
\`\`\`chart
|
|
263
|
+
type: pie
|
|
264
|
+
data:
|
|
265
|
+
- { label: Search, value: 46 }
|
|
266
|
+
- { label: Direct, value: 31 }
|
|
267
|
+
donut: true
|
|
268
|
+
\`\`\`
|
|
269
|
+
|
|
270
|
+
\`\`\`callout
|
|
271
|
+
tone: warning # info | success | warning | danger | neutral
|
|
272
|
+
title: Check before you run
|
|
273
|
+
body: The script **deletes** the old index.
|
|
274
|
+
\`\`\`
|
|
275
|
+
|
|
276
|
+
Rules: tone is one of success, danger, warning, info, neutral. Each series has one number per category. At most ${L.rows} table rows and ${L.columns} columns, ${L.stats} stats, ${L.series} series, ${L.categories} categories, ${L.slices} pie slices. Quote text that starts with a symbol or looks like a number you want kept as text.`;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type CSSProperties, type JSX } from 'react';
|
|
2
|
+
import { type Tone as ChartTone } from './theme.ts';
|
|
3
|
+
export type { Tone as ChartTone } from './theme.ts';
|
|
4
|
+
export type ChartDataPoint = {
|
|
5
|
+
label: string;
|
|
6
|
+
value: number;
|
|
7
|
+
};
|
|
8
|
+
export type ChartSeries = {
|
|
9
|
+
name: string;
|
|
10
|
+
data: number[];
|
|
11
|
+
tone?: ChartTone;
|
|
12
|
+
};
|
|
13
|
+
export type ChartReferenceLine = {
|
|
14
|
+
value: number;
|
|
15
|
+
label?: string;
|
|
16
|
+
tone?: ChartTone;
|
|
17
|
+
};
|
|
18
|
+
type ValueAxisProps = {
|
|
19
|
+
beginAtZero?: boolean;
|
|
20
|
+
yMin?: number;
|
|
21
|
+
yMax?: number;
|
|
22
|
+
referenceLines?: ChartReferenceLine[];
|
|
23
|
+
};
|
|
24
|
+
export type BarChartProps = ValueAxisProps & {
|
|
25
|
+
categories: string[];
|
|
26
|
+
series: ChartSeries[];
|
|
27
|
+
height?: number;
|
|
28
|
+
stacked?: boolean;
|
|
29
|
+
horizontal?: boolean;
|
|
30
|
+
normalized?: boolean;
|
|
31
|
+
valueSuffix?: string;
|
|
32
|
+
valuePrefix?: string;
|
|
33
|
+
showValues?: boolean;
|
|
34
|
+
style?: CSSProperties;
|
|
35
|
+
};
|
|
36
|
+
export type LineChartProps = ValueAxisProps & {
|
|
37
|
+
categories: string[];
|
|
38
|
+
series: ChartSeries[];
|
|
39
|
+
height?: number;
|
|
40
|
+
fill?: boolean;
|
|
41
|
+
valueSuffix?: string;
|
|
42
|
+
valuePrefix?: string;
|
|
43
|
+
showValues?: boolean;
|
|
44
|
+
showHoverGuide?: boolean;
|
|
45
|
+
style?: CSSProperties;
|
|
46
|
+
};
|
|
47
|
+
export type PieChartProps = {
|
|
48
|
+
data: Array<ChartDataPoint & {
|
|
49
|
+
tone?: ChartTone;
|
|
50
|
+
}>;
|
|
51
|
+
size?: number;
|
|
52
|
+
donut?: boolean;
|
|
53
|
+
style?: CSSProperties;
|
|
54
|
+
};
|
|
55
|
+
export declare function valueAxis(values: number[], options: ValueAxisProps & {
|
|
56
|
+
count?: number;
|
|
57
|
+
}): {
|
|
58
|
+
min: number;
|
|
59
|
+
max: number;
|
|
60
|
+
ticks: number[];
|
|
61
|
+
};
|
|
62
|
+
export declare function formatValue(value: number, prefix?: string, suffix?: string): string;
|
|
63
|
+
export declare function BarChart({ categories, series, height, stacked, horizontal, normalized, valueSuffix, valuePrefix, showValues, beginAtZero, yMin, yMax, referenceLines, style }: BarChartProps): JSX.Element;
|
|
64
|
+
export declare function LineChart({ categories, series, height, fill, valueSuffix, valuePrefix, showValues, showHoverGuide, beginAtZero, yMin, yMax, referenceLines, style }: LineChartProps): JSX.Element;
|
|
65
|
+
/** A pie or donut. It shrinks to its card (never wider than the slot) and stacks its legend below when narrow. */
|
|
66
|
+
export declare function PieChart({ data, size, donut, style }: PieChartProps): JSX.Element;
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
// Tier-A kit charts: inline SVG with the prop shapes of Cursor's `cursor/canvas` charts, copied from intake's kit
|
|
2
|
+
// (`charts.ts`). Changes: theme from `KitRoot`; width measured before paint and never wider than the slot; the pie
|
|
3
|
+
// shrinks to its card and puts its legend below on a phone; the tooltip fits narrow charts; non-hex host colours.
|
|
4
|
+
import { createElement as h, useLayoutEffect, useEffect, useRef, useState } from 'react';
|
|
5
|
+
import { mergeStyle, useKitTheme as useHostTheme } from "./context.js";
|
|
6
|
+
import { withAlpha } from "./theme.js";
|
|
7
|
+
const MONO_CHAR = 6.6;
|
|
8
|
+
const AXIS_FONT = 11;
|
|
9
|
+
const useBeforePaint = typeof window === 'undefined' ? useEffect : useLayoutEffect;
|
|
10
|
+
/** The element's width, read before the first paint (no flash at a guessed width), at least `min`. */
|
|
11
|
+
function useWidth(fallback, min = 160) {
|
|
12
|
+
const ref = useRef(null);
|
|
13
|
+
const [width, setWidth] = useState(fallback);
|
|
14
|
+
useBeforePaint(() => {
|
|
15
|
+
const el = ref.current;
|
|
16
|
+
if (!el)
|
|
17
|
+
return;
|
|
18
|
+
if (el.clientWidth)
|
|
19
|
+
setWidth(Math.max(min, el.clientWidth));
|
|
20
|
+
if (typeof ResizeObserver === 'undefined')
|
|
21
|
+
return;
|
|
22
|
+
const observer = new ResizeObserver((entries) => {
|
|
23
|
+
const next = entries[0]?.contentRect.width;
|
|
24
|
+
if (next)
|
|
25
|
+
setWidth(Math.max(min, Math.floor(next)));
|
|
26
|
+
});
|
|
27
|
+
observer.observe(el);
|
|
28
|
+
return () => observer.disconnect();
|
|
29
|
+
}, []);
|
|
30
|
+
return [ref, width];
|
|
31
|
+
}
|
|
32
|
+
function finite(value) {
|
|
33
|
+
return Number.isFinite(value) ? value : 0;
|
|
34
|
+
}
|
|
35
|
+
/** A round step near `range / count`: 1, 2, 2.5, or 5 times a power of ten. */
|
|
36
|
+
function niceStep(range, count) {
|
|
37
|
+
const raw = range / Math.max(1, count);
|
|
38
|
+
const magnitude = 10 ** Math.floor(Math.log10(raw));
|
|
39
|
+
const n = raw / magnitude;
|
|
40
|
+
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 2.5 ? 2.5 : n <= 5 ? 5 : 10) * magnitude;
|
|
41
|
+
}
|
|
42
|
+
export function valueAxis(values, options) {
|
|
43
|
+
const extra = (options.referenceLines ?? []).map((line) => line.value);
|
|
44
|
+
const all = [...values, ...extra].filter(Number.isFinite);
|
|
45
|
+
let lo = all.length ? Math.min(...all) : 0;
|
|
46
|
+
let hi = all.length ? Math.max(...all) : 1;
|
|
47
|
+
if (options.beginAtZero !== false) {
|
|
48
|
+
lo = Math.min(0, lo);
|
|
49
|
+
hi = Math.max(0, hi);
|
|
50
|
+
}
|
|
51
|
+
if (options.yMin != null)
|
|
52
|
+
lo = options.yMin;
|
|
53
|
+
if (options.yMax != null)
|
|
54
|
+
hi = options.yMax;
|
|
55
|
+
if (hi === lo) {
|
|
56
|
+
hi = lo + (Math.abs(lo) || 1);
|
|
57
|
+
if (options.beginAtZero === false)
|
|
58
|
+
lo -= Math.abs(lo) * 0.1 || 1;
|
|
59
|
+
}
|
|
60
|
+
const step = niceStep(hi - lo, options.count ?? 5);
|
|
61
|
+
const min = options.yMin ?? Math.floor(lo / step + 1e-9) * step;
|
|
62
|
+
const max = options.yMax ?? Math.ceil(hi / step - 1e-9) * step;
|
|
63
|
+
const ticks = [];
|
|
64
|
+
for (let v = Math.ceil(min / step - 1e-9) * step; v <= max + step * 1e-6; v += step)
|
|
65
|
+
ticks.push(Number(v.toPrecision(12)));
|
|
66
|
+
return { min, max: max === min ? min + step : max, ticks };
|
|
67
|
+
}
|
|
68
|
+
export function formatValue(value, prefix = '', suffix = '') {
|
|
69
|
+
const abs = Math.abs(value);
|
|
70
|
+
const text = abs >= 1e9 ? `${trim(value / 1e9)}B` : abs >= 1e6 ? `${trim(value / 1e6)}M` : abs >= 1e4 ? `${trim(value / 1e3)}k` : trim(value);
|
|
71
|
+
return `${prefix}${text}${suffix}`;
|
|
72
|
+
}
|
|
73
|
+
function trim(value) {
|
|
74
|
+
const digits = Math.abs(value) >= 100 ? 0 : Math.abs(value) >= 10 ? 1 : 2;
|
|
75
|
+
return String(Number(value.toFixed(digits)));
|
|
76
|
+
}
|
|
77
|
+
function seriesColor(t, series, index) {
|
|
78
|
+
return series.tone ? t.tone[series.tone] : t.chart.sequence[index % t.chart.sequence.length];
|
|
79
|
+
}
|
|
80
|
+
function Legend({ items }) {
|
|
81
|
+
const t = useHostTheme();
|
|
82
|
+
return h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '4px 14px', minWidth: 0, fontSize: 12, lineHeight: '16px', color: t.text.secondary } }, items.map((item, i) => h('span', { key: `${i}`, title: item.name, onMouseEnter: item.onEnter, onMouseLeave: item.onLeave, style: { display: 'inline-flex', alignItems: 'center', gap: 6, opacity: item.dim ? 0.45 : 1, cursor: item.onEnter ? 'default' : undefined, minWidth: 0, maxWidth: '100%' } }, h('span', { style: { width: 8, height: 8, borderRadius: 2, background: item.color, flex: 'none' } }), h('span', { style: { minWidth: 0, overflowWrap: 'anywhere' } }, item.name), item.extra ? h('span', { style: { color: t.text.tertiary, fontFamily: t.font.mono, fontSize: 11 } }, item.extra) : null)));
|
|
83
|
+
}
|
|
84
|
+
function Tooltip({ title, rows, x, width }) {
|
|
85
|
+
const t = useHostTheme();
|
|
86
|
+
const boxWidth = Math.min(180, width);
|
|
87
|
+
const left = Math.max(0, Math.min(width - boxWidth, x + 12 > width - boxWidth ? x - boxWidth - 12 : x + 12));
|
|
88
|
+
return h('div', {
|
|
89
|
+
role: 'tooltip',
|
|
90
|
+
style: { position: 'absolute', top: 4, left, width: boxWidth, pointerEvents: 'none', padding: '6px 8px', borderRadius: t.radius.md, background: t.bg.elevated, border: `1px solid ${t.stroke.secondary}`, fontSize: 12, lineHeight: '16px', color: t.text.primary, zIndex: 2 },
|
|
91
|
+
}, h('div', { style: { fontWeight: 650, marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, title), rows.map((row, i) => h('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 6 } }, h('span', { style: { width: 7, height: 7, borderRadius: 2, background: row.color, flex: 'none' } }), h('span', { style: { flex: 1, minWidth: 0, color: t.text.secondary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, row.name), h('span', { style: { fontFamily: t.font.mono, fontSize: 11 } }, row.value))));
|
|
92
|
+
}
|
|
93
|
+
function axisText(t, props, text) {
|
|
94
|
+
return h('text', { fill: t.text.tertiary, fontSize: AXIS_FONT, fontFamily: t.font.mono, ...props }, text);
|
|
95
|
+
}
|
|
96
|
+
function referenceMarks(t, lines, at, horizontal, extent) {
|
|
97
|
+
return (lines ?? []).map((line, i) => {
|
|
98
|
+
const color = line.tone ? t.tone[line.tone] : t.text.tertiary;
|
|
99
|
+
const pos = at(line.value);
|
|
100
|
+
const label = line.label ? h('text', {
|
|
101
|
+
x: horizontal ? pos + 4 : extent.end - 4, y: horizontal ? extent.start + 10 : pos - 4, textAnchor: horizontal ? 'start' : 'end',
|
|
102
|
+
fill: color, fontSize: 10, fontFamily: t.font.mono, paintOrder: 'stroke', stroke: t.bg.elevated, strokeWidth: 3,
|
|
103
|
+
}, line.label) : null;
|
|
104
|
+
const path = horizontal ? `M${pos} ${extent.start}V${extent.cross}` : `M${extent.start} ${pos}H${extent.end}`;
|
|
105
|
+
return h('g', { key: `ref${i}` }, h('path', { d: path, stroke: color, strokeWidth: 1.2, strokeDasharray: '4 3', fill: 'none' }), label);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
function labelStep(count, room, longest) {
|
|
109
|
+
const fit = Math.max(1, Math.floor(room / (longest * MONO_CHAR + 10)));
|
|
110
|
+
return Math.max(1, Math.ceil(count / fit));
|
|
111
|
+
}
|
|
112
|
+
function clip(label, chars) {
|
|
113
|
+
return label.length > chars ? `${label.slice(0, Math.max(1, chars - 1))}…` : label;
|
|
114
|
+
}
|
|
115
|
+
export function BarChart({ categories, series, height = 240, stacked = false, horizontal = false, normalized = false, valueSuffix = '', valuePrefix = '', showValues, beginAtZero, yMin, yMax, referenceLines, style }) {
|
|
116
|
+
const t = useHostTheme();
|
|
117
|
+
const [ref, width] = useWidth(560);
|
|
118
|
+
const [hover, setHover] = useState(null);
|
|
119
|
+
const stack = stacked || normalized;
|
|
120
|
+
const single = series.length === 1;
|
|
121
|
+
const colorOf = (s, c) => single && !series[0]?.tone ? seriesColor(t, {}, c) : seriesColor(t, series[s], s);
|
|
122
|
+
const totals = categories.map((_, c) => series.reduce((sum, s) => sum + Math.max(0, finite(s.data[c] ?? 0)), 0));
|
|
123
|
+
const valueAt = (s, c) => {
|
|
124
|
+
const raw = finite(series[s]?.data[c] ?? 0);
|
|
125
|
+
return normalized ? (totals[c] ? (Math.max(0, raw) / totals[c]) * 100 : 0) : raw;
|
|
126
|
+
};
|
|
127
|
+
const prefix = normalized ? '' : valuePrefix;
|
|
128
|
+
const suffix = normalized ? '%' : valueSuffix;
|
|
129
|
+
const values = stack ? categories.map((_, c) => series.reduce((sum, __, s) => sum + Math.max(0, valueAt(s, c)), 0)) : series.flatMap((s, i) => categories.map((_, c) => valueAt(i, c)));
|
|
130
|
+
const axis = stack ? valueAxis(normalized ? [0, 100] : values, { yMax: normalized ? 100 : undefined, referenceLines: normalized ? undefined : referenceLines }) : valueAxis(values, { beginAtZero, yMin, yMax, referenceLines });
|
|
131
|
+
const labels = showValues ?? (single && categories.length <= 8);
|
|
132
|
+
const showLabels = labels && !stack;
|
|
133
|
+
const tickWidth = Math.max(...axis.ticks.map((v) => formatValue(v, prefix, suffix).length)) * MONO_CHAR + 8;
|
|
134
|
+
const n = Math.max(1, categories.length);
|
|
135
|
+
let svg;
|
|
136
|
+
let tipX = 0;
|
|
137
|
+
if (!horizontal) {
|
|
138
|
+
const m = { top: showLabels ? 18 : 10, right: 8, bottom: 22, left: tickWidth };
|
|
139
|
+
const plotW = Math.max(40, width - m.left - m.right);
|
|
140
|
+
const plotH = Math.max(40, height - m.top - m.bottom);
|
|
141
|
+
const y = (v) => m.top + plotH - ((v - axis.min) / (axis.max - axis.min)) * plotH;
|
|
142
|
+
const band = plotW / n;
|
|
143
|
+
const inner = band * 0.72;
|
|
144
|
+
const step = labelStep(n, plotW, Math.min(14, Math.max(...categories.map((c) => c.length), 1)));
|
|
145
|
+
const zero = y(Math.max(axis.min, Math.min(axis.max, 0)));
|
|
146
|
+
const bars = [];
|
|
147
|
+
categories.forEach((_, c) => {
|
|
148
|
+
const x0 = m.left + c * band + (band - inner) / 2;
|
|
149
|
+
let base = 0;
|
|
150
|
+
series.forEach((s, i) => {
|
|
151
|
+
const v = valueAt(i, c);
|
|
152
|
+
const color = colorOf(i, c);
|
|
153
|
+
const dim = hover != null && hover !== c ? 0.55 : 1;
|
|
154
|
+
if (stack) {
|
|
155
|
+
const top = y(base + Math.max(0, v));
|
|
156
|
+
const bottom = y(base);
|
|
157
|
+
base += Math.max(0, v);
|
|
158
|
+
bars.push(h('rect', { key: `${c}-${i}`, x: x0, y: top, width: inner, height: Math.max(0, bottom - top), fill: color, opacity: dim }));
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
const w = inner / series.length;
|
|
162
|
+
const yv = y(v);
|
|
163
|
+
const x = x0 + i * w;
|
|
164
|
+
bars.push(h('rect', { key: `${c}-${i}`, x: x + 0.5, y: Math.min(yv, zero), width: Math.max(1, w - 1), height: Math.abs(zero - yv), rx: Math.min(2, w / 4), fill: color, opacity: dim }));
|
|
165
|
+
if (showLabels)
|
|
166
|
+
bars.push(axisText(t, { key: `l${c}-${i}`, x: x + w / 2, y: v >= 0 ? yv - 4 : yv + 12, textAnchor: 'middle', fill: t.text.secondary }, formatValue(v, prefix, suffix)));
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
tipX = hover == null ? 0 : m.left + hover * band + band / 2;
|
|
171
|
+
svg = h('svg', {
|
|
172
|
+
width, height, role: 'img', style: { display: 'block', overflow: 'visible' },
|
|
173
|
+
onMouseMove: (e) => {
|
|
174
|
+
const x = e.clientX - e.currentTarget.getBoundingClientRect().left - m.left;
|
|
175
|
+
setHover(x < 0 || x > plotW ? null : Math.min(n - 1, Math.floor(x / band)));
|
|
176
|
+
},
|
|
177
|
+
onMouseLeave: () => setHover(null),
|
|
178
|
+
}, axis.ticks.map((v) => h('g', { key: `t${v}` }, h('path', { d: `M${m.left} ${y(v)}H${m.left + plotW}`, stroke: v === 0 ? t.stroke.secondary : t.stroke.tertiary, strokeWidth: 1 }), axisText(t, { x: m.left - 6, y: y(v) + 3.5, textAnchor: 'end' }, formatValue(v, prefix, suffix)))), bars, categories.map((c, i) => i % step === 0 ? axisText(t, { key: `c${i}`, x: m.left + i * band + band / 2, y: height - 6, textAnchor: 'middle' }, clip(c, Math.max(3, Math.floor((band * step) / MONO_CHAR) - 1))) : null), referenceMarks(t, stack && normalized ? undefined : referenceLines, y, false, { start: m.left, end: m.left + plotW, cross: 0 }));
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
const longest = Math.min(22, Math.max(...categories.map((c) => c.length), 1));
|
|
182
|
+
const left = Math.min(width * 0.4, longest * MONO_CHAR + 10);
|
|
183
|
+
const rowH = Math.max(18, Math.min(34, (height - 28) / n));
|
|
184
|
+
const chartH = Math.max(height, rowH * n + 28);
|
|
185
|
+
const m = { top: 6, right: showLabels ? 48 : 12, bottom: 22, left };
|
|
186
|
+
const plotW = Math.max(40, width - m.left - m.right);
|
|
187
|
+
const x = (v) => m.left + ((v - axis.min) / (axis.max - axis.min)) * plotW;
|
|
188
|
+
const band = (chartH - m.top - m.bottom) / n;
|
|
189
|
+
const inner = band * 0.7;
|
|
190
|
+
const zero = x(Math.max(axis.min, Math.min(axis.max, 0)));
|
|
191
|
+
const bars = [];
|
|
192
|
+
categories.forEach((label, c) => {
|
|
193
|
+
const y0 = m.top + c * band + (band - inner) / 2;
|
|
194
|
+
let base = 0;
|
|
195
|
+
bars.push(axisText(t, { key: `c${c}`, x: m.left - 6, y: m.top + c * band + band / 2 + 3.5, textAnchor: 'end', fill: t.text.secondary }, clip(label, Math.floor((left - 10) / MONO_CHAR))));
|
|
196
|
+
series.forEach((s, i) => {
|
|
197
|
+
const v = valueAt(i, c);
|
|
198
|
+
const color = colorOf(i, c);
|
|
199
|
+
const dim = hover != null && hover !== c ? 0.55 : 1;
|
|
200
|
+
if (stack) {
|
|
201
|
+
const a = x(base);
|
|
202
|
+
base += Math.max(0, v);
|
|
203
|
+
bars.push(h('rect', { key: `${c}-${i}`, x: a, y: y0, width: Math.max(0, x(base) - a), height: inner, fill: color, opacity: dim }));
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
const hgt = inner / series.length;
|
|
207
|
+
const xv = x(v);
|
|
208
|
+
const y = y0 + i * hgt;
|
|
209
|
+
bars.push(h('rect', { key: `${c}-${i}`, x: Math.min(zero, xv), y: y + 0.5, width: Math.abs(xv - zero), height: Math.max(1, hgt - 1), rx: Math.min(2, hgt / 4), fill: color, opacity: dim }));
|
|
210
|
+
if (showLabels)
|
|
211
|
+
bars.push(axisText(t, { key: `l${c}-${i}`, x: Math.max(zero, xv) + 4, y: y + hgt / 2 + 3.5, fill: t.text.secondary }, formatValue(v, prefix, suffix)));
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
const step = labelStep(axis.ticks.length, plotW, tickWidth / MONO_CHAR);
|
|
216
|
+
svg = h('svg', {
|
|
217
|
+
width, height: chartH, role: 'img', style: { display: 'block', overflow: 'visible' },
|
|
218
|
+
onMouseMove: (e) => {
|
|
219
|
+
const yy = e.clientY - e.currentTarget.getBoundingClientRect().top - m.top;
|
|
220
|
+
setHover(yy < 0 || yy > band * n ? null : Math.min(n - 1, Math.floor(yy / band)));
|
|
221
|
+
},
|
|
222
|
+
onMouseLeave: () => setHover(null),
|
|
223
|
+
}, axis.ticks.map((v, i) => h('g', { key: `t${v}` }, h('path', { d: `M${x(v)} ${m.top}V${chartH - m.bottom}`, stroke: v === 0 ? t.stroke.secondary : t.stroke.tertiary, strokeWidth: 1 }), i % step === 0 ? axisText(t, { x: x(v), y: chartH - 6, textAnchor: 'middle' }, formatValue(v, prefix, suffix)) : null)), bars, referenceMarks(t, stack && normalized ? undefined : referenceLines, x, true, { start: m.top, end: 0, cross: chartH - m.bottom }));
|
|
224
|
+
tipX = width / 2;
|
|
225
|
+
}
|
|
226
|
+
const tip = hover == null ? null : h(Tooltip, {
|
|
227
|
+
title: categories[hover] ?? '',
|
|
228
|
+
x: tipX,
|
|
229
|
+
width,
|
|
230
|
+
rows: series.map((s, i) => ({ name: s.name, color: colorOf(i, hover), value: formatValue(valueAt(i, hover), prefix, suffix) })),
|
|
231
|
+
});
|
|
232
|
+
return h('div', { style: mergeStyle({ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }, style) }, series.length > 1 ? h(Legend, { items: series.map((s, i) => ({ name: s.name, color: seriesColor(t, s, i) })) }) : null, h('div', { ref, style: { position: 'relative', width: '100%', minWidth: 0, overflowX: 'clip' } }, svg, tip));
|
|
233
|
+
}
|
|
234
|
+
export function LineChart({ categories, series, height = 240, fill = false, valueSuffix = '', valuePrefix = '', showValues = false, showHoverGuide = true, beginAtZero, yMin, yMax, referenceLines, style }) {
|
|
235
|
+
const t = useHostTheme();
|
|
236
|
+
const [ref, width] = useWidth(560);
|
|
237
|
+
const [hover, setHover] = useState(null);
|
|
238
|
+
const axis = valueAxis(series.flatMap((s) => s.data.map(finite)), { beginAtZero, yMin, yMax, referenceLines });
|
|
239
|
+
const tickWidth = Math.max(...axis.ticks.map((v) => formatValue(v, valuePrefix, valueSuffix).length)) * MONO_CHAR + 8;
|
|
240
|
+
const n = Math.max(1, categories.length);
|
|
241
|
+
const labels = showValues && n <= 20;
|
|
242
|
+
const m = { top: labels ? 18 : 10, right: 12, bottom: 22, left: tickWidth };
|
|
243
|
+
const plotW = Math.max(40, width - m.left - m.right);
|
|
244
|
+
const plotH = Math.max(40, height - m.top - m.bottom);
|
|
245
|
+
const x = (i) => m.left + (n === 1 ? plotW / 2 : (i / (n - 1)) * plotW);
|
|
246
|
+
const y = (v) => m.top + plotH - ((Math.max(axis.min, Math.min(axis.max, v)) - axis.min) / (axis.max - axis.min)) * plotH;
|
|
247
|
+
const base = y(Math.max(axis.min, Math.min(axis.max, 0)));
|
|
248
|
+
// Edge labels are anchored start / end, so a label may take its full width beside a neighbour: leave one label of room.
|
|
249
|
+
const labelChars = Math.min(12, Math.max(...categories.map((c) => c.length), 1));
|
|
250
|
+
const step = labelStep(n, Math.max(1, plotW - labelChars * MONO_CHAR), labelChars);
|
|
251
|
+
const dots = n <= 40;
|
|
252
|
+
const lines = series.map((s, i) => {
|
|
253
|
+
const color = seriesColor(t, s, i);
|
|
254
|
+
const points = categories.map((_, c) => [x(c), y(finite(s.data[c] ?? 0))]);
|
|
255
|
+
const d = points.map(([px, py], c) => `${c ? 'L' : 'M'}${px.toFixed(1)} ${py.toFixed(1)}`).join('');
|
|
256
|
+
return h('g', { key: s.name || i }, fill && points.length ? h('path', { d: `${d}L${points.at(-1)[0].toFixed(1)} ${base}L${points[0][0].toFixed(1)} ${base}Z`, fill: withAlpha(color, 0.14), stroke: 'none' }) : null, h('path', { d, fill: 'none', stroke: color, strokeWidth: 1.8, strokeLinejoin: 'round', strokeLinecap: 'round' }), dots || hover != null ? points.map(([px, py], c) => (dots || c === hover) ? h('circle', { key: c, cx: px, cy: py, r: c === hover ? 4 : 2.4, fill: c === hover ? color : t.bg.elevated, stroke: color, strokeWidth: 1.5 }) : null) : null, labels ? points.map(([px, py], c) => axisText(t, { key: `v${c}`, x: px, y: py - 7, textAnchor: 'middle', fill: t.text.secondary }, formatValue(finite(s.data[c] ?? 0), valuePrefix, valueSuffix))) : null);
|
|
257
|
+
});
|
|
258
|
+
const svg = h('svg', {
|
|
259
|
+
width, height, role: 'img', style: { display: 'block', overflow: 'visible' },
|
|
260
|
+
onMouseMove: (e) => {
|
|
261
|
+
const px = e.clientX - e.currentTarget.getBoundingClientRect().left;
|
|
262
|
+
if (px < m.left - 8 || px > m.left + plotW + 8)
|
|
263
|
+
return setHover(null);
|
|
264
|
+
setHover(n === 1 ? 0 : Math.max(0, Math.min(n - 1, Math.round(((px - m.left) / plotW) * (n - 1)))));
|
|
265
|
+
},
|
|
266
|
+
onMouseLeave: () => setHover(null),
|
|
267
|
+
}, axis.ticks.map((v) => h('g', { key: `t${v}` }, h('path', { d: `M${m.left} ${y(v)}H${m.left + plotW}`, stroke: v === 0 ? t.stroke.secondary : t.stroke.tertiary, strokeWidth: 1 }), axisText(t, { x: m.left - 6, y: y(v) + 3.5, textAnchor: 'end' }, formatValue(v, valuePrefix, valueSuffix)))), categories.map((c, i) => i % step === 0 ? axisText(t, { key: `c${i}`, x: x(i), y: height - 6, textAnchor: n > 1 && i === 0 ? 'start' : n > 1 && i === n - 1 ? 'end' : 'middle' }, clip(c, labelChars)) : null), referenceMarks(t, referenceLines, y, false, { start: m.left, end: m.left + plotW, cross: 0 }), showHoverGuide && hover != null ? h('path', { d: `M${x(hover)} ${m.top}V${m.top + plotH}`, stroke: t.stroke.primary, strokeWidth: 1 }) : null, lines);
|
|
268
|
+
const tip = hover == null ? null : h(Tooltip, {
|
|
269
|
+
title: categories[hover] ?? '',
|
|
270
|
+
x: x(hover),
|
|
271
|
+
width,
|
|
272
|
+
rows: series.map((s, i) => ({ name: s.name, color: seriesColor(t, s, i), value: formatValue(finite(s.data[hover] ?? 0), valuePrefix, valueSuffix) })),
|
|
273
|
+
});
|
|
274
|
+
return h('div', { style: mergeStyle({ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }, style) }, series.length > 1 ? h(Legend, { items: series.map((s, i) => ({ name: s.name, color: seriesColor(t, s, i) })) }) : null, h('div', { ref, style: { position: 'relative', width: '100%', minWidth: 0, overflowX: 'clip' } }, svg, tip));
|
|
275
|
+
}
|
|
276
|
+
function arc(cx, cy, r, inner, start, end) {
|
|
277
|
+
const sweep = end - start;
|
|
278
|
+
if (sweep >= Math.PI * 2 - 1e-6) {
|
|
279
|
+
const outer = `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${2 * r} 0a${r} ${r} 0 1 0 ${-2 * r} 0`;
|
|
280
|
+
return inner > 0 ? `${outer}M${cx - inner} ${cy}a${inner} ${inner} 0 1 1 ${2 * inner} 0a${inner} ${inner} 0 1 1 ${-2 * inner} 0` : outer;
|
|
281
|
+
}
|
|
282
|
+
const large = sweep > Math.PI ? 1 : 0;
|
|
283
|
+
const p = (radius, angle) => `${(cx + radius * Math.sin(angle)).toFixed(2)} ${(cy - radius * Math.cos(angle)).toFixed(2)}`;
|
|
284
|
+
if (inner <= 0)
|
|
285
|
+
return `M${cx} ${cy}L${p(r, start)}A${r} ${r} 0 ${large} 1 ${p(r, end)}Z`;
|
|
286
|
+
return `M${p(r, start)}A${r} ${r} 0 ${large} 1 ${p(r, end)}L${p(inner, end)}A${inner} ${inner} 0 ${large} 0 ${p(inner, start)}Z`;
|
|
287
|
+
}
|
|
288
|
+
/** A pie or donut. It shrinks to its card (never wider than the slot) and stacks its legend below when narrow. */
|
|
289
|
+
export function PieChart({ data, size = 200, donut = false, style }) {
|
|
290
|
+
const t = useHostTheme();
|
|
291
|
+
const [ref, width] = useWidth(size + 16, 80);
|
|
292
|
+
const [hover, setHover] = useState(null);
|
|
293
|
+
const values = data.map((d) => Math.max(0, finite(d.value)));
|
|
294
|
+
const total = values.reduce((a, b) => a + b, 0);
|
|
295
|
+
const colors = data.map((d, i) => seriesColor(t, d, i));
|
|
296
|
+
const pad = 8;
|
|
297
|
+
// Side by side needs the pie plus a 140 px legend and the gap; otherwise the legend goes below and the pie takes the width.
|
|
298
|
+
const side = width >= size + pad * 2 + 20 + 140;
|
|
299
|
+
const drawn = Math.max(64, Math.min(size, width - pad * 2));
|
|
300
|
+
const r = drawn / 2;
|
|
301
|
+
const c = r + pad;
|
|
302
|
+
const inner = donut ? r * 0.6 : 0;
|
|
303
|
+
let angle = 0;
|
|
304
|
+
const slices = data.map((d, i) => {
|
|
305
|
+
const sweep = total ? (values[i] / total) * Math.PI * 2 : 0;
|
|
306
|
+
const start = angle;
|
|
307
|
+
angle += sweep;
|
|
308
|
+
const mid = start + sweep / 2;
|
|
309
|
+
const out = hover === i ? Math.min(6, pad - 1) : 0;
|
|
310
|
+
return h('path', {
|
|
311
|
+
key: `${d.label}${i}`, d: arc(c + out * Math.sin(mid), c - out * Math.cos(mid), r, inner, start, start + sweep), fill: colors[i],
|
|
312
|
+
stroke: t.bg.elevated, strokeWidth: data.length > 1 ? 1.5 : 0, opacity: hover != null && hover !== i ? 0.45 : 1,
|
|
313
|
+
onMouseEnter: () => setHover(i), onMouseLeave: () => setHover(null), style: { transition: 'opacity 120ms' },
|
|
314
|
+
}, h('title', null, `${d.label}: ${formatValue(values[i])} (${pct(i)})`));
|
|
315
|
+
});
|
|
316
|
+
function pct(i) { return total ? `${Math.round((values[i] / total) * 1000) / 10}%` : '0%'; }
|
|
317
|
+
const focus = hover == null ? null : data[hover];
|
|
318
|
+
return h('div', { ref, style: mergeStyle({ display: 'flex', flexDirection: side ? 'row' : 'column', alignItems: side ? 'center' : 'stretch', gap: side ? 20 : 8, minWidth: 0, maxWidth: '100%' }, style) }, h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flex: 'none', minWidth: 0 } }, h('svg', { width: drawn + pad * 2, height: drawn + pad * 2, viewBox: `0 0 ${drawn + pad * 2} ${drawn + pad * 2}`, role: 'img', style: { display: 'block', maxWidth: '100%', height: 'auto' } }, slices, donut ? h('text', { x: c, y: c - 2, textAnchor: 'middle', fill: t.text.primary, fontFamily: t.font.heading, fontSize: Math.max(12, drawn / 9), fontWeight: 620 }, formatValue(focus ? values[hover] : total)) : null, donut ? h('text', { x: c, y: c + 14, textAnchor: 'middle', fill: t.text.tertiary, fontSize: 11 }, focus ? clip(focus.label, Math.floor((inner * 2) / 6.5)) : 'Total') : null), h('div', { style: { minHeight: 16, maxWidth: '100%', fontSize: 12, color: t.text.secondary, fontFamily: t.font.mono, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, focus ? `${focus.label} · ${formatValue(values[hover])} · ${pct(hover)}` : '')), h('div', { style: { flex: side ? 1 : 'none', minWidth: 0 } }, h(Legend, { items: data.map((d, i) => ({ name: d.label, color: colors[i], dim: hover != null && hover !== i, extra: pct(i), onEnter: () => setHover(i), onLeave: () => setHover(null) })) })));
|
|
319
|
+
}
|