@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,624 @@
|
|
|
1
|
+
// The one reader of tables on the site. The editor on /make and the grid on the landing both go
|
|
2
|
+
// through parseTable(), so the same cells give the same numbers on both pages.
|
|
3
|
+
//
|
|
4
|
+
// Read a table pasted from Excel, Google Sheets, Numbers or a CSV file and turn
|
|
5
|
+
// it into the /chart URL of a bar, line, pie, doughnut or ranking chart. Pure and without imports
|
|
6
|
+
// from the renderer, so the page script can bundle it for the browser and a test can run it under
|
|
7
|
+
// node (test/table-chart.test.ts sends every accepted paste through parseRequest and renderPng).
|
|
8
|
+
//
|
|
9
|
+
// parseTable() never guesses silently: every assumption it makes comes back as a short note that
|
|
10
|
+
// the page shows under the textarea (which delimiter, whether row 1 is a header, which decimal
|
|
11
|
+
// mark, which columns were skipped).
|
|
12
|
+
import { MAKER_DPR, MAKER_MAX_URL, MAKER_WIDTH, rankingConfig } from './maker.js';
|
|
13
|
+
// Caps that keep the URL usable and the chart readable. 50 rows of 6 series is about 300 numbers.
|
|
14
|
+
export const TABLE_MAX_ROWS = 50;
|
|
15
|
+
export const TABLE_MAX_SERIES = 6;
|
|
16
|
+
// The editor draws one size, the same as the makers on the guides: 800 by 450 at dpr 2.
|
|
17
|
+
export const TABLE_WIDTH = MAKER_WIDTH;
|
|
18
|
+
export const TABLE_HEIGHT = 450;
|
|
19
|
+
export const TABLE_DPR = MAKER_DPR;
|
|
20
|
+
export const TABLE_MAX_URL = MAKER_MAX_URL;
|
|
21
|
+
// A paste larger than this is not a table anyone wants as a chart, and parsing it would only freeze the tab.
|
|
22
|
+
export const TABLE_MAX_CHARS = 200_000;
|
|
23
|
+
const MAX_LABEL = 40;
|
|
24
|
+
const MAX_TITLE = 60;
|
|
25
|
+
// Big enough for any real count or sum, small enough that the number stays readable in JSON.
|
|
26
|
+
const MAX_ABS = 1e15;
|
|
27
|
+
const DELIMITER_CHARS = { tab: '\t', semicolon: ';', comma: ',', none: null };
|
|
28
|
+
// Counts the separators outside quotes. A tab wins over a semicolon and a semicolon over a comma: a
|
|
29
|
+
// copy from a spreadsheet is tab separated whatever the cells hold, and a CSV written in a locale that
|
|
30
|
+
// uses the decimal comma separates with semicolons, so a comma there belongs to a number.
|
|
31
|
+
export function detectDelimiter(text) {
|
|
32
|
+
const count = { '\t': 0, ';': 0, ',': 0 };
|
|
33
|
+
let quoted = false;
|
|
34
|
+
let start = true;
|
|
35
|
+
// Whether the first line with content has a comma outside quotes: a one column copy of 1,5 and 2,5
|
|
36
|
+
// under a header such as Sales has commas, but not in its first line.
|
|
37
|
+
let firstLineComma = null;
|
|
38
|
+
let lineComma = false;
|
|
39
|
+
let lineContent = false;
|
|
40
|
+
const endLine = () => {
|
|
41
|
+
if (firstLineComma === null && lineContent)
|
|
42
|
+
firstLineComma = lineComma;
|
|
43
|
+
lineComma = false;
|
|
44
|
+
lineContent = false;
|
|
45
|
+
};
|
|
46
|
+
for (let i = 0; i < text.length; i++) {
|
|
47
|
+
const ch = text[i];
|
|
48
|
+
if (quoted) {
|
|
49
|
+
if (ch === '"') {
|
|
50
|
+
if (text[i + 1] === '"')
|
|
51
|
+
i++;
|
|
52
|
+
else
|
|
53
|
+
quoted = false;
|
|
54
|
+
}
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (ch === '"' && start) {
|
|
58
|
+
quoted = true;
|
|
59
|
+
start = false;
|
|
60
|
+
lineContent = true;
|
|
61
|
+
}
|
|
62
|
+
else if (ch === '\t' || ch === ';' || ch === ',') {
|
|
63
|
+
count[ch]++;
|
|
64
|
+
start = true;
|
|
65
|
+
if (ch === ',')
|
|
66
|
+
lineComma = true;
|
|
67
|
+
lineContent = true;
|
|
68
|
+
}
|
|
69
|
+
else if (ch === '\n') {
|
|
70
|
+
start = true;
|
|
71
|
+
endLine();
|
|
72
|
+
}
|
|
73
|
+
else if (ch !== ' ') {
|
|
74
|
+
start = false;
|
|
75
|
+
lineContent = true;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
endLine();
|
|
79
|
+
if (count['\t'] > 0)
|
|
80
|
+
return 'tab';
|
|
81
|
+
if (count[';'] > 0)
|
|
82
|
+
return 'semicolon';
|
|
83
|
+
if (count[','] > 0) {
|
|
84
|
+
if (!firstLineComma)
|
|
85
|
+
return 'none';
|
|
86
|
+
// Every line that has a comma is a lone number such as 1,5 or 1,234: a one column paste with a
|
|
87
|
+
// decimal comma or a thousands group, not two columns of whole numbers.
|
|
88
|
+
const withComma = text.split('\n').map((line) => line.trim()).filter((line) => line.includes(','));
|
|
89
|
+
if (withComma.every((line) => /^\d+,(\d+|\d{3}(\.\d+)?)$/.test(line)))
|
|
90
|
+
return 'none';
|
|
91
|
+
return 'comma';
|
|
92
|
+
}
|
|
93
|
+
return 'none';
|
|
94
|
+
}
|
|
95
|
+
// Splits text into rows of cells. A quote opens a quoted cell only at the start of the cell; inside,
|
|
96
|
+
// the delimiter, a line break and a doubled quote are all part of the text.
|
|
97
|
+
export function splitCells(text, delimiter) {
|
|
98
|
+
const rows = [];
|
|
99
|
+
let row = [];
|
|
100
|
+
let field = '';
|
|
101
|
+
let quoted = false;
|
|
102
|
+
const endField = () => {
|
|
103
|
+
row.push(field);
|
|
104
|
+
field = '';
|
|
105
|
+
};
|
|
106
|
+
for (let i = 0; i < text.length; i++) {
|
|
107
|
+
const ch = text[i];
|
|
108
|
+
if (quoted) {
|
|
109
|
+
if (ch === '"') {
|
|
110
|
+
if (text[i + 1] === '"') {
|
|
111
|
+
field += '"';
|
|
112
|
+
i++;
|
|
113
|
+
}
|
|
114
|
+
else
|
|
115
|
+
quoted = false;
|
|
116
|
+
}
|
|
117
|
+
else
|
|
118
|
+
field += ch;
|
|
119
|
+
}
|
|
120
|
+
else if (ch === '"' && field.trim() === '') {
|
|
121
|
+
quoted = true;
|
|
122
|
+
field = '';
|
|
123
|
+
}
|
|
124
|
+
else if (ch === '\n') {
|
|
125
|
+
endField();
|
|
126
|
+
rows.push(row);
|
|
127
|
+
row = [];
|
|
128
|
+
}
|
|
129
|
+
else if (delimiter !== null && ch === delimiter)
|
|
130
|
+
endField();
|
|
131
|
+
else
|
|
132
|
+
field += ch;
|
|
133
|
+
}
|
|
134
|
+
if (field !== '' || row.length > 0) {
|
|
135
|
+
endField();
|
|
136
|
+
rows.push(row);
|
|
137
|
+
}
|
|
138
|
+
return { rows, unterminated: quoted };
|
|
139
|
+
}
|
|
140
|
+
// A cell that stands for "no value", as spreadsheets and exports write it.
|
|
141
|
+
const PLACEHOLDER = /^(n\/a|na|#n\/a|null|nan|-|–|—|\.\.)$/i;
|
|
142
|
+
// Thousands groups separated by a space, a non-breaking space or a thin space: French and Swiss exports.
|
|
143
|
+
const SPACE_GROUPS = /^\d{1,3}(?:\s\d{3})+(?:[.,]\d+)?$/;
|
|
144
|
+
// Currency symbols, a percent sign, a sign, accounting parentheses and the spaces around a number come
|
|
145
|
+
// off; what is left is the digits and their separators.
|
|
146
|
+
function prepare(raw) {
|
|
147
|
+
let s = raw.trim();
|
|
148
|
+
if (s === '')
|
|
149
|
+
return 'empty';
|
|
150
|
+
if (PLACEHOLDER.test(s))
|
|
151
|
+
return 'gap';
|
|
152
|
+
s = s.replace(/−/g, '-');
|
|
153
|
+
let negative = false;
|
|
154
|
+
const accounting = /^\((.*)\)$/.exec(s);
|
|
155
|
+
if (accounting) {
|
|
156
|
+
negative = true;
|
|
157
|
+
s = accounting[1].trim();
|
|
158
|
+
}
|
|
159
|
+
const currency = /\p{Sc}/u.test(s);
|
|
160
|
+
if (currency)
|
|
161
|
+
s = s.replace(/\p{Sc}/gu, '').trim();
|
|
162
|
+
const percent = /^%|%$/.test(s);
|
|
163
|
+
if (percent)
|
|
164
|
+
s = s.replace(/^%|%$/g, '').trim();
|
|
165
|
+
const sign = /^([+-])\s*/.exec(s);
|
|
166
|
+
if (sign) {
|
|
167
|
+
if (sign[1] === '-')
|
|
168
|
+
negative = !negative;
|
|
169
|
+
s = s.slice(sign[0].length);
|
|
170
|
+
}
|
|
171
|
+
if (SPACE_GROUPS.test(s))
|
|
172
|
+
s = s.replace(/\s/g, '');
|
|
173
|
+
return { body: s, negative, currency, percent };
|
|
174
|
+
}
|
|
175
|
+
// The digits of a prepared body as a JavaScript number string, or null when it is not a number under
|
|
176
|
+
// this decimal mark. "1,234.5" is 1234.5 with a dot mark and "1.234,5" is 1234.5 with a comma mark.
|
|
177
|
+
function normalize(body, mark) {
|
|
178
|
+
let s = body;
|
|
179
|
+
if (mark === 'dot') {
|
|
180
|
+
if (/^\d{1,3}(,\d{3})+(\.\d+)?$/.test(s))
|
|
181
|
+
s = s.replace(/,/g, '');
|
|
182
|
+
else if (s.includes(','))
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
else if (/^\d{1,3}(\.\d{3})+(,\d+)?$/.test(s))
|
|
186
|
+
s = s.replace(/\./g, '').replace(',', '.');
|
|
187
|
+
else if (/^(\d+,\d*|,\d+)(e[+-]?\d+)?$/i.test(s))
|
|
188
|
+
s = s.replace(',', '.');
|
|
189
|
+
else if (s.includes('.') || s.includes(','))
|
|
190
|
+
return null;
|
|
191
|
+
return /^(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i.test(s) ? s : null;
|
|
192
|
+
}
|
|
193
|
+
export function readCell(raw, mark) {
|
|
194
|
+
const p = prepare(raw);
|
|
195
|
+
if (p === 'empty')
|
|
196
|
+
return { kind: 'empty' };
|
|
197
|
+
if (p === 'gap')
|
|
198
|
+
return { kind: 'gap' };
|
|
199
|
+
if (p === null)
|
|
200
|
+
return { kind: 'text' };
|
|
201
|
+
const digits = normalize(p.body, mark);
|
|
202
|
+
if (digits === null)
|
|
203
|
+
return { kind: 'text' };
|
|
204
|
+
const n = Number(digits);
|
|
205
|
+
if (!Number.isFinite(n) || n > MAX_ABS)
|
|
206
|
+
return { kind: 'text' };
|
|
207
|
+
return { kind: 'number', value: p.negative ? -n : n, currency: p.currency, percent: p.percent };
|
|
208
|
+
}
|
|
209
|
+
// What the numbers say about the decimal mark. 1.234,5 and 1,5 can only be a comma mark; 1,234.5 and 1.5
|
|
210
|
+
// can only be a dot mark; 1.234 and 1,234 could be either, so they decide nothing.
|
|
211
|
+
function evidence(rows, columns) {
|
|
212
|
+
let comma = false;
|
|
213
|
+
let dot = false;
|
|
214
|
+
let ambiguous = null;
|
|
215
|
+
for (const c of columns) {
|
|
216
|
+
let groups = false;
|
|
217
|
+
let plain = false;
|
|
218
|
+
for (const row of rows) {
|
|
219
|
+
const p = prepare(row[c] ?? '');
|
|
220
|
+
if (p === null || typeof p === 'string')
|
|
221
|
+
continue;
|
|
222
|
+
const b = p.body;
|
|
223
|
+
if (/^\d{1,3}(\.\d{3})+,\d+$/.test(b) || /^\d{1,3}(\.\d{3}){2,}$/.test(b) || /^\d+,(\d{1,2}|\d{4,})$/.test(b) || /^,\d+$/.test(b))
|
|
224
|
+
comma = true;
|
|
225
|
+
else if (/^\d{1,3}(,\d{3})+\.\d+$/.test(b) || /^\d{1,3}(,\d{3}){2,}$/.test(b) || /^\.\d+$/.test(b) || (/^\d+\.\d+$/.test(b) && !/^\d{1,3}\.\d{3}$/.test(b)))
|
|
226
|
+
dot = true;
|
|
227
|
+
else if (/^\d{1,3}[.,]\d{3}$/.test(b)) {
|
|
228
|
+
ambiguous ??= row[c].trim();
|
|
229
|
+
// A General cell in a dot locale drops trailing zeros, so 12.500 is a thousands group.
|
|
230
|
+
if (/^[1-9]\d{0,2}\.\d{2}0$/.test(b))
|
|
231
|
+
comma = true;
|
|
232
|
+
else if (/^[1-9]\d{0,2}\.\d{3}$/.test(b))
|
|
233
|
+
groups = true;
|
|
234
|
+
}
|
|
235
|
+
else if (/^\d+$/.test(b))
|
|
236
|
+
plain = true;
|
|
237
|
+
}
|
|
238
|
+
// A column that shows 1.234 beside 980 is not formatted to three decimals, or 980 would read 980.000.
|
|
239
|
+
if (groups && plain)
|
|
240
|
+
comma = true;
|
|
241
|
+
}
|
|
242
|
+
return { comma, dot, ambiguous };
|
|
243
|
+
}
|
|
244
|
+
const YEAR = /^(19|20)\d{2}$/;
|
|
245
|
+
const cut = (text, max) => (text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text);
|
|
246
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
247
|
+
export function parseTable(input, options = {}) {
|
|
248
|
+
const notes = [];
|
|
249
|
+
const fail = (error, reason) => ({ ok: false, error, reason, notes });
|
|
250
|
+
const text = input.replace(/\r\n?/g, '\n');
|
|
251
|
+
if (text.trim() === '')
|
|
252
|
+
return fail('Paste a table first: cells copied from a spreadsheet, or CSV text.', 'empty');
|
|
253
|
+
if (text.length > TABLE_MAX_CHARS)
|
|
254
|
+
return fail(`The paste is ${text.length.toLocaleString('en-US')} characters long; the editor reads up to ${TABLE_MAX_CHARS.toLocaleString('en-US')}. Paste fewer rows.`, 'too_long');
|
|
255
|
+
const delimiter = detectDelimiter(text);
|
|
256
|
+
notes.push({
|
|
257
|
+
tab: 'Columns are separated by tabs, as in cells copied from Excel, Google Sheets or Numbers.',
|
|
258
|
+
semicolon: 'Columns are separated by semicolons.',
|
|
259
|
+
comma: 'Columns are separated by commas.',
|
|
260
|
+
none: 'No column separator found, so the paste is one column.',
|
|
261
|
+
}[delimiter]);
|
|
262
|
+
const split = splitCells(text, DELIMITER_CHARS[delimiter]);
|
|
263
|
+
if (split.unterminated)
|
|
264
|
+
notes.push('A quote was opened and never closed, so the rest of the paste was read as one cell.');
|
|
265
|
+
// Blank rows go; the rest are padded to the same width.
|
|
266
|
+
let rows = split.rows.map((row) => row.map((cell) => cell.trim())).filter((row) => row.some((cell) => cell !== ''));
|
|
267
|
+
if (rows.length === 0)
|
|
268
|
+
return fail('The paste has no cells with content.', 'empty');
|
|
269
|
+
const width = Math.max(...rows.map((row) => row.length));
|
|
270
|
+
rows = rows.map((row) => [...row, ...Array(width - row.length).fill('')]);
|
|
271
|
+
if (options.transpose) {
|
|
272
|
+
rows = Array.from({ length: width }, (_, c) => rows.map((row) => row[c]));
|
|
273
|
+
notes.push('Rows and columns are switched: the first row is now the first column.');
|
|
274
|
+
}
|
|
275
|
+
// A column with nothing in it, such as the one a copy of columns B to D leaves in front, is not a column.
|
|
276
|
+
const filled = Array.from({ length: rows[0].length }, (_, c) => c).filter((c) => rows.some((row) => row[c] !== ''));
|
|
277
|
+
rows = rows.map((row) => filled.map((c) => row[c]));
|
|
278
|
+
const columns = filled.length;
|
|
279
|
+
// One column of numbers has no labels column; with more, the first column names the rows.
|
|
280
|
+
const dataColumns = columns > 1 ? Array.from({ length: columns - 1 }, (_, i) => i + 1) : [0];
|
|
281
|
+
// The decimal mark. A comma mark is never taken when commas separate the columns: a comma there is
|
|
282
|
+
// part of a thousands group at most.
|
|
283
|
+
let mark = 'dot';
|
|
284
|
+
const found = evidence(rows, dataColumns);
|
|
285
|
+
const asked = options.decimal ?? 'auto';
|
|
286
|
+
if (asked === 'comma' && delimiter === 'comma') {
|
|
287
|
+
notes.push('Decimal mark: dot. A decimal comma needs tabs or semicolons between the columns; with commas between them a comma cannot also be a decimal mark.');
|
|
288
|
+
}
|
|
289
|
+
else if (asked === 'comma') {
|
|
290
|
+
mark = 'comma';
|
|
291
|
+
notes.push('Decimal mark: comma, as you chose, so 1.234,5 is read as 1234.5.');
|
|
292
|
+
}
|
|
293
|
+
else if (asked === 'dot') {
|
|
294
|
+
notes.push('Decimal mark: dot, as you chose.');
|
|
295
|
+
}
|
|
296
|
+
else if (delimiter !== 'comma' && found.comma && !found.dot) {
|
|
297
|
+
mark = 'comma';
|
|
298
|
+
notes.push('Decimal mark: comma, so 1.234,5 is read as 1234.5.');
|
|
299
|
+
}
|
|
300
|
+
else if (delimiter !== 'comma' && found.comma && found.dot) {
|
|
301
|
+
notes.push('Decimal mark: dot. The paste mixes 1,5 and 1.5; choose the decimal mark below if the dot is wrong.');
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
notes.push('Decimal mark: dot.');
|
|
305
|
+
if (delimiter !== 'comma' && found.ambiguous)
|
|
306
|
+
notes.push(`${found.ambiguous} could be a number with a decimal or with a thousands group. It was read with a dot as the decimal mark; choose Comma under Decimal mark if it is a thousands group.`);
|
|
307
|
+
}
|
|
308
|
+
// A header row: row 1 is text over numbers. Years over numbers (2023, 2024) are still a header.
|
|
309
|
+
const cell = (row, c) => readCell(row[c], mark);
|
|
310
|
+
const first = rows[0];
|
|
311
|
+
let header = false;
|
|
312
|
+
if (rows.length > 1 && dataColumns.some((c) => cell(rows[1], c).kind === 'number')) {
|
|
313
|
+
const kinds = dataColumns.map((c) => cell(first, c));
|
|
314
|
+
const numbers = dataColumns.filter((c, i) => kinds[i].kind === 'number');
|
|
315
|
+
const noNumbers = numbers.length === 0 && kinds.some((k) => k.kind === 'text');
|
|
316
|
+
const years = numbers.length > 0 && columns > 1 && !/^[\d.,]+$/.test(first[0]) && numbers.every((c) => YEAR.test(first[c]));
|
|
317
|
+
header = noNumbers || years;
|
|
318
|
+
}
|
|
319
|
+
if (options.header)
|
|
320
|
+
header = true;
|
|
321
|
+
const names = header ? first : [];
|
|
322
|
+
const body = header ? rows.slice(1) : rows;
|
|
323
|
+
notes.push(header ? 'Row 1 is a header: its cells name the series.' : 'No header row found, so the series are called Series 1, Series 2 and so on.');
|
|
324
|
+
const label = (i) => (columns > 1 ? body[i][0] : String(i + 1));
|
|
325
|
+
// Each column after the first is a series when every cell is a number, a gap or empty.
|
|
326
|
+
const series = [];
|
|
327
|
+
const skipped = [];
|
|
328
|
+
const gapCells = [];
|
|
329
|
+
const rowNumber = (i) => i + 1 + (header ? 1 : 0);
|
|
330
|
+
let gaps = 0;
|
|
331
|
+
let money = false;
|
|
332
|
+
let percent = false;
|
|
333
|
+
for (const c of dataColumns) {
|
|
334
|
+
const title = header && names[c] !== '' ? `column "${cut(names[c], MAX_LABEL)}"` : `column ${c + 1}`;
|
|
335
|
+
const name = header && names[c] !== '' ? cut(names[c], MAX_LABEL) : String(c + 1);
|
|
336
|
+
const values = [];
|
|
337
|
+
let text = null;
|
|
338
|
+
let textRow = 0;
|
|
339
|
+
let seen = false;
|
|
340
|
+
let usedMoney = false;
|
|
341
|
+
let usedPercent = false;
|
|
342
|
+
for (const row of body) {
|
|
343
|
+
const read = cell(row, c);
|
|
344
|
+
if (read.kind === 'number') {
|
|
345
|
+
values.push(read.value);
|
|
346
|
+
seen = true;
|
|
347
|
+
usedMoney ||= read.currency;
|
|
348
|
+
usedPercent ||= read.percent;
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
values.push(null);
|
|
352
|
+
if (read.kind === 'text' && text === null) {
|
|
353
|
+
text = row[c];
|
|
354
|
+
textRow = rowNumber(values.length - 1);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (text !== null) {
|
|
359
|
+
notes.push(`Skipped ${title}: "${cut(text.replace(/\s+/g, ' '), 24)}" is not a number.`);
|
|
360
|
+
skipped.push({ name, row: textRow, sample: text });
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (!seen) {
|
|
364
|
+
if (header || body.some((row) => row[c] !== ''))
|
|
365
|
+
notes.push(`Skipped ${title}: it has no numbers.`);
|
|
366
|
+
skipped.push({ name, row: 0, sample: '' });
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
values.forEach((v, i) => {
|
|
370
|
+
if (v === null)
|
|
371
|
+
gapCells.push({ name, row: rowNumber(i), sample: body[i][c] });
|
|
372
|
+
});
|
|
373
|
+
gaps += values.filter((v) => v === null).length;
|
|
374
|
+
money ||= usedMoney;
|
|
375
|
+
percent ||= usedPercent;
|
|
376
|
+
series.push({ name: header && names[c] !== '' ? cut(names[c], MAX_LABEL) : `Series ${series.length + 1}`, values });
|
|
377
|
+
}
|
|
378
|
+
if (series.length === 0) {
|
|
379
|
+
return { ...fail('There is no column of numbers in this paste. The first column names the rows and every other column that holds only numbers becomes a series.', 'no_numbers'), skipped };
|
|
380
|
+
}
|
|
381
|
+
if (columns === 1)
|
|
382
|
+
notes.push('One column of numbers: the rows are numbered 1, 2, 3 and so on.');
|
|
383
|
+
// Two columns with the same header would be one entry in the legend.
|
|
384
|
+
const used = new Map();
|
|
385
|
+
for (const s of series) {
|
|
386
|
+
const times = (used.get(s.name) ?? 0) + 1;
|
|
387
|
+
used.set(s.name, times);
|
|
388
|
+
if (times > 1)
|
|
389
|
+
s.name = `${s.name} (${times})`;
|
|
390
|
+
}
|
|
391
|
+
if (gaps > 0)
|
|
392
|
+
notes.push(`${plural(gaps, 'empty cell')} will be drawn as ${gaps === 1 ? 'a gap' : 'gaps'}.`);
|
|
393
|
+
if (money)
|
|
394
|
+
notes.push('Currency symbols were removed.');
|
|
395
|
+
if (percent)
|
|
396
|
+
notes.push('Percent signs were removed: 12% is drawn as 12.');
|
|
397
|
+
const labels = body.map((_, i) => label(i) || `Row ${i + 1}`);
|
|
398
|
+
if (labels.some((l) => l.length > MAX_LABEL))
|
|
399
|
+
notes.push(`Labels longer than ${MAX_LABEL} characters were shortened.`);
|
|
400
|
+
if (body.length > TABLE_MAX_ROWS) {
|
|
401
|
+
return fail(`The table has ${body.length} rows. Up to ${TABLE_MAX_ROWS} fit a chart you can read and an image URL that stays short; keep the rows that matter or add them up first.`, 'rows');
|
|
402
|
+
}
|
|
403
|
+
if (series.length > TABLE_MAX_SERIES) {
|
|
404
|
+
return fail(`The table has ${series.length} columns of numbers. Up to ${TABLE_MAX_SERIES} fit a legend you can read. If your categories run across the top, tick Switch rows and columns; otherwise keep the columns that matter.`, 'series');
|
|
405
|
+
}
|
|
406
|
+
return { ok: true, table: { labels: labels.map((l) => cut(l, MAX_LABEL)), series }, notes, delimiter, decimal: mark, header, skipped, gaps: gapCells };
|
|
407
|
+
}
|
|
408
|
+
export const TABLE_CHART_TYPES = [
|
|
409
|
+
{ id: 'bar', label: 'Bar' },
|
|
410
|
+
{ id: 'horizontal', label: 'Horizontal bar' },
|
|
411
|
+
{ id: 'line', label: 'Line' },
|
|
412
|
+
{ id: 'pie', label: 'Pie' },
|
|
413
|
+
{ id: 'doughnut', label: 'Doughnut' },
|
|
414
|
+
{ id: 'ranking', label: 'Ranking, biggest first' },
|
|
415
|
+
];
|
|
416
|
+
// The same as encodeURIComponent, and also the characters it leaves alone that end a Markdown link or
|
|
417
|
+
// a quoted string early: ( ) ' ! *.
|
|
418
|
+
const encode = (text) => encodeURIComponent(text).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
419
|
+
// What a chart type says it does with the series, for the notes under the preview.
|
|
420
|
+
export function chartNotes(table, type) {
|
|
421
|
+
const notes = [];
|
|
422
|
+
if ((type === 'pie' || type === 'doughnut' || type === 'ranking') && table.series.length > 1) {
|
|
423
|
+
notes.push(`${type === 'ranking' ? 'A ranking' : type === 'pie' ? 'A pie' : 'A doughnut'} draws one series, so it uses the first, ${table.series[0].name}. Use a bar chart to show all ${table.series.length}.`);
|
|
424
|
+
}
|
|
425
|
+
if ((type === 'ranking' || type === 'horizontal') && table.labels.length > 15) {
|
|
426
|
+
notes.push(`With ${table.labels.length} rows the labels get small. Fifteen or fewer read best.`);
|
|
427
|
+
}
|
|
428
|
+
return notes;
|
|
429
|
+
}
|
|
430
|
+
const NAMES = { bar: 'Bar chart', horizontal: 'Horizontal bar chart', line: 'Line chart', pie: 'Pie chart', doughnut: 'Doughnut chart', ranking: 'Ranking chart' };
|
|
431
|
+
function altOf(table, type, title, drawn) {
|
|
432
|
+
const rows = table.labels.length;
|
|
433
|
+
const range = rows > 1 ? `from ${table.labels[0]} to ${table.labels[rows - 1]}` : `for ${table.labels[0]}`;
|
|
434
|
+
const names = drawn.map((s) => s.name).join(', ');
|
|
435
|
+
const head = title ? `${NAMES[type]}: ${title}.` : `${NAMES[type]}.`;
|
|
436
|
+
return `${head} ${plural(rows, 'row')} ${range}. Series: ${names}.`.replace(/\s+/g, ' ');
|
|
437
|
+
}
|
|
438
|
+
export function tableChartUrl(table, settings) {
|
|
439
|
+
const errors = [];
|
|
440
|
+
const title = settings.title.trim();
|
|
441
|
+
const { type } = settings;
|
|
442
|
+
if (title.length > MAX_TITLE)
|
|
443
|
+
errors.push({ field: 'title', message: `The title takes up to ${MAX_TITLE} characters.` });
|
|
444
|
+
if (!TABLE_CHART_TYPES.some((t) => t.id === type))
|
|
445
|
+
errors.push({ field: 'type', message: 'Pick one of the chart types in the list.' });
|
|
446
|
+
if (table.labels.length === 0 || table.series.length === 0)
|
|
447
|
+
errors.push({ field: 'table', message: 'The table has no rows to draw.' });
|
|
448
|
+
// Pie, doughnut and ranking draw the first series.
|
|
449
|
+
const single = type === 'pie' || type === 'doughnut' || type === 'ranking';
|
|
450
|
+
const drawn = single ? table.series.slice(0, 1) : table.series;
|
|
451
|
+
if ((type === 'pie' || type === 'doughnut') && drawn.some((s) => s.values.some((v) => v !== null && v < 0))) {
|
|
452
|
+
errors.push({ field: 'type', message: `A ${type === 'pie' ? 'pie' : 'doughnut'} cannot show a negative value, and ${drawn[0].name} has one. Pick a bar or line chart.` });
|
|
453
|
+
}
|
|
454
|
+
if (errors.length)
|
|
455
|
+
return { ok: false, errors };
|
|
456
|
+
const plugins = title ? { title: { display: true, text: title } } : {};
|
|
457
|
+
const options = {
|
|
458
|
+
...(type === 'horizontal' ? { indexAxis: 'y' } : {}),
|
|
459
|
+
...(Object.keys(plugins).length ? { plugins } : {}),
|
|
460
|
+
};
|
|
461
|
+
// A ranking is built where the ranking guide's maker builds it, so the two cannot drift apart.
|
|
462
|
+
const config = type === 'ranking'
|
|
463
|
+
? rankingConfig({ labels: table.labels, values: drawn[0].values, name: drawn[0].name, title })
|
|
464
|
+
: {
|
|
465
|
+
type: type === 'horizontal' ? 'bar' : type,
|
|
466
|
+
data: { labels: table.labels, datasets: drawn.map((s) => ({ label: s.name, data: s.values })) },
|
|
467
|
+
...(Object.keys(options).length ? { options } : {}),
|
|
468
|
+
};
|
|
469
|
+
const alt = altOf(table, type, title, drawn);
|
|
470
|
+
const path = `/chart?c=${encode(JSON.stringify(config))}&w=${TABLE_WIDTH}&h=${TABLE_HEIGHT}&dpr=${TABLE_DPR}`;
|
|
471
|
+
if (path.length > TABLE_MAX_URL) {
|
|
472
|
+
const message = `The image URL would be ${path.length.toLocaleString('en-US')} characters, past the ${TABLE_MAX_URL.toLocaleString('en-US')} this page builds, because of how much the table holds. Get a short URL below: ChartPNG keeps the chart for 90 days and the URL stays short.`;
|
|
473
|
+
return { ok: false, errors: [{ field: 'url', message }], long: { length: path.length, path, width: TABLE_WIDTH, height: TABLE_HEIGHT, alt, config } };
|
|
474
|
+
}
|
|
475
|
+
return { ok: true, path, width: TABLE_WIDTH, height: TABLE_HEIGHT, alt, config };
|
|
476
|
+
}
|
|
477
|
+
// The three snippets for an image URL: Markdown for a README or a Notion page, HTML for an email, and
|
|
478
|
+
// the Google Sheets formula. The alt is escaped for each.
|
|
479
|
+
export function tableSnippets(url, alt, width, height) {
|
|
480
|
+
const html = (text) => text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
481
|
+
return {
|
|
482
|
+
markdown: `![${alt.replace(/[\\[\]]/g, '\\$&')}](${url})`,
|
|
483
|
+
html: `<img src="${html(url)}" alt="${html(alt)}" width="${width}" height="${height}">`,
|
|
484
|
+
sheets: `=IMAGE("${url.replace(/"/g, '""')}")`,
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
// The table the "Use an example" button pastes: a header and two series, tab separated as a spreadsheet copies.
|
|
488
|
+
export const TABLE_EXAMPLE = [
|
|
489
|
+
['Month', 'Signups', 'Trials'],
|
|
490
|
+
['Jan', '120', '45'],
|
|
491
|
+
['Feb', '150', '60'],
|
|
492
|
+
['Mar', '180', '72'],
|
|
493
|
+
['Apr', '210', '80'],
|
|
494
|
+
['May', '260', '95'],
|
|
495
|
+
['Jun', '300', '110'],
|
|
496
|
+
]
|
|
497
|
+
.map((row) => row.join('\t'))
|
|
498
|
+
.join('\n');
|
|
499
|
+
export const TABLE_EXAMPLE_SETTINGS = { type: 'bar', title: 'Signups and trials by month' };
|
|
500
|
+
// The example, built the way the page builds it. Throws if the example stops being valid.
|
|
501
|
+
export function tableExample() {
|
|
502
|
+
const parsed = parseTable(TABLE_EXAMPLE);
|
|
503
|
+
if (!parsed.ok)
|
|
504
|
+
throw new Error(`the table example does not parse: ${parsed.error}`);
|
|
505
|
+
const made = tableChartUrl(parsed.table, TABLE_EXAMPLE_SETTINGS);
|
|
506
|
+
if (!made.ok)
|
|
507
|
+
throw new Error(`the table example is not valid: ${made.errors.map((e) => e.message).join(' ')}`);
|
|
508
|
+
return made;
|
|
509
|
+
}
|
|
510
|
+
export const GRID_TYPES = TABLE_CHART_TYPES.filter((t) => t.id === 'bar' || t.id === 'line' || t.id === 'pie');
|
|
511
|
+
// The table the landing starts with: the same numbers as its sample config.
|
|
512
|
+
export const GRID_EXAMPLE = 'Day\tSignups\nMon\t12\nTue\t19\nWed\t7\nThu\t15\nFri\t22';
|
|
513
|
+
// The cells of a pasted table, row by row, split as parseTable() splits them. Empty lines are
|
|
514
|
+
// dropped. The grid uses it to spread a paste over its cells.
|
|
515
|
+
export function splitTable(text) {
|
|
516
|
+
const normal = text.replace(/\r\n?/g, '\n');
|
|
517
|
+
return splitCells(normal, DELIMITER_CHARS[detectDelimiter(normal)])
|
|
518
|
+
.rows.map((row) => row.map((cell) => cell.trim()))
|
|
519
|
+
.filter((row) => row.some((cell) => cell !== ''));
|
|
520
|
+
}
|
|
521
|
+
export function tableToConfig(text, type = 'bar') {
|
|
522
|
+
const fail = (error) => ({ ok: false, error });
|
|
523
|
+
const rows = splitTable(text);
|
|
524
|
+
if (rows.length < 2)
|
|
525
|
+
return fail('A chart needs at least two rows: the column names, then one row of data.');
|
|
526
|
+
const width = Math.max(...rows.map((row) => row.length));
|
|
527
|
+
if (width < 2)
|
|
528
|
+
return fail('Each row needs a label and at least one number, in separate columns.');
|
|
529
|
+
if (rows.length - 1 > TABLE_MAX_ROWS)
|
|
530
|
+
return fail(`That is ${rows.length - 1} rows of data; a chart here takes up to ${TABLE_MAX_ROWS}.`);
|
|
531
|
+
if (width - 1 > TABLE_MAX_SERIES)
|
|
532
|
+
return fail(`That is ${width - 1} columns of numbers; a chart here takes up to ${TABLE_MAX_SERIES}.`);
|
|
533
|
+
const parsed = parseTable(text, { header: true });
|
|
534
|
+
// The cell that is not a number comes first: it says more than "no column of numbers".
|
|
535
|
+
const [bad] = parsed.skipped ?? [];
|
|
536
|
+
if (bad)
|
|
537
|
+
return fail(bad.row === 0 ? `Column "${bad.name}" has no numbers. Type one in each row.` : `Row ${bad.row}, column "${bad.name}": "${bad.sample}" is not a number.`);
|
|
538
|
+
if (!parsed.ok)
|
|
539
|
+
return fail(parsed.error);
|
|
540
|
+
const [gap] = parsed.gaps;
|
|
541
|
+
if (gap)
|
|
542
|
+
return fail(gap.sample === '' ? `Row ${gap.row}, column "${gap.name}" is empty. Type a number.` : `Row ${gap.row}, column "${gap.name}": "${gap.sample}" is not a number.`);
|
|
543
|
+
if (type === 'pie' && parsed.table.series.length > 1)
|
|
544
|
+
return fail('A pie chart takes one column of numbers. Remove the others or pick bar or line.');
|
|
545
|
+
const made = tableChartUrl(parsed.table, { type, title: '' });
|
|
546
|
+
// The landing draws at its own size and offers POST for a long config, so only the config is taken.
|
|
547
|
+
const config = made.ok ? made.config : made.long?.config;
|
|
548
|
+
if (!config)
|
|
549
|
+
return fail(made.ok ? '' : made.errors[0].message);
|
|
550
|
+
return { ok: true, config, rows: parsed.table.labels.length, series: parsed.table.series.length, notes: parsed.notes };
|
|
551
|
+
}
|
|
552
|
+
// Only text and numbers are cells: anything else in a hostile config reads as empty, never thrown on.
|
|
553
|
+
const cellText = (value) => (typeof value === 'string' || typeof value === 'number' ? String(value) : '').replace(/[\t\r\n]+/g, ' ').trim();
|
|
554
|
+
// `hosts` are the hosts whose /chart URLs are ours: the page's own and the public domain.
|
|
555
|
+
// Returns null when the text is not one of our chart URLs, so the caller reads it as a table.
|
|
556
|
+
export function tableFromChartUrl(text, hosts) {
|
|
557
|
+
const line = text.trim();
|
|
558
|
+
if (!/^https?:\/\/\S+$/.test(line))
|
|
559
|
+
return null;
|
|
560
|
+
let url;
|
|
561
|
+
try {
|
|
562
|
+
url = new URL(line);
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
if (!hosts.includes(url.host))
|
|
568
|
+
return null;
|
|
569
|
+
const fail = (message) => ({ kind: 'error', message });
|
|
570
|
+
if (/^\/c\/[^/]+\.png$/.test(url.pathname))
|
|
571
|
+
return fail('A short URL does not carry the chart, so it cannot be read back. Paste the long image URL, or the table again.');
|
|
572
|
+
if (url.pathname !== '/chart')
|
|
573
|
+
return null;
|
|
574
|
+
// A chart that reads a Google Sheet is edited in the sheet; the page shows it from its link.
|
|
575
|
+
const sheet = url.searchParams.get('sheet');
|
|
576
|
+
if (sheet !== null) {
|
|
577
|
+
return /^[A-Za-z0-9_-]{25,100}$/.test(sheet) ? { kind: 'sheet', path: `${url.pathname}${url.search}` } : fail('That URL reads a Google Sheet, but the sheet in it is not a sheet id. Paste the link of the sheet instead.');
|
|
578
|
+
}
|
|
579
|
+
const raw = url.searchParams.get('c') ?? url.searchParams.get('chart');
|
|
580
|
+
if (!raw)
|
|
581
|
+
return fail('That URL has no chart in it: the c parameter is missing.');
|
|
582
|
+
let config;
|
|
583
|
+
try {
|
|
584
|
+
config = JSON.parse(raw);
|
|
585
|
+
}
|
|
586
|
+
catch {
|
|
587
|
+
return fail('The chart in that URL is not plain JSON, so it cannot be turned back into a table. Open it on the home page to edit its config.');
|
|
588
|
+
}
|
|
589
|
+
const datasets = config?.data?.datasets;
|
|
590
|
+
const labels = config?.data?.labels;
|
|
591
|
+
const numeric = (value) => value === null || (typeof value === 'number' && Number.isFinite(value));
|
|
592
|
+
const tabular = typeof config === 'object' && config !== null && Array.isArray(datasets) && datasets.length > 0 && datasets.length <= TABLE_MAX_SERIES &&
|
|
593
|
+
datasets.every((d) => d && typeof d === 'object' && Array.isArray(d.data) && d.data.every(numeric));
|
|
594
|
+
const base = config?.type === 'bar' || config?.type === 'line' || config?.type === 'pie' || config?.type === 'doughnut' ? config.type : null;
|
|
595
|
+
if (!tabular || !base)
|
|
596
|
+
return fail('That chart was not made from a table (its data is not rows of plain numbers), so it cannot be edited here. Open it on the home page to edit its config.');
|
|
597
|
+
const series = datasets;
|
|
598
|
+
const rows = Math.max(...series.map((s) => s.data.length));
|
|
599
|
+
if (rows === 0 || rows > TABLE_MAX_ROWS)
|
|
600
|
+
return fail(`That chart has ${rows} rows; a table here takes 1 to ${TABLE_MAX_ROWS}.`);
|
|
601
|
+
const names = Array.isArray(labels) ? labels : [];
|
|
602
|
+
const head = ['Label', ...series.map((s, i) => cellText(s.label) || `Series ${i + 1}`)];
|
|
603
|
+
const body = Array.from({ length: rows }, (_, r) => [cellText(names[r]) || String(r + 1), ...series.map((s) => (typeof s.data[r] === 'number' ? String(s.data[r]) : ''))]);
|
|
604
|
+
const preset = config.options?.plugins?.chartpng?.preset;
|
|
605
|
+
const type = base === 'bar' && typeof preset === 'string' && preset.split(',').includes('ranking') ? 'ranking' : base === 'bar' && config.options?.indexAxis === 'y' ? 'horizontal' : base;
|
|
606
|
+
const title = config.options?.plugins?.title?.text;
|
|
607
|
+
// What a table cannot hold: said by the page, so nothing is lost in silence.
|
|
608
|
+
const left = [];
|
|
609
|
+
if (url.searchParams.has('k') || url.searchParams.has('s'))
|
|
610
|
+
left.push('its signature, so the new chart is unsigned and carries the watermark');
|
|
611
|
+
if (['w', 'h', 'width', 'height', 'dpr', 'devicePixelRatio'].some((name) => url.searchParams.has(name) && !['800', '450', '2'].includes(url.searchParams.get(name))))
|
|
612
|
+
left.push('its size');
|
|
613
|
+
if (['bkg', 'backgroundColor', 'theme', 'palette', 'preset'].some((name) => url.searchParams.has(name)))
|
|
614
|
+
left.push('its background, theme or palette');
|
|
615
|
+
const { title: _title, chartpng, ...otherPlugins } = (config.options?.plugins ?? {});
|
|
616
|
+
const { indexAxis: _axis, plugins: _plugins, ...otherOptions } = (config.options ?? {});
|
|
617
|
+
const ownSettings = chartpng && typeof chartpng === 'object' ? Object.keys(chartpng).filter((k) => !(k === 'preset' && type === 'ranking')) : [];
|
|
618
|
+
const styled = series.some((s) => Object.keys(s).some((k) => k !== 'label' && k !== 'data'));
|
|
619
|
+
if (Object.keys(otherOptions).length > 0 || Object.keys(otherPlugins).length > 0 || ownSettings.length > 0 || styled)
|
|
620
|
+
left.push('its colours and other options');
|
|
621
|
+
if (names.length > rows)
|
|
622
|
+
left.push('labels that had no number');
|
|
623
|
+
return { kind: 'table', text: [head, ...body].map((row) => row.join('\t')).join('\n'), type, title: typeof title === 'string' ? cut(title.trim(), MAX_TITLE) : '', left };
|
|
624
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ChartConfiguration, Plugin } from 'chart.js';
|
|
2
|
+
import type { ChartConfig } from './render.js';
|
|
3
|
+
export declare const PALETTE: string[];
|
|
4
|
+
export declare const THEMES: Record<string, {
|
|
5
|
+
light: string[];
|
|
6
|
+
dark: string[];
|
|
7
|
+
}>;
|
|
8
|
+
export declare const THEME_NAMES: string[];
|
|
9
|
+
export declare function paletteFor(theme: unknown, background: string): string[];
|
|
10
|
+
export declare const PALETTE_MAX = 12;
|
|
11
|
+
export declare function readPalette(value: unknown): string[];
|
|
12
|
+
export declare function resolvePalette(settings: Record<string, unknown>, background: string): string[];
|
|
13
|
+
export declare const FONT_FAMILY = "IBM Plex Sans";
|
|
14
|
+
export declare const FONT_EXT = "IBM Plex Sans Ext";
|
|
15
|
+
export declare const FONT_STACK = "\"IBM Plex Sans\", \"IBM Plex Sans Ext\"";
|
|
16
|
+
declare const LIGHT: {
|
|
17
|
+
ink: string;
|
|
18
|
+
muted: string;
|
|
19
|
+
grid: string;
|
|
20
|
+
axis: string;
|
|
21
|
+
label: string;
|
|
22
|
+
};
|
|
23
|
+
type Options = Record<string, any>;
|
|
24
|
+
type Ink = typeof LIGHT;
|
|
25
|
+
export declare function isDark(background: string): boolean;
|
|
26
|
+
export declare const inkFor: (background: string) => Ink;
|
|
27
|
+
export declare const chipFor: (background: string) => {
|
|
28
|
+
fill: string;
|
|
29
|
+
stroke: string;
|
|
30
|
+
text: string;
|
|
31
|
+
};
|
|
32
|
+
export declare function underlay(base: Options, user: Options): Options;
|
|
33
|
+
export declare const valuesPlugin: Plugin;
|
|
34
|
+
export declare function applyTheme(config: ChartConfig, background: string, output?: boolean): Pick<ChartConfiguration, 'data'> & {
|
|
35
|
+
options: Options;
|
|
36
|
+
};
|
|
37
|
+
export {};
|