report-studio 1.2.2 → 1.3.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.
Files changed (46) hide show
  1. package/README.md +254 -3
  2. package/dist/designer-Dj330bWd.js +4690 -0
  3. package/dist/designer.js +1 -1
  4. package/dist/index.js +2 -2
  5. package/dist/react-designer.js +1 -1
  6. package/dist/react.js +1 -1
  7. package/dist/viewer-BewnkhfP.js +4028 -0
  8. package/package.json +2 -2
  9. package/src/designer/blank.js +0 -1
  10. package/src/designer/canvas.js +172 -54
  11. package/src/designer/designer.js +313 -12
  12. package/src/designer/dialog.js +609 -5
  13. package/src/designer/fields.js +128 -11
  14. package/src/designer/geometry.js +77 -4
  15. package/src/designer/grouping.js +556 -0
  16. package/src/designer/icons.js +9 -0
  17. package/src/designer/menu.js +50 -6
  18. package/src/designer/panel.js +478 -38
  19. package/src/designer/rulers.js +14 -6
  20. package/src/designer/sample-data.js +112 -31
  21. package/src/designer/select.js +3 -2
  22. package/src/designer/structure.js +126 -12
  23. package/src/designer/styles.css +661 -27
  24. package/src/designer/tokens.js +38 -11
  25. package/src/engine/calculate.js +487 -0
  26. package/src/engine/csv.js +17 -9
  27. package/src/engine/format.js +483 -0
  28. package/src/engine/group.js +350 -70
  29. package/src/engine/highlight.js +224 -0
  30. package/src/engine/index.js +8 -1
  31. package/src/engine/measure.js +53 -26
  32. package/src/engine/paginate.js +189 -92
  33. package/src/engine/resolve.js +117 -10
  34. package/src/engine/rows.js +71 -8
  35. package/src/engine/search.js +12 -4
  36. package/src/engine/tables.js +309 -11
  37. package/src/engine/validate.js +265 -8
  38. package/src/engine/xlsx-style.js +50 -4
  39. package/src/engine/xlsx.js +91 -21
  40. package/src/index.js +18 -0
  41. package/src/render/items.js +61 -10
  42. package/src/render/report.css +0 -5
  43. package/types/index.d.ts +96 -8
  44. package/types/layout.d.ts +156 -2
  45. package/dist/designer-DQlfKnTr.js +0 -3416
  46. package/dist/viewer-BSPNCNRU.js +0 -2912
@@ -7,7 +7,12 @@
7
7
  */
8
8
 
9
9
 
10
- import { tablesOf, hasOwnGrouping } from './tables.js';
10
+ import { tablesOf, hasOwnGrouping, levelsOf, MAX_GROUP_LEVELS, GROUP_SORTS } from './tables.js';
11
+ import {
12
+ FORMAT_TYPES, GROUPINGS, NEGATIVES, ZEROS, SYMBOL_POSITIONS, MAX_DECIMALS
13
+ } from './format.js';
14
+ import { HIGHLIGHT_OPS, HIGHLIGHT_STYLE_KEYS } from './highlight.js';
15
+ import { parseExpression } from './calculate.js';
11
16
  import { designHeight } from './measure.js';
12
17
 
13
18
 
@@ -74,6 +79,8 @@ export function validateLayout(json) {
74
79
  issues.push('layout.groupBy must be a field name or null');
75
80
  }
76
81
 
82
+ validateFormat(json.format, 'layout.format', issues, false);
83
+
77
84
  const seenTypes = new Set();
78
85
 
