@chartpng/render 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/LICENSE +21 -0
- package/README.md +165 -2
- package/SECURITY.md +34 -0
- package/THIRD_PARTY_NOTICES.md +253 -0
- package/bin/chartpng-render.js +2 -0
- package/dist/packages/render/cli.d.ts +1 -0
- package/dist/packages/render/cli.js +88 -0
- package/dist/packages/render/index.d.ts +61 -0
- package/dist/packages/render/index.js +79 -0
- package/dist/src/fonts/plex.d.ts +2 -0
- package/dist/src/fonts/plex.js +9 -0
- package/dist/src/lib/errors.d.ts +4 -0
- package/dist/src/lib/errors.js +9 -0
- package/dist/src/lib/maker.d.ts +90 -0
- package/dist/src/lib/maker.js +297 -0
- package/dist/src/lib/presets.d.ts +61 -0
- package/dist/src/lib/presets.js +576 -0
- package/dist/src/lib/render.d.ts +38 -0
- package/dist/src/lib/render.js +738 -0
- package/dist/src/lib/repair.d.ts +8 -0
- package/dist/src/lib/repair.js +598 -0
- package/dist/src/lib/style.d.ts +23 -0
- package/dist/src/lib/style.js +110 -0
- package/dist/src/lib/table-chart.d.ts +133 -0
- package/dist/src/lib/table-chart.js +624 -0
- package/dist/src/lib/theme.d.ts +37 -0
- package/dist/src/lib/theme.js +288 -0
- package/package.json +51 -3
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
import { addRoundedRectPath } from 'chart.js/helpers';
|
|
2
|
+
import { applyTheme, FONT_STACK, inkFor, isDark, resolvePalette, underlay } from './theme.js';
|
|
3
|
+
import { RenderError } from './errors.js';
|
|
4
|
+
export const PRESET_NAMES = ['kpi', 'ranking', 'comparison', 'funnel', 'gauge'];
|
|
5
|
+
const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
6
|
+
// Green and red for a change, muted so they hold on white and on near-black.
|
|
7
|
+
// Text on its own background is at least 4.5:1; a chip carries its own fill.
|
|
8
|
+
export const TONES = {
|
|
9
|
+
light: {
|
|
10
|
+
up: { text: '#1c7048', fill: '#e1f0e8' },
|
|
11
|
+
down: { text: '#a3342a', fill: '#f7e2df' },
|
|
12
|
+
flat: { text: '#5b5d63', fill: '#ecebe6' },
|
|
13
|
+
muted: '#c3cfdd',
|
|
14
|
+
previous: '#b3b7bf',
|
|
15
|
+
},
|
|
16
|
+
dark: {
|
|
17
|
+
up: { text: '#6cd0a0', fill: '#1c3a2d' },
|
|
18
|
+
down: { text: '#f29a8e', fill: '#44211e' },
|
|
19
|
+
flat: { text: '#a2a39d', fill: '#2c2e33' },
|
|
20
|
+
muted: '#3f5068',
|
|
21
|
+
previous: '#6d717a',
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
// A number from a JSON value, or null: nulls, text and Infinity are not data.
|
|
25
|
+
function num(value) {
|
|
26
|
+
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
|
|
27
|
+
return Number.isFinite(n) ? n : null;
|
|
28
|
+
}
|
|
29
|
+
// Percent change from base to current. Measured against |base| so a rise from -10
|
|
30
|
+
// to -5 reads as +50%. No base (zero, missing, not a number) means no change.
|
|
31
|
+
export function variation(current, base) {
|
|
32
|
+
const c = num(current);
|
|
33
|
+
const b = num(base);
|
|
34
|
+
if (c === null || b === null || b === 0)
|
|
35
|
+
return null;
|
|
36
|
+
const change = ((c - b) / Math.abs(b)) * 100;
|
|
37
|
+
return Number.isFinite(change) ? change : null;
|
|
38
|
+
}
|
|
39
|
+
// '↑ 12.4%', '↓ 3.1%' or '0.0%'. compact: '+12%', for crowded charts.
|
|
40
|
+
export function formatChange(change, compact = false) {
|
|
41
|
+
const rounded = Math.round(Math.abs(change) * (compact ? 1 : 10)) / (compact ? 1 : 10);
|
|
42
|
+
const direction = rounded === 0 ? 'flat' : change > 0 ? 'up' : 'down';
|
|
43
|
+
const digits = compact ? 0 : 1;
|
|
44
|
+
const amount = rounded.toLocaleString('en', { minimumFractionDigits: digits, maximumFractionDigits: digits });
|
|
45
|
+
if (compact)
|
|
46
|
+
return { text: direction === 'flat' ? '0%' : `${direction === 'up' ? '+' : '-'}${amount}%`, direction };
|
|
47
|
+
return { text: direction === 'flat' ? `${amount}%` : `${direction === 'up' ? '↑' : '↓'} ${amount}%`, direction };
|
|
48
|
+
}
|
|
49
|
+
const text = (value) => (typeof value === 'string' ? value.slice(0, 16) : '');
|
|
50
|
+
// 1234.5 with a prefix and suffix: '$1,234.5k'. The sign goes first: '-$5'.
|
|
51
|
+
function figure(n, prefix, suffix) {
|
|
52
|
+
return `${n < 0 ? '-' : ''}${prefix}${Math.abs(n).toLocaleString('en')}${suffix}`;
|
|
53
|
+
}
|
|
54
|
+
// What the kpi shows: the last number of a series and its change against `previous`,
|
|
55
|
+
// or against the first number when there is no previous.
|
|
56
|
+
export function kpiFigures(values, previous) {
|
|
57
|
+
const numbers = (Array.isArray(values) ? values : []).map(num);
|
|
58
|
+
const last = numbers.findLastIndex((n) => n !== null);
|
|
59
|
+
if (last < 0)
|
|
60
|
+
return { value: null, change: null };
|
|
61
|
+
const first = numbers.findIndex((n) => n !== null);
|
|
62
|
+
const base = num(previous) ?? (first < last ? numbers[first] : null);
|
|
63
|
+
return { value: numbers[last], change: variation(numbers[last], base) };
|
|
64
|
+
}
|
|
65
|
+
// Two families share the name `preset`, with no name in common. A report preset (above) is a
|
|
66
|
+
// layout for what the chart says. An output preset says where the image is going: it sets the
|
|
67
|
+
// size, pixel ratio and background the request did not, roomier margins and a type floor of 11 px.
|
|
68
|
+
// One request can have one of each, comma-separated: preset=ranking,email.
|
|
69
|
+
export const OUTPUT_PRESET_NAMES = ['email', 'slack'];
|
|
70
|
+
// Reads the preset setting. Always checked, even under theme: false, so a typo is never silent.
|
|
71
|
+
// A string of one or two names; at most one of each family.
|
|
72
|
+
export function readPresets(value) {
|
|
73
|
+
if (value == null)
|
|
74
|
+
return {};
|
|
75
|
+
const valid = [...PRESET_NAMES, ...OUTPUT_PRESET_NAMES];
|
|
76
|
+
const found = {};
|
|
77
|
+
for (const name of typeof value === 'string' ? value.split(',').map((part) => part.trim()) : [value]) {
|
|
78
|
+
if (typeof name !== 'string' || !valid.includes(name)) {
|
|
79
|
+
throw new RenderError(`unknown preset ${JSON.stringify(String(name).slice(0, 40))}; valid presets: ${valid.join(', ')}`, 'bad_preset');
|
|
80
|
+
}
|
|
81
|
+
const family = OUTPUT_PRESET_NAMES.includes(name) ? 'output' : 'report';
|
|
82
|
+
if (found[family])
|
|
83
|
+
throw new RenderError(`preset takes at most one of ${family === 'output' ? OUTPUT_PRESET_NAMES.join(', ') : PRESET_NAMES.join(', ')}`, 'bad_preset');
|
|
84
|
+
Object.assign(found, { [family]: name });
|
|
85
|
+
}
|
|
86
|
+
return found;
|
|
87
|
+
}
|
|
88
|
+
// The most stages a funnel draws: past this the rows are too thin to read.
|
|
89
|
+
export const FUNNEL_MAX_STAGES = 12;
|
|
90
|
+
function checkShape(preset, config, settings) {
|
|
91
|
+
const count = Array.isArray(config.data?.datasets) ? config.data.datasets.length : 0;
|
|
92
|
+
const fail = (why) => {
|
|
93
|
+
throw new RenderError(`preset ${preset} ${why}`, 'bad_preset');
|
|
94
|
+
};
|
|
95
|
+
if (preset === 'kpi' && config.type !== 'line' && config.type !== 'bar')
|
|
96
|
+
fail('needs type line or bar');
|
|
97
|
+
if (preset === 'kpi' && count > 1)
|
|
98
|
+
fail('takes one dataset');
|
|
99
|
+
if (preset === 'ranking' && config.type !== 'bar')
|
|
100
|
+
fail('needs type bar');
|
|
101
|
+
if (preset === 'comparison' && config.type !== 'line' && config.type !== 'bar')
|
|
102
|
+
fail('needs type line or bar');
|
|
103
|
+
if (preset === 'comparison' && count > 0 && count !== 2)
|
|
104
|
+
fail('takes two datasets: the current period first, then the previous one');
|
|
105
|
+
if (preset === 'funnel') {
|
|
106
|
+
if (config.type !== 'bar')
|
|
107
|
+
fail('needs type bar');
|
|
108
|
+
if (count !== 1)
|
|
109
|
+
fail('takes one dataset: the value of each stage, from the first stage to the last');
|
|
110
|
+
const values = config.data.datasets[0]?.data;
|
|
111
|
+
if (!Array.isArray(values))
|
|
112
|
+
fail('needs data.datasets[0].data to be a list of numbers, one per stage');
|
|
113
|
+
const stages = values;
|
|
114
|
+
if (stages.length === 0)
|
|
115
|
+
fail('needs at least one stage');
|
|
116
|
+
if (stages.length > FUNNEL_MAX_STAGES)
|
|
117
|
+
fail(`takes at most ${FUNNEL_MAX_STAGES} stages, got ${stages.length}`);
|
|
118
|
+
const negative = stages.findIndex((v) => (num(v) ?? 0) < 0);
|
|
119
|
+
if (negative >= 0)
|
|
120
|
+
fail(`needs stage values of zero or more; stage ${negative + 1} is negative`);
|
|
121
|
+
}
|
|
122
|
+
if (preset === 'gauge') {
|
|
123
|
+
if (config.type !== 'doughnut')
|
|
124
|
+
fail('needs type doughnut');
|
|
125
|
+
if (count !== 1)
|
|
126
|
+
fail('takes one dataset with the value as its first number');
|
|
127
|
+
const values = config.data.datasets[0]?.data;
|
|
128
|
+
if (!Array.isArray(values) || num(values.find((v) => num(v) !== null)) === null)
|
|
129
|
+
fail('needs a number in data.datasets[0].data: the value to show');
|
|
130
|
+
if (settings.max != null && !((num(settings.max) ?? 0) > 0))
|
|
131
|
+
fail('needs max to be a number above 0, the value that fills the gauge');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// Where the kpi block sits, measured from the top of the image.
|
|
135
|
+
const KPI = { top: 14, size: 36, label: 21, sublabel: 18, gap: 14, chipHeight: 22, chipGap: 10 };
|
|
136
|
+
const capHeight = (size) => size * 0.7;
|
|
137
|
+
function kpiPadding(hasLabel, hasSublabel) {
|
|
138
|
+
return Math.ceil(KPI.top + (hasLabel ? KPI.label : 0) + (hasSublabel ? KPI.sublabel : 0) + capHeight(KPI.size) + KPI.gap);
|
|
139
|
+
}
|
|
140
|
+
function kpiOptions(hasLabel, hasSublabel) {
|
|
141
|
+
return {
|
|
142
|
+
layout: { padding: { top: kpiPadding(hasLabel, hasSublabel), right: 16, bottom: 8, left: 16 } },
|
|
143
|
+
plugins: { legend: { display: false } },
|
|
144
|
+
scales: { x: { display: false }, y: { display: false, grace: '12%' } },
|
|
145
|
+
elements: { line: { borderWidth: 2 } },
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// Per-bar styles that must follow their bar when the bars are reordered.
|
|
149
|
+
const PER_BAR_KEYS = ['backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'borderSkipped', 'hoverBackgroundColor', 'hoverBorderColor', 'hoverBorderWidth', 'inflateAmount', 'base', 'pointStyle'];
|
|
150
|
+
// Biggest first. Labels and every dataset follow the first dataset's order, so a
|
|
151
|
+
// label keeps its values. Entries that are not numbers go last, in their order.
|
|
152
|
+
function rankedData(data, tone, highlight) {
|
|
153
|
+
const datasets = Array.isArray(data.datasets) ? data.datasets : [];
|
|
154
|
+
const first = datasets[0];
|
|
155
|
+
if (!isObject(first) || !Array.isArray(first.data))
|
|
156
|
+
return data;
|
|
157
|
+
const values = first.data.map(num);
|
|
158
|
+
const order = values.map((_, i) => i).sort((a, b) => (values[b] ?? -Infinity) - (values[a] ?? -Infinity) || a - b);
|
|
159
|
+
const pick = (list) => order.map((i) => list[i] ?? null);
|
|
160
|
+
const colors = order.map((_, rank) => (rank === 0 ? highlight : tone.muted));
|
|
161
|
+
return {
|
|
162
|
+
...data,
|
|
163
|
+
...(Array.isArray(data.labels) && { labels: order.map((i) => data.labels[i] ?? '') }),
|
|
164
|
+
datasets: datasets.map((dataset, i) => {
|
|
165
|
+
if (!isObject(dataset) || !Array.isArray(dataset.data))
|
|
166
|
+
return dataset;
|
|
167
|
+
const styled = i !== 0 || dataset.backgroundColor != null || dataset.borderColor != null;
|
|
168
|
+
const reordered = { data: pick(dataset.data) };
|
|
169
|
+
for (const key of PER_BAR_KEYS)
|
|
170
|
+
if (Array.isArray(dataset[key]))
|
|
171
|
+
reordered[key] = pick(dataset[key]);
|
|
172
|
+
return { ...(!styled && { backgroundColor: colors, borderColor: colors }), ...dataset, ...reordered };
|
|
173
|
+
}),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function rankingOptions(user) {
|
|
177
|
+
const valueAxis = (user.indexAxis ?? 'y') === 'y' ? 'x' : 'y';
|
|
178
|
+
const categoryAxis = valueAxis === 'x' ? 'y' : 'x';
|
|
179
|
+
return {
|
|
180
|
+
indexAxis: 'y',
|
|
181
|
+
// grace leaves room after the longest bar for its value; every label stays, none is skipped.
|
|
182
|
+
scales: { [valueAxis]: { grid: { display: false }, grace: '16%' }, [categoryAxis]: { ticks: { autoSkip: false } } },
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
// The first dataset is the current period, the second the previous one in grey.
|
|
186
|
+
function comparisonData(data, type, tone) {
|
|
187
|
+
const datasets = Array.isArray(data.datasets) ? data.datasets : [];
|
|
188
|
+
return {
|
|
189
|
+
...data,
|
|
190
|
+
datasets: datasets.map((dataset, i) => {
|
|
191
|
+
if (!isObject(dataset))
|
|
192
|
+
return dataset;
|
|
193
|
+
const label = i === 0 ? 'Current' : 'Previous';
|
|
194
|
+
if (i !== 1 || dataset.backgroundColor != null || dataset.borderColor != null)
|
|
195
|
+
return { label, ...dataset };
|
|
196
|
+
const grey = { backgroundColor: tone.previous, borderColor: tone.previous };
|
|
197
|
+
return type === 'line'
|
|
198
|
+
? { label, ...grey, borderDash: [6, 4], borderWidth: 2, pointRadius: 0, fill: false, ...dataset }
|
|
199
|
+
: { label, ...grey, ...dataset };
|
|
200
|
+
}),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function comparisonOptions(type, user) {
|
|
204
|
+
const horizontal = type === 'bar' && user.indexAxis === 'y';
|
|
205
|
+
return {
|
|
206
|
+
plugins: { legend: { display: true } },
|
|
207
|
+
// Room after the longest bar for its change.
|
|
208
|
+
...(horizontal && { scales: { x: { grace: '18%' } } }),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
// The funnel is one set of floating bars, each centred on zero and as wide as its value,
|
|
212
|
+
// so the widths are proportional and Chart.js draws them. A stage that is not a number
|
|
213
|
+
// has no bar.
|
|
214
|
+
function funnelData(data, accent) {
|
|
215
|
+
const datasets = Array.isArray(data.datasets) ? data.datasets : [];
|
|
216
|
+
const [first, ...rest] = datasets;
|
|
217
|
+
if (!isObject(first) || !Array.isArray(first.data))
|
|
218
|
+
return data;
|
|
219
|
+
const bars = first.data.map((v) => {
|
|
220
|
+
const n = num(v);
|
|
221
|
+
return n === null ? null : [-n / 2, n / 2];
|
|
222
|
+
});
|
|
223
|
+
const styled = { backgroundColor: accent, borderColor: accent, borderSkipped: false, categoryPercentage: 1, barPercentage: 0.78 };
|
|
224
|
+
// A stage without a name would not draw at all: each gets Stage n until the labels cover it.
|
|
225
|
+
const given = Array.isArray(data.labels) ? data.labels : [];
|
|
226
|
+
const labels = bars.map((_, i) => (i < given.length ? given[i] : `Stage ${i + 1}`));
|
|
227
|
+
return { ...data, labels, datasets: [{ ...styled, ...first, data: bars }, ...rest] };
|
|
228
|
+
}
|
|
229
|
+
// Room on the right for the value and the conversion of each stage.
|
|
230
|
+
const FUNNEL_COLUMN = 132;
|
|
231
|
+
function funnelOptions(values) {
|
|
232
|
+
const widest = Math.max(0, ...values.map((v) => v ?? 0));
|
|
233
|
+
return {
|
|
234
|
+
indexAxis: 'y',
|
|
235
|
+
layout: { padding: { right: FUNNEL_COLUMN } },
|
|
236
|
+
plugins: { legend: { display: false } },
|
|
237
|
+
scales: {
|
|
238
|
+
x: { display: false, grid: { display: false }, ...(widest > 0 && { min: -widest / 2, max: widest / 2 }) },
|
|
239
|
+
y: { grid: { display: false }, border: { display: false }, ticks: { autoSkip: false } },
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
// Percent of the previous stage; none when that stage is empty or not a number.
|
|
244
|
+
export function conversion(current, previous) {
|
|
245
|
+
if (current === null || previous === null || previous <= 0)
|
|
246
|
+
return null;
|
|
247
|
+
return (current / previous) * 100;
|
|
248
|
+
}
|
|
249
|
+
// '42.1%', '9%', '1,234.5%': at most one decimal.
|
|
250
|
+
export function formatShare(percent) {
|
|
251
|
+
return `${(Math.round(percent * 10) / 10).toLocaleString('en', { maximumFractionDigits: 1 })}%`;
|
|
252
|
+
}
|
|
253
|
+
// The gauge is a half doughnut: the value, then what is left up to max.
|
|
254
|
+
const gaugeValue = (data) => num((Array.isArray(data) ? data : []).find((v) => num(v) !== null)) ?? 0;
|
|
255
|
+
function gaugeData(data, value, max, tone, accent) {
|
|
256
|
+
const datasets = Array.isArray(data.datasets) ? data.datasets : [];
|
|
257
|
+
const [first, ...rest] = datasets;
|
|
258
|
+
if (!isObject(first))
|
|
259
|
+
return data;
|
|
260
|
+
const filled = Math.min(Math.max(value, 0), max);
|
|
261
|
+
return { ...data, datasets: [{ backgroundColor: [accent, tone.muted], ...first, data: [filled, max - filled] }, ...rest] };
|
|
262
|
+
}
|
|
263
|
+
function gaugeOptions() {
|
|
264
|
+
return { rotation: -90, circumference: 180, cutout: '78%', plugins: { legend: { display: false } }, elements: { arc: { borderWidth: 0 } } };
|
|
265
|
+
}
|
|
266
|
+
// Returns what applyTheme returns, with the preset under the config: the preset's options
|
|
267
|
+
// are the base the config is merged over, then the theme fills in the rest.
|
|
268
|
+
export function applyPreset(config, background) {
|
|
269
|
+
const user = isObject(config.options) ? config.options : {};
|
|
270
|
+
const settings = isObject(user.plugins?.chartpng) ? user.plugins.chartpng : {};
|
|
271
|
+
const { report: preset, output } = readPresets(settings.preset);
|
|
272
|
+
if (!preset || settings.theme === false)
|
|
273
|
+
return applyTheme(config, background, !!output);
|
|
274
|
+
checkShape(preset, config, settings);
|
|
275
|
+
const tone = TONES[isDark(background) ? 'dark' : 'light'];
|
|
276
|
+
const data = config.data;
|
|
277
|
+
const heading = (block, shown) => {
|
|
278
|
+
if (!isObject(block) || !shown)
|
|
279
|
+
return '';
|
|
280
|
+
const value = Array.isArray(block.text) ? block.text.join(' ') : block.text;
|
|
281
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
282
|
+
};
|
|
283
|
+
const label = heading(user.plugins?.title, user.plugins?.title?.display !== false);
|
|
284
|
+
const sublabel = heading(user.plugins?.subtitle, user.plugins?.subtitle?.display === true);
|
|
285
|
+
const hasLabel = label !== '';
|
|
286
|
+
const hasSublabel = sublabel !== '';
|
|
287
|
+
const show = settings.values !== false;
|
|
288
|
+
const plugin = { preset, background, show };
|
|
289
|
+
let presetData = data;
|
|
290
|
+
let presetOptions;
|
|
291
|
+
if (preset === 'kpi') {
|
|
292
|
+
const first = Array.isArray(data?.datasets) ? data.datasets[0] : undefined;
|
|
293
|
+
const { value, change } = kpiFigures(isObject(first) ? first.data : [], settings.previous);
|
|
294
|
+
Object.assign(plugin, { text: value === null ? '—' : figure(value, text(settings.prefix), text(settings.suffix)), label, sublabel, ...(change !== null && { change }) });
|
|
295
|
+
presetOptions = kpiOptions(hasLabel, hasSublabel);
|
|
296
|
+
}
|
|
297
|
+
else if (preset === 'ranking') {
|
|
298
|
+
Object.assign(plugin, { prefix: text(settings.prefix), suffix: text(settings.suffix) });
|
|
299
|
+
presetData = rankedData(data, tone, resolvePalette(settings, background)[0]);
|
|
300
|
+
presetOptions = rankingOptions(user);
|
|
301
|
+
}
|
|
302
|
+
else if (preset === 'funnel') {
|
|
303
|
+
const values = data.datasets[0].data.map(num);
|
|
304
|
+
Object.assign(plugin, { prefix: text(settings.prefix), suffix: text(settings.suffix), values });
|
|
305
|
+
presetData = funnelData(data, resolvePalette(settings, background)[0]);
|
|
306
|
+
presetOptions = funnelOptions(values);
|
|
307
|
+
}
|
|
308
|
+
else if (preset === 'gauge') {
|
|
309
|
+
const value = gaugeValue(data.datasets[0].data);
|
|
310
|
+
const max = num(settings.max) ?? 100;
|
|
311
|
+
Object.assign(plugin, { prefix: text(settings.prefix), suffix: text(settings.suffix), value, max });
|
|
312
|
+
presetData = gaugeData(data, value, max, tone, resolvePalette(settings, background)[0]);
|
|
313
|
+
presetOptions = gaugeOptions();
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
presetData = comparisonData(data, config.type, tone);
|
|
317
|
+
presetOptions = comparisonOptions(config.type, user);
|
|
318
|
+
}
|
|
319
|
+
const themed = applyTheme({ ...config, data: presetData, options: underlay(presetOptions, user) }, background, !!output);
|
|
320
|
+
const plugins = { ...themed.options.plugins };
|
|
321
|
+
// The preset draws the numbers itself; the theme's value labels would repeat them.
|
|
322
|
+
plugins.chartpngValues = { ...plugins.chartpngValues, show: false };
|
|
323
|
+
// The kpi draws its title and subtitle itself, as small lines above the number.
|
|
324
|
+
if (preset === 'kpi') {
|
|
325
|
+
plugins.title = { ...plugins.title, display: false };
|
|
326
|
+
plugins.subtitle = { ...plugins.subtitle, display: false };
|
|
327
|
+
}
|
|
328
|
+
plugins.chartpngPreset = plugin;
|
|
329
|
+
return { data: themed.data, options: { ...themed.options, plugins } };
|
|
330
|
+
}
|
|
331
|
+
// Cuts text to fit maxWidth, ending in an ellipsis. The context's font must be set.
|
|
332
|
+
function fit(ctx, value, maxWidth) {
|
|
333
|
+
if (ctx.measureText(value).width <= maxWidth)
|
|
334
|
+
return value;
|
|
335
|
+
// Binary search for the longest prefix that fits: a 16 KB title would
|
|
336
|
+
// otherwise take one measureText per character, about 30 s.
|
|
337
|
+
const cut = (end) => `${value.slice(0, end).trimEnd()}…`;
|
|
338
|
+
let low = 0;
|
|
339
|
+
let high = value.length;
|
|
340
|
+
while (low < high) {
|
|
341
|
+
const mid = Math.ceil((low + high) / 2);
|
|
342
|
+
if (ctx.measureText(cut(mid)).width <= maxWidth)
|
|
343
|
+
low = mid;
|
|
344
|
+
else
|
|
345
|
+
high = mid - 1;
|
|
346
|
+
}
|
|
347
|
+
return low > 0 ? cut(low) : '';
|
|
348
|
+
}
|
|
349
|
+
function drawKpi({ chart, opts, tone, ink }) {
|
|
350
|
+
const { ctx, chartArea } = chart;
|
|
351
|
+
const left = chartArea.left;
|
|
352
|
+
const room = chartArea.right - left;
|
|
353
|
+
let y = KPI.top;
|
|
354
|
+
if (opts.label) {
|
|
355
|
+
ctx.font = `13px ${FONT_STACK}`;
|
|
356
|
+
ctx.fillStyle = ink.muted;
|
|
357
|
+
ctx.textAlign = 'left';
|
|
358
|
+
ctx.textBaseline = 'top';
|
|
359
|
+
ctx.fillText(fit(ctx, opts.label, room), left, y);
|
|
360
|
+
y += KPI.label;
|
|
361
|
+
}
|
|
362
|
+
if (opts.sublabel) {
|
|
363
|
+
ctx.font = `12px ${FONT_STACK}`;
|
|
364
|
+
ctx.fillStyle = ink.muted;
|
|
365
|
+
ctx.textAlign = 'left';
|
|
366
|
+
ctx.textBaseline = 'top';
|
|
367
|
+
ctx.fillText(fit(ctx, opts.sublabel, room), left, y);
|
|
368
|
+
y += KPI.sublabel;
|
|
369
|
+
}
|
|
370
|
+
const change = opts.change === undefined ? undefined : formatChange(opts.change);
|
|
371
|
+
ctx.font = `600 12px ${FONT_STACK}`;
|
|
372
|
+
const chipWidth = change ? Math.ceil(ctx.measureText(change.text).width) + 16 : 0;
|
|
373
|
+
// The number gives way before the chip does, down to a readable size.
|
|
374
|
+
let size = KPI.size;
|
|
375
|
+
const measure = () => {
|
|
376
|
+
ctx.font = `600 ${size}px ${FONT_STACK}`;
|
|
377
|
+
return ctx.measureText(opts.text ?? '').width;
|
|
378
|
+
};
|
|
379
|
+
while (size > 20 && measure() + (chipWidth ? KPI.chipGap + chipWidth : 0) > room)
|
|
380
|
+
size -= 2;
|
|
381
|
+
const width = measure();
|
|
382
|
+
const baseline = y + capHeight(size);
|
|
383
|
+
ctx.fillStyle = ink.ink;
|
|
384
|
+
ctx.textAlign = 'left';
|
|
385
|
+
ctx.textBaseline = 'alphabetic';
|
|
386
|
+
ctx.fillText(opts.text ?? '', left, baseline);
|
|
387
|
+
if (!change)
|
|
388
|
+
return;
|
|
389
|
+
const chip = tone[change.direction];
|
|
390
|
+
const x = left + width + KPI.chipGap;
|
|
391
|
+
const top = baseline - capHeight(size) / 2 - KPI.chipHeight / 2;
|
|
392
|
+
const radius = KPI.chipHeight / 2;
|
|
393
|
+
ctx.beginPath();
|
|
394
|
+
addRoundedRectPath(ctx, { x, y: top, w: chipWidth, h: KPI.chipHeight, radius: { topLeft: radius, topRight: radius, bottomLeft: radius, bottomRight: radius } });
|
|
395
|
+
ctx.fillStyle = chip.fill;
|
|
396
|
+
ctx.fill();
|
|
397
|
+
ctx.font = `600 12px ${FONT_STACK}`;
|
|
398
|
+
ctx.fillStyle = chip.text;
|
|
399
|
+
ctx.textAlign = 'center';
|
|
400
|
+
ctx.textBaseline = 'middle';
|
|
401
|
+
ctx.fillText(change.text, x + chipWidth / 2, top + KPI.chipHeight / 2 + 0.5);
|
|
402
|
+
}
|
|
403
|
+
function drawRanking({ chart, opts, ink }) {
|
|
404
|
+
if (!opts.show)
|
|
405
|
+
return;
|
|
406
|
+
const { ctx } = chart;
|
|
407
|
+
const visible = chart.data.datasets.map((_, i) => i).filter((i) => chart.isDatasetVisible(i));
|
|
408
|
+
if (visible.length > 2 || (chart.data.labels?.length ?? 0) > 20)
|
|
409
|
+
return;
|
|
410
|
+
const horizontal = chart.options.indexAxis === 'y';
|
|
411
|
+
ctx.font = `600 12px ${FONT_STACK}`;
|
|
412
|
+
for (const i of visible) {
|
|
413
|
+
const dataset = chart.data.datasets[i];
|
|
414
|
+
chart.getDatasetMeta(i).data.forEach((bar, j) => {
|
|
415
|
+
const value = num(dataset.data[j]);
|
|
416
|
+
if (value === null)
|
|
417
|
+
return;
|
|
418
|
+
const { x, y } = bar.getProps(['x', 'y'], true);
|
|
419
|
+
const label = figure(value, opts.prefix ?? '', opts.suffix ?? '');
|
|
420
|
+
const negative = value < 0;
|
|
421
|
+
// A value that would run off the image goes inside its bar, in the colour that reads on it.
|
|
422
|
+
const inside = horizontal && !negative && x + 6 + ctx.measureText(label).width > chart.width - 4;
|
|
423
|
+
const fill = bar.options.backgroundColor;
|
|
424
|
+
// The leader reads strongest, the rest quieter.
|
|
425
|
+
ctx.fillStyle = inside ? (typeof fill === 'string' && !isDark(fill) ? '#15161a' : '#ffffff') : j === 0 && i === 0 ? ink.ink : ink.muted;
|
|
426
|
+
ctx.textAlign = horizontal ? (inside || negative ? 'right' : 'left') : 'center';
|
|
427
|
+
ctx.textBaseline = horizontal ? 'middle' : negative ? 'top' : 'bottom';
|
|
428
|
+
ctx.fillText(label, horizontal ? x + (inside || negative ? -6 : 6) : x, horizontal ? y : y + (negative ? 4 : -4));
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
function drawFunnel({ chart, opts, ink }) {
|
|
433
|
+
if (!opts.show || !chart.isDatasetVisible(0))
|
|
434
|
+
return;
|
|
435
|
+
const { ctx, chartArea } = chart;
|
|
436
|
+
const values = opts.values ?? [];
|
|
437
|
+
const left = chartArea.right + 10;
|
|
438
|
+
const right = chartArea.right + FUNNEL_COLUMN - 6;
|
|
439
|
+
chart.getDatasetMeta(0).data.forEach((bar, j) => {
|
|
440
|
+
const value = values[j] ?? null;
|
|
441
|
+
const { y } = bar.getProps(['y'], true);
|
|
442
|
+
const share = j === 0 ? null : conversion(value, values[j - 1] ?? null);
|
|
443
|
+
ctx.textBaseline = 'middle';
|
|
444
|
+
ctx.textAlign = 'right';
|
|
445
|
+
ctx.font = `11px ${FONT_STACK}`;
|
|
446
|
+
ctx.fillStyle = ink.muted;
|
|
447
|
+
const shareText = share === null ? '' : formatShare(share);
|
|
448
|
+
if (shareText)
|
|
449
|
+
ctx.fillText(shareText, right, y);
|
|
450
|
+
const room = right - left - (shareText ? ctx.measureText(shareText).width + 8 : 0);
|
|
451
|
+
ctx.textAlign = 'left';
|
|
452
|
+
ctx.font = `600 12px ${FONT_STACK}`;
|
|
453
|
+
ctx.fillStyle = ink.ink;
|
|
454
|
+
ctx.fillText(fit(ctx, value === null ? '—' : figure(value, opts.prefix ?? '', opts.suffix ?? ''), room), left, y);
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
function drawGauge({ chart, opts, ink }) {
|
|
458
|
+
if (!opts.show)
|
|
459
|
+
return;
|
|
460
|
+
const arc = chart.getDatasetMeta(0).data[0];
|
|
461
|
+
if (!arc)
|
|
462
|
+
return;
|
|
463
|
+
const { ctx } = chart;
|
|
464
|
+
const { x, y, innerRadius } = arc.getProps(['x', 'y', 'innerRadius'], true);
|
|
465
|
+
const value = opts.value ?? 0;
|
|
466
|
+
const max = opts.max ?? 100;
|
|
467
|
+
const prefix = opts.prefix ?? '';
|
|
468
|
+
const suffix = opts.suffix ?? '';
|
|
469
|
+
const full = figure(value, prefix, suffix);
|
|
470
|
+
const goal = figure(max, prefix, suffix);
|
|
471
|
+
const share = formatShare((value / max) * 100);
|
|
472
|
+
// 72% of 100% says the same twice, so the share is left out when the value already is one.
|
|
473
|
+
const sub = max === 100 && suffix === '%' ? `of ${goal}` : `${share} of ${goal}`;
|
|
474
|
+
const room = innerRadius * 1.7;
|
|
475
|
+
const subBaseline = y - 4;
|
|
476
|
+
ctx.font = `12px ${FONT_STACK}`;
|
|
477
|
+
ctx.fillStyle = ink.muted;
|
|
478
|
+
ctx.textAlign = 'center';
|
|
479
|
+
ctx.textBaseline = 'alphabetic';
|
|
480
|
+
ctx.fillText(fit(ctx, sub, room), x, subBaseline);
|
|
481
|
+
let size = Math.max(16, Math.min(48, (innerRadius * 0.9 - 26) / 0.7));
|
|
482
|
+
const measure = () => {
|
|
483
|
+
ctx.font = `600 ${size}px ${FONT_STACK}`;
|
|
484
|
+
return ctx.measureText(full).width;
|
|
485
|
+
};
|
|
486
|
+
while (size > 14 && measure() > room)
|
|
487
|
+
size -= 2;
|
|
488
|
+
measure();
|
|
489
|
+
ctx.fillStyle = ink.ink;
|
|
490
|
+
ctx.fillText(fit(ctx, full, room), x, subBaseline - 22);
|
|
491
|
+
}
|
|
492
|
+
function drawComparison({ chart, opts, tone }) {
|
|
493
|
+
if (!opts.show || !chart.isDatasetVisible(0))
|
|
494
|
+
return;
|
|
495
|
+
const { ctx } = chart;
|
|
496
|
+
const [current, previous] = chart.data.datasets;
|
|
497
|
+
const points = chart.getDatasetMeta(0).data;
|
|
498
|
+
if (!current || !previous || !points.length)
|
|
499
|
+
return;
|
|
500
|
+
const type = chart.config.type;
|
|
501
|
+
const changes = points.map((_, j) => variation(current.data[j], previous.data[j]));
|
|
502
|
+
ctx.font = `600 11px ${FONT_STACK}`;
|
|
503
|
+
if (type === 'line') {
|
|
504
|
+
const j = changes.findLastIndex((c) => c !== null);
|
|
505
|
+
if (j < 0)
|
|
506
|
+
return;
|
|
507
|
+
const { x, y } = points[j].getProps(['x', 'y'], true);
|
|
508
|
+
const other = chart.getDatasetMeta(1).data[j]?.getProps(['y'], true).y;
|
|
509
|
+
// Below the point when the previous line passes above it.
|
|
510
|
+
const below = other !== undefined && other < y && y - other < 24;
|
|
511
|
+
const { text, direction } = formatChange(changes[j]);
|
|
512
|
+
ctx.fillStyle = tone[direction].text;
|
|
513
|
+
ctx.textAlign = 'right';
|
|
514
|
+
ctx.textBaseline = below ? 'top' : 'bottom';
|
|
515
|
+
ctx.fillText(text, x + 6, below ? y + 9 : y - 9);
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const horizontal = chart.options.indexAxis === 'y';
|
|
519
|
+
const gaps = points.slice(1).map((p, j) => {
|
|
520
|
+
const a = p.getProps(['x', 'y'], true);
|
|
521
|
+
const b = points[j].getProps(['x', 'y'], true);
|
|
522
|
+
return horizontal ? Math.abs(a.y - b.y) : Math.abs(a.x - b.x);
|
|
523
|
+
});
|
|
524
|
+
const gap = gaps.length ? Math.min(...gaps) : Infinity;
|
|
525
|
+
// The full text, then a short one, then nothing when the bars are too close.
|
|
526
|
+
const widest = (compact) => Math.max(0, ...changes.map((c) => (c === null ? 0 : ctx.measureText(formatChange(c, compact).text).width)));
|
|
527
|
+
const compact = !horizontal && gap < widest(false) + 6;
|
|
528
|
+
if (horizontal ? gap < 14 : compact && gap < widest(true) + 4)
|
|
529
|
+
return;
|
|
530
|
+
points.forEach((bar, j) => {
|
|
531
|
+
const change = changes[j];
|
|
532
|
+
if (change === null)
|
|
533
|
+
return;
|
|
534
|
+
const { x, y, base } = bar.getProps(['x', 'y', 'base'], true);
|
|
535
|
+
const { text, direction } = formatChange(change, compact);
|
|
536
|
+
const negative = (num(current.data[j]) ?? 0) < 0;
|
|
537
|
+
ctx.fillStyle = tone[direction].text;
|
|
538
|
+
if (horizontal) {
|
|
539
|
+
ctx.textAlign = negative ? 'right' : 'left';
|
|
540
|
+
ctx.textBaseline = 'middle';
|
|
541
|
+
ctx.fillText(text, negative ? x - 6 : x + 6, y);
|
|
542
|
+
}
|
|
543
|
+
else {
|
|
544
|
+
ctx.textAlign = 'center';
|
|
545
|
+
ctx.textBaseline = negative || y > base ? 'top' : 'bottom';
|
|
546
|
+
ctx.fillText(text, x, negative || y > base ? y + 4 : y - 4);
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
// Draws what the preset puts on the canvas: the kpi block, the ranking's values, the comparison's changes,
|
|
551
|
+
// the funnel's values and conversions, the gauge's number.
|
|
552
|
+
export const presetPlugin = {
|
|
553
|
+
id: 'chartpngPreset',
|
|
554
|
+
afterDraw(chart, _args, opts) {
|
|
555
|
+
if (!opts.preset)
|
|
556
|
+
return;
|
|
557
|
+
const background = opts.background ?? '#ffffff';
|
|
558
|
+
const drawn = { chart, opts, tone: TONES[isDark(background) ? 'dark' : 'light'], ink: inkFor(background) };
|
|
559
|
+
chart.ctx.save();
|
|
560
|
+
try {
|
|
561
|
+
if (opts.preset === 'kpi')
|
|
562
|
+
drawKpi(drawn);
|
|
563
|
+
else if (opts.preset === 'ranking')
|
|
564
|
+
drawRanking(drawn);
|
|
565
|
+
else if (opts.preset === 'funnel')
|
|
566
|
+
drawFunnel(drawn);
|
|
567
|
+
else if (opts.preset === 'gauge')
|
|
568
|
+
drawGauge(drawn);
|
|
569
|
+
else
|
|
570
|
+
drawComparison(drawn);
|
|
571
|
+
}
|
|
572
|
+
finally {
|
|
573
|
+
chart.ctx.restore();
|
|
574
|
+
}
|
|
575
|
+
},
|
|
576
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { RenderError } from './errors.js';
|
|
2
|
+
import type { ChartConfiguration, ChartType } from 'chart.js';
|
|
3
|
+
import type { OutputPresetName } from './presets.js';
|
|
4
|
+
import type { StyleFields } from './style.js';
|
|
5
|
+
export declare const LIMITS: {
|
|
6
|
+
maxConfigBytes: number;
|
|
7
|
+
maxSide: number;
|
|
8
|
+
minSide: number;
|
|
9
|
+
defaultWidth: number;
|
|
10
|
+
defaultHeight: number;
|
|
11
|
+
maxTicks: number;
|
|
12
|
+
maxDepth: number;
|
|
13
|
+
freeMaxPixels: number;
|
|
14
|
+
maxBodyBytes: number;
|
|
15
|
+
};
|
|
16
|
+
export declare function queryFields(params: URLSearchParams): Record<string, string>;
|
|
17
|
+
export declare function checkFreeSize({ width, height, dpr }: RenderRequest): void;
|
|
18
|
+
export { RenderError };
|
|
19
|
+
export interface ChartConfig {
|
|
20
|
+
type: ChartType;
|
|
21
|
+
data: ChartConfiguration['data'];
|
|
22
|
+
options?: Record<string, any>;
|
|
23
|
+
}
|
|
24
|
+
export interface RenderRequest {
|
|
25
|
+
config: ChartConfig;
|
|
26
|
+
width: number;
|
|
27
|
+
height: number;
|
|
28
|
+
background: string;
|
|
29
|
+
dpr: 1 | 2;
|
|
30
|
+
fixes: string[];
|
|
31
|
+
style?: StyleFields;
|
|
32
|
+
output?: OutputPresetName;
|
|
33
|
+
}
|
|
34
|
+
export declare function parseRequest({ c, w, h, bkg, dpr, theme, palette, preset }: Record<string, unknown>): RenderRequest;
|
|
35
|
+
export declare const MAX_SCALES = 16;
|
|
36
|
+
export declare function renderPng({ config: sent, width, height, background, dpr, style, output }: RenderRequest, { watermark }?: {
|
|
37
|
+
watermark?: string;
|
|
38
|
+
}): Buffer;
|