79
86
  json.bands.forEach((band, i) => {
@@ -114,12 +121,18 @@ export function validateLayout(json) {
114
121
  /**
115
122
  * What the tables of a report may be, together.
116
123
  *
117
- * Any number of them, each bound to its own dataset - but two things they may
118
- * not do, because the engine has no honest way to print them:
124
+ * Any number of them, each bound to its own dataset, and any number of them
125
+ * grouped - each through a `grouping` of its own, which carries the bands its
126
+ * groups are drawn with. What they may not do, because the engine has no
127
+ * honest way to print it:
128
+ *
129
+ * Two tables grouped the older way. `groupBy` on a table borrows the report's
130
+ * groupHeader and groupFooter, and there is one of each - so both tables
131
+ * would draw their groups with the same heading. A second grouped table says
132
+ * so with a `grouping` of its own.
119
133
  *
120
- * Two grouped tables. groupHeader and groupFooter are the report's bands, so
121
- * both tables would draw their groups with the same heading - and a subtotal
122
- * in it would be summed over whichever table happened to be drawn.
134
+ * One table grouped both ways. Which of the two it meant is not something to
135
+ * guess at.
123
136
  *
124
137
  * Two tables side by side. Each table splits across pages on its own, so the
125
138
  * one on the left would run to page three before the one on the right began,
@@ -142,14 +155,17 @@ function validateTables(json, bands, issues) {
142
155
  if (table.dataset != null && typeof table.dataset !== 'string') {
143
156
  issues.push(`table "${table.id}".dataset must be a dataset name or null`);
144
157
  }
158
+
159
+ validateGrouping(table, issues);
145
160
  }
146
161
 
147
162
  const grouped = tables.filter(hasOwnGrouping);
148
163
 
149
164
  if (grouped.length > 1) {
150
165
  issues.push(
151
- `${grouped.length} tables are grouped (${grouped.map(t => `"${t.id}"`).join(', ')}); ` +
152
- `a report groups one, because groupHeader and groupFooter are shared`);
166
+ `${grouped.length} tables are grouped by groupBy (${grouped.map(t => `"${t.id}"`).join(', ')}); ` +
167
+ `only one can use the report's groupHeader and groupFooter - give the others ` +
168
+ `a grouping of their own`);
153
169
  }
154
170
 
155
171
  if (grouped.length > 0 && json.groupBy == null
@@ -159,6 +175,16 @@ function validateTables(json, bands, issues) {
159
175
  `no groupHeader or groupFooter band to show it`);
160
176
  }
161
177
 
178
+ /** layout.groupBy means the first table, unless a table names its own groupBy */
179
+ const first = tables[0];
180
+
181
+ if (json.groupBy != null && grouped.length === 0
182
+ && first && levelsOf(first).length > 0) {
183
+ issues.push(
184
+ `layout.groupBy groups the first table, "${first.id}", which already has a ` +
185
+ `grouping of its own; remove one of the two`);
186
+ }
187
+
162
188
  for (const band of bands) {
163
189
  if (!Array.isArray(band?.items)) continue;
164
190
 
@@ -182,6 +208,122 @@ function validateTables(json, bands, issues) {
182
208
  }
183
209
 
184
210
 
211
+ /**
212
+ * A table's own grouping: a list of levels, each a field and the bands its
213
+ * groups are drawn with.
214
+ *
215
+ * "grouping": [{ "by": "region", "header": { "height": 30, "items": [] }, "footer": null }]
216
+ *
217
+ * Levels are outermost first; each after the first groups within the groups of
218
+ * the one before. Grouping twice by the same field is refused - every group of
219
+ * the inner level would be the whole of its outer group, drawn twice over.
220
+ *
221
+ * @param {object} table
222
+ * @param {string[]} issues
223
+ */
224
+ function validateGrouping(table, issues) {
225
+ if (table.grouping == null) return;
226
+
227
+ const where = `table "${table.id}".grouping`;
228
+
229
+ if (!Array.isArray(table.grouping)) {
230
+ issues.push(`${where} must be a list of group levels, or null`);
231
+ return;
232
+ }
233
+
234
+ if (table.grouping.length > 0 && hasOwnGrouping(table)) {
235
+ issues.push(
236
+ `table "${table.id}" is grouped both by groupBy and by grouping; remove groupBy`);
237
+ }
238
+
239
+ if (table.grouping.length > MAX_GROUP_LEVELS) {
240
+ issues.push(
241
+ `${where} has ${table.grouping.length} levels; a table may be grouped at ` +
242
+ `${MAX_GROUP_LEVELS} at most`);
243
+ }
244
+
245
+ /** the level each field was first grouped by, to name a repeat against */
246
+ const seen = new Map();
247
+
248
+ table.grouping.forEach((level, n) => {
249
+ const at = `${where}[${n}]`;
250
+
251
+ if (level == null || typeof level !== 'object' || Array.isArray(level)) {
252
+ issues.push(`${at} must be an object with by, header and footer`);
253
+ return;
254
+ }
255
+
256
+ if (typeof level.by !== 'string' || level.by === '') {
257
+ issues.push(`${at}.by must be the name of the field to group by`);
258
+ } else if (seen.has(level.by)) {
259
+ issues.push(
260
+ `${at} groups by "${level.by}" again, as ${where}[${seen.get(level.by)}] ` +
261
+ `already does; group each level by a different field`);
262
+ } else {
263
+ seen.set(level.by, n);
264
+ }
265
+
266
+ if (level.sort != null && !GROUP_SORTS.includes(level.sort)) {
267
+ issues.push(
268
+ `${at}.sort must be ${GROUP_SORTS.map(s => `"${s}"`).join(' or ')}, or null ` +
269
+ `to keep the groups in the order they are first seen`);
270
+ }
271
+
272
+ if (level.newPage != null && typeof level.newPage !== 'boolean') {
273
+ issues.push(`${at}.newPage must be true or false`);
274
+ }
275
+
276
+ validateGroupBand(level.header, `${at}.header`, issues);
277
+ validateGroupBand(level.footer, `${at}.footer`, issues);
278
+
279
+ if (level.header == null && level.footer == null) {
280
+ issues.push(`${at} has neither a header nor a footer to show its groups`);
281
+ }
282
+ });
283
+ }
284
+
285
+
286
+ /**
287
+ * One of a table's group bands: a band in all but its place in the file, so
288
+ * its items are checked the same way. It may not hold a table - it is drawn
289
+ * once for every group, inside the table it belongs to.
290
+ *
291
+ * @param {*} band
292
+ * @param {string} where
293
+ * @param {string[]} issues
294
+ */
295
+ function validateGroupBand(band, where, issues) {
296
+ if (band == null) return;
297
+
298
+ if (typeof band !== 'object' || Array.isArray(band)) {
299
+ issues.push(`${where} must be a band with items, or null`);
300
+ return;
301
+ }
302
+
303
+ if (band.height != null && !(typeof band.height === 'number' && band.height >= 0)) {
304
+ issues.push(`${where}.height must be a number of pixels`);
305
+ }
306
+
307
+ if (band.background != null && (typeof band.background !== 'string' || band.background === '')) {
308
+ issues.push(`${where}.background must be a colour, or null`);
309
+ }
310
+
311
+ if (!Array.isArray(band.items)) {
312
+ issues.push(`${where}.items must be an array`);
313
+ return;
314
+ }
315
+
316
+ band.items.forEach((item, j) => {
317
+ if (item?.type === 'table') {
318
+ issues.push(`${where}.items[${j}] is a table; a group band cannot hold one`);
319
+ return;
320
+ }
321
+
322
+ validateItem(item, `${where}.items[${j}]`, issues);
323
+ });
324
+ }
325
+
326
+
185
327
  function validatePage(page, issues) {
186
328
  if (page == null || typeof page !== 'object') {
187
329
  issues.push('layout.page must be an object with width, height and margin');
@@ -231,6 +373,8 @@ function validateItem(item, where, issues) {
231
373
  if (typeof item.value !== 'string') {
232
374
  issues.push(`${where}.value must be a string`);
233
375
  }
376
+ validateFormat(item.format, `${where}.format`, issues, true);
377
+ validateHighlight(item.highlight, `${where}.highlight`, issues, false);
234
378
  return;
235
379
  }
236
380
 
@@ -275,10 +419,123 @@ function validateItem(item, where, issues) {
275
419
  if (col == null || typeof col.field !== 'string' || col.field === '') {
276
420
  issues.push(`${where}.columns[${k}].field must be a non-empty string`);
277
421
  }
422
+ validateFormat(col?.format, `${where}.columns[${k}].format`, issues, true);
423
+
424
+ if (col?.expression != null && col.expression !== '') {
425
+ const parsed = typeof col.expression === 'string'
426
+ ? parseExpression(col.expression)
427
+ : { error: 'must be text' };
428
+ if (parsed.error) issues.push(`${where}.columns[${k}].expression ${parsed.error}`);
429
+ }
430
+ validateHighlight(col?.highlight, `${where}.columns[${k}].highlight`, issues, false);
431
+ });
432
+
433
+ validateHighlight(item.rowHighlight, `${where}.rowHighlight`, issues, true);
434
+ }
435
+
436
+
437
+ /**
438
+ * A list of highlight rules: each a condition and the style it gives.
439
+ *
440
+ * @param {*} rules
441
+ * @param {string} where
442
+ * @param {string[]} issues
443
+ * @param {boolean} needsField whether every rule must name a field - a row's
444
+ * rules do, a row having no one value of its own to test
445
+ */
446
+ function validateHighlight(rules, where, issues, needsField) {
447
+ if (rules == null) return;
448
+
449
+ if (!Array.isArray(rules)) {
450
+ issues.push(`${where} must be a list of rules, or null`);
451
+ return;
452
+ }
453
+
454
+ rules.forEach((rule, n) => {
455
+ const at = `${where}[${n}]`;
456
+ const when = rule?.when;
457
+
458
+ if (when == null || typeof when !== 'object') {
459
+ issues.push(`${at}.when must say what to test`);
460
+ return;
461
+ }
462
+
463
+ if (!HIGHLIGHT_OPS.includes(when.op)) {
464
+ issues.push(`${at}.when.op "${when.op}" is not one of: ${HIGHLIGHT_OPS.join(', ')}`);
465
+ }
466
+
467
+ if (when.field != null && (typeof when.field !== 'string' || when.field === '')) {
468
+ issues.push(`${at}.when.field must be the name of a field`);
469
+ } else if (needsField && when.field == null) {
470
+ issues.push(`${at}.when.field must name the field of the row to test`);
471
+ }
472
+
473
+ if (when.op === 'between' && (when.value == null || when.to == null)) {
474
+ issues.push(`${at}.when needs both value and to for between`);
475
+ }
476
+
477
+ const style = rule.style;
478
+ if (style == null || typeof style !== 'object' || Array.isArray(style)) {
479
+ issues.push(`${at}.style must be an object`);
480
+ return;
481
+ }
482
+
483
+ for (const key of Object.keys(style)) {
484
+ if (!HIGHLIGHT_STYLE_KEYS.includes(key)) {
485
+ issues.push(`${at}.style.${key} is not one of: ${HIGHLIGHT_STYLE_KEYS.join(', ')}`);
486
+ }
487
+ }
278
488
  });
279
489
  }
280
490
 
281
491
 
492
+ /**
493
+ * A number or date format - a text item's, a column's, or the report's own
494
+ * defaults, which have every key but `type`. Every key is optional; what is
495
+ * there has to be one of the things format.js knows.
496
+ *
497
+ * @param {*} format
498
+ * @param {string} where
499
+ * @param {string[]} issues
500
+ * @param {boolean} typed whether it may say a `type` - the report's defaults may not
501
+ */
502
+ function validateFormat(format, where, issues, typed) {
503
+ if (format == null) return;
504
+
505
+ if (typeof format !== 'object' || Array.isArray(format)) {
506
+ issues.push(`${where} must be an object, or null`);
507
+ return;
508
+ }
509
+
510
+ const oneOf = (key, list) => {
511
+ if (format[key] != null && !list.includes(format[key])) {
512
+ issues.push(`${where}.${key} "${format[key]}" is not one of: ${list.join(', ')}`);
513
+ }
514
+ };
515
+
516
+ if (typed) oneOf('type', FORMAT_TYPES);
517
+ else if (format.type != null) {
518
+ issues.push(`${where}.type is an item's or a column's to say, not the report's`);
519
+ }
520
+
521
+ oneOf('grouping', GROUPINGS);
522
+ oneOf('negative', NEGATIVES);
523
+ oneOf('zero', ZEROS);
524
+ oneOf('symbolPosition', SYMBOL_POSITIONS);
525
+
526
+ if (format.decimals != null && !(Number.isInteger(format.decimals)
527
+ && format.decimals >= 0 && format.decimals <= MAX_DECIMALS)) {
528
+ issues.push(`${where}.decimals must be a whole number from 0 to ${MAX_DECIMALS}`);
529
+ }
530
+
531
+ for (const key of ['symbol', 'pattern']) {
532
+ if (format[key] != null && typeof format[key] !== 'string') {
533
+ issues.push(`${where}.${key} must be text`);
534
+ }
535
+ }
536
+ }
537
+
538
+
282
539
  /**
283
540
  * A box carries no content either - it is a rule bent round four sides - so what
284
541
  * there is to check is the pen and the corner. Everything is optional: a bare
@@ -238,15 +238,41 @@ export function excelBorder({ style = 'solid', width = 1, color = null } = {}) {
238
238
  export function cellFormat(design) {
239
239
  if (!design) return null;
240
240
 
241
- if (design.kind === 'text') return textFormat(design.style ?? {});
241
+ if (design.kind === 'text') return lit(textFormat(design.style ?? {}), design.highlight);
242
242
  if (design.kind === 'head' || design.kind === 'cell') {
243
- return tableFormat(design.kind === 'head', design.column ?? {}, design.table ?? {});
243
+ return lit(tableFormat(design.kind === 'head', design.column ?? {}, design.table ?? {}),
244
+ design.highlight);
244
245
  }
245
246
 
246
247
  return null;
247
248
  }
248
249
 
249
250
 
251
+ /**
252
+ * A format with a highlight rule's style laid over it: the text colour, the
253
+ * fill, bold and italic, each only where the rule set it - the same four the
254
+ * page draws, so a red figure on the page is a red figure in the sheet.
255
+ *
256
+ * @param {object} format from textFormat or tableFormat
257
+ * @param {object|null|undefined} highlight from highlight.js
258
+ * @returns {object}
259
+ */
260
+ function lit(format, highlight) {
261
+ if (!highlight) return format;
262
+
263
+ const font = { ...format.font };
264
+ if (highlight.color) font.color = argb(highlight.color) ?? font.color;
265
+ if (highlight.fontWeight) font.bold = isBold(highlight.fontWeight);
266
+ if (highlight.fontStyle) font.italic = highlight.fontStyle === 'italic' || highlight.fontStyle === 'oblique';
267
+
268
+ return {
269
+ ...format,
270
+ font,
271
+ fill: highlight.background ? (argb(highlight.background) ?? format.fill) : format.fill
272
+ };
273
+ }
274
+
275
+
250
276
  /**
251
277
  * A text item: its own font, colour and alignment. Text sits at the top of its
252
278
  * box on the page and never wraps here - a cell's neighbours are empty more
@@ -343,6 +369,20 @@ export function createStyles() {
343
369
  const borders = ['<border><left/><right/><top/><bottom/><diagonal/></border>'];
344
370
  const xfs = ['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'];
345
371
 
372
+ /** custom number format codes, by code; Excel numbers its own from 164 up */
373
+ const numFmts = new Map();
374
+
375
+ /**
376
+ * The id of a custom number format, such as "#,##0.00" or "dd/mm/yyyy",
377
+ * adding it the first time it is asked for.
378
+ * @param {string} code
379
+ * @returns {number}
380
+ */
381
+ function numFmt(code) {
382
+ if (!numFmts.has(code)) numFmts.set(code, 164 + numFmts.size);
383
+ return numFmts.get(code);
384
+ }
385
+
346
386
  const index = new Map([
347
387
  ...fonts.map((x, i) => [x, i]),
348
388
  ...fills.map((x, i) => [x, i]),
@@ -401,7 +441,8 @@ export function createStyles() {
401
441
 
402
442
  /**
403
443
  * @param {object|null} format from cellFormat, or { font: { bold } } and the like
404
- * @param {number} [numFmtId=0] a built-in number format, such as 14 for a date
444
+ * @param {number} [numFmtId=0] a number format's id: built in, such as 14 for a
445
+ * date, or one numFmt handed out
405
446
  * @returns {number} the cell format's index
406
447
  */
407
448
  function xf(format, numFmtId = 0) {
@@ -434,6 +475,11 @@ export function createStyles() {
434
475
  function xml() {
435
476
  return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
436
477
  '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
478
+ (numFmts.size
479
+ ? `<numFmts count="${numFmts.size}">${[...numFmts]
480
+ .map(([code, id]) => `<numFmt numFmtId="${id}" formatCode="${escapeAttr(code)}"/>`)
481
+ .join('')}</numFmts>`
482
+ : '') +
437
483
  `<fonts count="${fonts.length}">${fonts.join('')}</fonts>` +
438
484
  `<fills count="${fills.length}">${fills.join('')}</fills>` +
439
485
  `<borders count="${borders.length}">${borders.join('')}</borders>` +
@@ -443,7 +489,7 @@ export function createStyles() {
443
489
  '</styleSheet>';
444
490
  }
445
491
 
446
- return { xf, xml, get size() { return xfs.length; } };
492
+ return { xf, numFmt, xml, get size() { return xfs.length; } };
447
493
  }
448
494
 
449
495
 
@@ -34,7 +34,7 @@
34
34
  * never the layout or the data.
35
35
  */
36
36
 
37
- import { reportLayout, reportRows, tableRows, reportTables, columnLabel } from './rows.js';
37
+ import { reportLayout, reportRows, tableRows, reportTables, columnLabel, groupColumns } from './rows.js';
38
38
  import {
39
39
  argb, cellFormat, createStyles, columnChars, indentLevels, DEFAULT_COLUMN_PX, points
40
40
  } from './xlsx-style.js';
@@ -44,6 +44,8 @@ import {
44
44
  } from './xlsx-drawing.js';
45
45
  import { imageSrc } from '../render/items.js';
46
46
  import { zip } from './zip.js';
47
+ import { excelNumberFormat, excelValue } from './format.js';
48
+ import { cellHighlight } from './highlight.js';
47
49
 
48
50
 
49
51
  /** Excel's hard limits; past them it refuses the whole file */
@@ -134,7 +136,7 @@ const PLACEHOLDER = /\{[^{}]+\}/;
134
136
  * @param {string} [options.reportSheetName='Report']
135
137
  * @param {boolean} [options.groupColumn=true] prepend the group key on a
136
138
  * grouped table's sheet, as toCSV does
137
- * @param {string} [options.groupLabel='Group']
139
+ * @param {string|string[]} [options.groupLabel='Group'] as toCSV's
138
140
  * @param {Object<string, Uint8Array|ArrayBuffer>|Map} [options.images] the
139
141
  * bytes of pictures that are not `data:` URIs, keyed by their src - which is
140
142
  * what toXLSXAsync fetches. A picture with no bytes is left out
@@ -299,7 +301,9 @@ function reportSheet(pages, name, styled, images) {
299
301
  if (isText) return placeText(row, grid, formats);
300
302
 
301
303
  return [{
302
- cells: row.cells.map((value, i) => ({ value, format: formats(row.design?.[i]) })),
304
+ cells: row.cells.map((value, i) => ({
305
+ ...typed(value, row.design?.[i]), format: formats(row.design?.[i])
306
+ })),
303
307
  page: row.page, top: row.top, own: row.height
304
308
  }];
305
309
  });
@@ -324,13 +328,14 @@ function reportSheet(pages, name, styled, images) {
324
328
 
325
329
  /**
326
330
  * One table as a sheet: the labels, then every row across every page.
327
- * Grouped tables get the group key as a first column, so the groups survive a
328
- * sort - the same choice toCSV makes.
331
+ * Grouped tables get the group key as a first column - one per level, for a
332
+ * table grouped within its groups - so the groups survive a sort: the same
333
+ * choice toCSV makes.
329
334
  */
330
335
  function tableSheet(table, styled, groupColumn, groupLabel) {
331
- const grouped = groupColumn && table.rows.some(r => r.group !== null);
332
- const columns = grouped ? [{ field: null, align: 'left' }, ...table.columns] : table.columns;
333
- const labels = grouped ? [groupLabel, ...table.columns.map(columnLabel)] : table.columns.map(columnLabel);
336
+ const groups = groupColumn ? groupColumns(table, groupLabel) : { labels: [], cells: () => [] };
337
+ const columns = [...groups.labels.map(() => ({ field: null, align: 'left' })), ...table.columns];
338
+ const labels = [...groups.labels, ...table.columns.map(columnLabel)];
334
339
 
335
340
  /**
336
341
  * One format object per column, so the writer resolves each once. A
@@ -354,17 +359,37 @@ function tableSheet(table, styled, groupColumn, groupLabel) {
354
359
  const cellFormats = columns.map(column =>
355
360
  styled ? cellFormat({ kind: 'cell', column, table: table.table }) : null);
356
361
 
362
+ /** a highlighted cell's format, made once per column and style */
363
+ const litFormats = new Map();
364
+ const formatFor = (i, highlight) => {
365
+ if (!styled || !highlight) return cellFormats[i];
366
+
367
+ const key = `${i}|${JSON.stringify(highlight)}`;
368
+ if (!litFormats.has(key)) {
369
+ litFormats.set(key, cellFormat({ kind: 'cell', column: columns[i], table: table.table, highlight }));
370
+ }
371
+ return litFormats.get(key);
372
+ };
373
+ const groupWidth = columns.length - table.columns.length;
374
+
357
375
  const rows = [{
358
376
  cells: labels.map((value, i) => ({ value, format: headFormats[i] })),
359
377
  height: styled ? table.headerHeight : null
360
378
  }];
361
379
 
362
- for (const { group, row, height } of table.rows) {
380
+ for (const entry of table.rows) {
381
+ const { row, height } = entry;
363
382
  const values = table.columns.map(c => row?.[c.field]);
364
- const cells = grouped ? [group, ...values] : values;
383
+ const cells = [...groups.cells(entry), ...values];
365
384
 
366
385
  rows.push({
367
- cells: cells.map((value, i) => ({ value, format: cellFormats[i] })),
386
+ cells: cells.map((value, i) => ({
387
+ ...typed(value, { kind: 'cell', column: columns[i] }),
388
+ /** the group columns are the report's, not the table's, and take no rules */
389
+ format: i < groupWidth
390
+ ? cellFormats[i]
391
+ : formatFor(i, cellHighlight(table.table, columns[i], row))
392
+ })),
368
393
  height: styled ? height : null
369
394
  });
370
395
  }
@@ -457,7 +482,10 @@ function placeText(row, grid, formats) {
457
482
  row.cells.forEach((raw, i) => {
458
483
  const design = row.design[i];
459
484
  const align = formats(design)?.alignment?.horizontal ?? 'left';
460
- const value = numericText(raw, design.template);
485
+ /** a formatted total is a real number; an unformatted one is guessed at, as ever */
486
+ const typedValue = typed(raw, design);
487
+ const value = typedValue.numFmt ? typedValue.value : numericText(raw, design.template);
488
+ const numFmt = typedValue.numFmt;
461
489
 
462
490
  const x = Math.max(0, Number(design.x) || 0);
463
491
  const w = Math.max(1, Number(design.w) || 1);
@@ -471,14 +499,14 @@ function placeText(row, grid, formats) {
471
499
  const across = formats.text(design, { centred: true });
472
500
 
473
501
  line = lineFor(span);
474
- line.cells[first] = { value, format: across };
502
+ line.cells[first] = { value, format: across, numFmt };
475
503
  for (let c = first + 1; c <= last; c++) line.cells[c] = { value: null, format: across };
476
504
  } else {
477
505
  const c = align === 'right' ? last : first;
478
506
  const inset = align === 'right' ? grid.right(c) - (x + w) : x - grid.left(c);
479
507
 
480
508
  line = lineFor([c]);
481
- line.cells[c] = { value, format: formats.text(design, { indent: indentLevels(inset) }) };
509
+ line.cells[c] = { value, format: formats.text(design, { indent: indentLevels(inset) }), numFmt };
482
510
  }
483
511
 
484
512
  line.top = Math.min(line.top, design.y);
@@ -489,6 +517,35 @@ function placeText(row, grid, formats) {
489
517
  }
490
518
 
491
519
 
520
+ /**
521
+ * A value as the workbook should hold it, when the report gave it a format:
522
+ * the real number or date, and the code that shows it as the report printed
523
+ * it - so 1,00,000.00 on the page is 100000 in the cell, and still adds up.
524
+ *
525
+ * A table cell is typed by its column's format. A text item is typed only when
526
+ * it is one placeholder and nothing else - a grand total - which is when the
527
+ * engine keeps the value it printed as `raw`; "Total: ₹1,200" stays text.
528
+ *
529
+ * @param {*} value what the row or the page holds
530
+ * @param {object|undefined} design the cell's descriptor, from rows.js
531
+ * @returns {{value: *, numFmt?: string}}
532
+ */
533
+ function typed(value, design) {
534
+ const source = design?.kind === 'cell' ? design.column?.format
535
+ : design?.kind === 'text' ? design.format
536
+ : null;
537
+
538
+ const code = excelNumberFormat(source);
539
+ if (!code) return { value };
540
+
541
+ const raw = design.kind === 'text' ? design.raw : value;
542
+ if (raw === undefined) return { value };
543
+
544
+ const number = excelValue(raw, source);
545
+ return number === null ? { value } : { value: number, numFmt: code };
546
+ }
547
+
548
+
492
549
  /**
493
550
  * A text item's value, as a number when it is a total: the item's template
494
551
  * holds a placeholder and what it printed is a plain number and nothing else.
@@ -807,8 +864,11 @@ function formatCache() {
807
864
  const key = design.column ?? design;
808
865
  if (!byColumn.has(key)) byColumn.set(key, {});
809
866
  const entry = byColumn.get(key);
810
- entry[design.kind] ??= cellFormat(design);
811
- return entry[design.kind];
867
+
868
+ /** a highlighted cell is its column's format and its rule's style - one per pair */
869
+ const variant = design.highlight ? `${design.kind}|${JSON.stringify(design.highlight)}` : design.kind;
870
+ entry[variant] ??= cellFormat(design);
871
+ return entry[variant];
812
872
  }
813
873
 
814
874
  formats.text = (design, { centred = false, indent = 0 } = {}) => {
@@ -816,7 +876,7 @@ function formatCache() {
816
876
  if (!byStyle.has(key)) byStyle.set(key, new Map());
817
877
  const variants = byStyle.get(key);
818
878
 
819
- const variant = `${centred}|${indent}`;
879
+ const variant = `${centred}|${indent}|${design.highlight ? JSON.stringify(design.highlight) : ''}`;
820
880
  if (!variants.has(variant)) {
821
881
  const base = cellFormat(design);
822
882
  variants.set(variant, {
@@ -907,7 +967,7 @@ function worksheet({ name, rows, frozen, gridLines, widths, width, drawing }, st
907
967
  rows.forEach((row, r) => {
908
968
  let cells = '';
909
969
  row.cells.forEach((c, i) => {
910
- if (c) cells += cell(`${columnName(i)}${r + 1}`, c.value, c.format, xfFor);
970
+ if (c) cells += cell(`${columnName(i)}${r + 1}`, c.value, c.format, xfFor, c.numFmt);
911
971
  });
912
972
 
913
973
  const height = Number(row.height) > 0
@@ -943,12 +1003,17 @@ function usedRange(width, height) {
943
1003
  }
944
1004
 
945
1005
 
946
- /** format object and number format to a cell format index, each pair resolved once */
1006
+ /**
1007
+ * format object and number format to a cell format index, each pair resolved
1008
+ * once. The number format is a built-in id, or a custom code from format.js.
1009
+ */
947
1010
  function xfResolver(styles) {
948
1011
  const cache = new WeakMap();
949
1012
  const plain = new Map();
950
1013
 
951
- return (format, numFmt) => {
1014
+ return (format, code) => {
1015
+ const numFmt = typeof code === 'string' ? styles.numFmt(code) : code;
1016
+
952
1017
  if (!format) {
953
1018
  if (!plain.has(numFmt)) plain.set(numFmt, styles.xf(null, numFmt));
954
1019
  return plain.get(numFmt);
@@ -971,8 +1036,10 @@ function xfResolver(styles) {
971
1036
  * @param {*} value the raw value from the row
972
1037
  * @param {object|null} format
973
1038
  * @param {Function} xfFor
1039
+ * @param {string} [code] the number format a typed value is shown with, from
1040
+ * format.js - a number or a date serial the report formats
974
1041
  */
975
- function cell(ref, value, format, xfFor) {
1042
+ function cell(ref, value, format, xfFor, code) {
976
1043
  const empty = value === null || value === undefined || value === '';
977
1044
  const isDate = value instanceof Date && !Number.isNaN(value.getTime());
978
1045
 
@@ -983,6 +1050,9 @@ function cell(ref, value, format, xfFor) {
983
1050
  numFmt = Number.isInteger(serial) ? NUMFMT_DATE : NUMFMT_DATE_TIME;
984
1051
  }
985
1052
 
1053
+ if (code && typeof value === 'number') numFmt = code;
1054
+ if (code && isDate) numFmt = code;
1055
+
986
1056
  const xf = xfFor(format, numFmt);
987
1057
  const s = xf ? ` s="${xf}"` : '';
988
1058