report-studio 1.2.0 → 1.2.2

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.
@@ -0,0 +1,456 @@
1
+ /**
2
+ * rows.js reads a built report back as rows of cells - the part CSV and XLSX
3
+ * export share, so the two files can never disagree about what a report holds.
4
+ *
5
+ * Two shapes, the same two csv.js has always written:
6
+ *
7
+ * reportRows is the report as it reads on paper: every text line and every
8
+ * table row, in the order the page draws them. Lines, boxes and images have no
9
+ * text to give, so they do not come along.
10
+ *
11
+ * tableRows is the data rectangle: one table's columns and rows, gathered
12
+ * across every page and group fragment, so a row split by a page break comes
13
+ * back in one piece.
14
+ *
15
+ * Cells are the raw values - a number stays a number - and encoding them is the
16
+ * caller's business: CSV quotes them as text, XLSX types them. Spec 2.2 makes
17
+ * every exporter a page-list consumer, so everything here reads the built pages
18
+ * and never the layout or the data.
19
+ *
20
+ * Each row also carries how it was drawn, for an exporter that can show it:
21
+ * `design` runs parallel to `cells`, one descriptor per cell; `page` is the
22
+ * 0-based page it is on, and `top` and `height` are where it sits on that page
23
+ * and how tall it is, in pixels from the top of the printable area. CSV ignores
24
+ * all of it. A descriptor is one of
25
+ *
26
+ * { kind: 'text', style, template, x, y, w, h } a text item, placed on the page
27
+ * { kind: 'head', column, table } a table's column label
28
+ * { kind: 'cell', column, table } a table's data cell
29
+ *
30
+ * where `table` is { style, wrap } - the table's own style block, and whether
31
+ * its cells wrap - and `template` is the text item's value before placeholders
32
+ * were filled. They are the page objects' own values, unresolved: what the
33
+ * stylesheet does when they are absent is the exporter's to know.
34
+ *
35
+ * reportLayout adds what reportRows leaves out: the graphics - images, lines
36
+ * and boxes, placed on the page the same way - and a spacer row wherever a
37
+ * graphic stands on a line of its own, so whatever lays the rows out has
38
+ * somewhere to put it.
39
+ */
40
+
41
+
42
+ /** the items that are drawn rather than written */
43
+ const GRAPHICS = ['image', 'line', 'box'];
44
+
45
+
46
+ /**
47
+ * The whole report as rows, in the order it is read.
48
+ *
49
+ * One row per line of the report: text items that share a line become the
50
+ * cells of one row, and a table contributes its column labels and then its
51
+ * rows, where the table sits. The rows are ragged, because the report is.
52
+ *
53
+ * A page header drawn on three pages is three rows, because that is what the
54
+ * report has.
55
+ *
56
+ * @param {object[]} pages the `pages` array from buildPages
57
+ * @returns {{cells: Array, header: boolean, design: object[], page: number,
58
+ * top: number, height: number|null}[]} `header` marks a table's column-label row
59
+ */
60
+ export function reportRows(pages) {
61
+ return reportLayout(pages).rows.filter(row => !row.spacer);
62
+ }
63
+
64
+
65
+ /**
66
+ * The report's rows, plus its graphics and the spacer rows that make room for
67
+ * them.
68
+ *
69
+ * A spacer row has no cells and `spacer: true`; it stands for a stretch of the
70
+ * page that holds a graphic and no text - a rule under a heading, a logo on a
71
+ * band of its own.
72
+ *
73
+ * @param {object[]} pages the `pages` array from buildPages
74
+ * @returns {{rows: object[], graphics: {kind: string, page: number, x: number,
75
+ * y: number, w: number, h: number, item: object}[]}} graphics in drawing
76
+ * order, placed in the same coordinates as the rows
77
+ */
78
+ export function reportLayout(pages) {
79
+ const rows = [];
80
+ const graphics = [];
81
+
82
+ (pages ?? []).forEach((page, index) => {
83
+ for (const band of readingOrder(page?.bands)) {
84
+ collectBand(band, rows, { page: index, origin: Number(band?.top) || 0, graphics });
85
+ }
86
+ });
87
+
88
+ return { rows, graphics };
89
+ }
90
+
91
+
92
+ /**
93
+ * One table's columns and rows, gathered across the whole report.
94
+ *
95
+ * @param {object[]} pages the `pages` array from buildPages
96
+ * @param {string|null} [only] the table's id; the first table met when absent
97
+ * @returns {{id: string, columns: object[], table: {style: object, wrap: boolean},
98
+ * headerHeight: number|null, rows: {group: *, row: object, height: number|null}[]}|null}
99
+ * null when the report holds no such table. `group` is the group key on a
100
+ * grouped table, null otherwise; `height` is the row's measured height
101
+ */
102
+ export function tableRows(pages, only = null) {
103
+ let columns = null;
104
+ let id = only;
105
+ let first = null;
106
+ const rows = [];
107
+
108
+ for (const page of (pages ?? [])) {
109
+ for (const band of (page.bands ?? [])) {
110
+ for (const item of (band.items ?? [])) {
111
+ if (item.type !== 'table') continue;
112
+ if (id !== null && item.id !== id) continue;
113
+
114
+ if (columns === null) {
115
+ id = item.id;
116
+ columns = item.columns ?? [];
117
+ first = item;
118
+ }
119
+
120
+ if (item.row) {
121
+ item.row.forEach((row, n) => {
122
+ rows.push({ group: null, row, height: rowHeight(item, item.rowHeights, n) });
123
+ });
124
+ continue;
125
+ }
126
+
127
+ for (const fragment of (item.groups ?? [])) {
128
+ fragment.rows.forEach((row, n) => {
129
+ rows.push({
130
+ group: fragment.key, row,
131
+ height: rowHeight(item, fragment.rowHeights, n)
132
+ });
133
+ });
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ if (columns === null) return null;
140
+
141
+ return { id, columns, table: tableDesign(first), headerHeight: headerHeight(first), rows };
142
+ }
143
+
144
+
145
+ /**
146
+ * The tables a built report holds, in the order they first appear - what a
147
+ * host offers when it asks which one to export.
148
+ *
149
+ * A table split over three pages is listed once, by its id.
150
+ *
151
+ * @param {object[]} pages the `pages` array from buildPages
152
+ * @returns {{id: string, columns: string[]}[]}
153
+ */
154
+ export function reportTables(pages) {
155
+ const found = new Map();
156
+
157
+ for (const page of (pages ?? [])) {
158
+ for (const band of (page.bands ?? [])) {
159
+ for (const item of (band.items ?? [])) {
160
+ if (item.type !== 'table' || found.has(item.id)) continue;
161
+
162
+ found.set(item.id, {
163
+ id: item.id,
164
+ columns: (item.columns ?? []).map(columnLabel)
165
+ });
166
+ }
167
+ }
168
+ }
169
+
170
+ return [...found.values()];
171
+ }
172
+
173
+
174
+ /** what the descriptors of a table's cells share */
175
+ function tableDesign(table) {
176
+ return { style: table.style ?? {}, wrap: table.wrap !== false };
177
+ }
178
+
179
+ /** what items.js draws a header row at: measured if a label wrapped, else declared */
180
+ function headerHeight(table) {
181
+ return table.headerMeasured ?? table.headerHeight ?? table.rowHeight ?? null;
182
+ }
183
+
184
+ /** what items.js draws a data row at */
185
+ function rowHeight(table, heights, n) {
186
+ return heights?.[n] ?? table.rowHeight ?? null;
187
+ }
188
+
189
+ /** how tall a band is drawn, which is what a table moves down past */
190
+ function bandHeight(band) {
191
+ return Number(band?.measuredHeight ?? band?.height) || 0;
192
+ }
193
+
194
+ /** what a column is called in a header row */
195
+ export function columnLabel(column) {
196
+ return column.label ?? column.field;
197
+ }
198
+
199
+
200
+ /**
201
+ * A page's bands, top of the paper first.
202
+ *
203
+ * The array they arrive in is the order they were built, which is not the order
204
+ * they are read: a page footer is anchored to the bottom edge and is often
205
+ * second in the list. `top` is the position the renderer places them at, so it
206
+ * is the only thing that knows.
207
+ */
208
+ function readingOrder(bands) {
209
+ return [...(bands ?? [])].sort((a, b) => (a?.top ?? 0) - (b?.top ?? 0));
210
+ }
211
+
212
+
213
+ /**
214
+ * Adds a band's lines to the output, and its graphics to the context's list.
215
+ *
216
+ * Items are sorted down the band and then across it, and neighbours that share
217
+ * a line are written as one row - so a caption and the figure beside it arrive
218
+ * as two cells rather than as two rows, which is how the band was designed to
219
+ * be read.
220
+ *
221
+ * @param {object} band
222
+ * @param {object[]} out gathered rows, appended to
223
+ * @param {{page: number, origin: number, graphics: object[]}} context where
224
+ * the band's top is on its page, and where graphics are gathered
225
+ */
226
+ function collectBand(band, out, context) {
227
+ const { page, origin } = context;
228
+ const start = out.length;
229
+
230
+ const sorted = [...(band?.items ?? [])]
231
+ .sort((a, b) => (a?.y ?? 0) - (b?.y ?? 0) || (a?.x ?? 0) - (b?.x ?? 0));
232
+
233
+ const graphics = sorted
234
+ .filter(item => GRAPHICS.includes(item?.type))
235
+ .map(item => ({
236
+ kind: item.type, page,
237
+ x: Number(item.x) || 0,
238
+ y: origin + (Number(item.y) || 0),
239
+ w: Number(item.w) || 0,
240
+ h: Number(item.h) || 0,
241
+ item
242
+ }));
243
+
244
+ /** the run of text items being gathered, and the item that anchors its line */
245
+ let line = null;
246
+ const flush = () => {
247
+ if (line) {
248
+ out.push({
249
+ cells: line.cells, header: false, design: line.design,
250
+ page, top: line.top, height: line.bottom - line.top
251
+ });
252
+ }
253
+ line = null;
254
+ };
255
+
256
+ const textDesign = (item) => ({
257
+ kind: 'text',
258
+ style: item.style ?? {},
259
+ template: item.value,
260
+ x: Number(item.x) || 0,
261
+ y: origin + (Number(item.y) || 0),
262
+ w: Number(item.w) || 0,
263
+ h: Number(item.measuredHeight ?? item.h) || 0
264
+ });
265
+
266
+ for (const item of sorted) {
267
+ if (item?.type === 'table') {
268
+ flush();
269
+ collectTable(item, out, { ...context, origin: origin + (Number(item.y) || 0) });
270
+ continue;
271
+ }
272
+
273
+ if (item?.type !== 'text') continue;
274
+
275
+ const design = textDesign(item);
276
+
277
+ if (line && sameLine(line.anchor, item)) {
278
+ line.cells.push(item.text);
279
+ line.design.push(design);
280
+ line.top = Math.min(line.top, design.y);
281
+ line.bottom = Math.max(line.bottom, design.y + design.h);
282
+ continue;
283
+ }
284
+
285
+ flush();
286
+ line = {
287
+ anchor: item,
288
+ cells: [item.text],
289
+ design: [design],
290
+ top: design.y,
291
+ bottom: design.y + design.h
292
+ };
293
+ }
294
+
295
+ flush();
296
+
297
+ addSpacers(out, start, graphics, page);
298
+ context.graphics.push(...graphics);
299
+ }
300
+
301
+
302
+ /** a stretch of a graphic thinner than this, beside no row, is absorbed rather than given a row */
303
+ const MIN_SPACER_PX = 4;
304
+
305
+ /**
306
+ * Rows for the parts of the page that hold a graphic and nothing else.
307
+ *
308
+ * A graphic drawn beside a text line or a table row is drawn over that row.
309
+ * Where it reaches past every row in its band - a rule under a heading, a logo
310
+ * taller than the title beside it, a panel with a margin round its text - the
311
+ * part that sticks out would land on whatever row came next, or be squeezed
312
+ * into nothing. So each such stretch gets an empty row of its own, as tall as
313
+ * it is, where the page has it, and the graphic keeps its size.
314
+ *
315
+ * Slivers under MIN_SPACER_PX are left to the row gaps, unless they are the
316
+ * whole graphic: a hairline on a line of its own still needs its row.
317
+ *
318
+ * @param {object[]} out
319
+ * @param {number} start the first row this band added
320
+ * @param {object[]} graphics this band's
321
+ * @param {number} page
322
+ */
323
+ function addSpacers(out, start, graphics, page) {
324
+ const taken = out.slice(start).map(row => [row.top, row.top + (row.height ?? 0)]);
325
+
326
+ const pieces = [];
327
+ for (const g of graphics) {
328
+ const whole = [g.y, g.y + Math.max(g.h, 1)];
329
+ const free = subtract(whole, taken);
330
+ const alone = free.length === 1 && free[0][0] === whole[0] && free[0][1] === whole[1];
331
+
332
+ for (const piece of free) {
333
+ if (alone || piece[1] - piece[0] >= MIN_SPACER_PX) pieces.push(piece);
334
+ }
335
+ }
336
+
337
+ const spacers = [];
338
+ for (const [top, bottom] of pieces.sort((a, b) => a[0] - b[0])) {
339
+ const last = spacers[spacers.length - 1];
340
+ if (last && top <= last.top + last.height) {
341
+ last.height = Math.max(last.height, bottom - last.top);
342
+ continue;
343
+ }
344
+ spacers.push({ cells: [], header: false, design: [], page, top, height: bottom - top, spacer: true });
345
+ }
346
+
347
+ for (const spacer of spacers) {
348
+ let at = start;
349
+ while (at < out.length && out[at].top < spacer.top + spacer.height) at++;
350
+ out.splice(at, 0, spacer);
351
+ }
352
+ }
353
+
354
+
355
+ /** what is left of an interval once some others are taken out of it */
356
+ function subtract([from, to], taken) {
357
+ let free = [[from, to]];
358
+
359
+ for (const [a, b] of taken) {
360
+ if (!(b > a)) continue;
361
+ free = free.flatMap(([f, t]) => {
362
+ if (b <= f || a >= t) return [[f, t]];
363
+ const left = a > f ? [[f, a]] : [];
364
+ const right = b < t ? [[b, t]] : [];
365
+ return [...left, ...right];
366
+ });
367
+ }
368
+
369
+ return free;
370
+ }
371
+
372
+
373
+ /**
374
+ * Whether two items are on the same line of the band.
375
+ *
376
+ * By overlap rather than by an equal y: a heading and the date beside it are
377
+ * set in different sizes, so they are placed a few pixels apart and still read
378
+ * as one line. Half the shorter item is the threshold - enough that a genuine
379
+ * second line, which clears the first, is never folded into it.
380
+ *
381
+ * Measured against the item that opened the line rather than against the line
382
+ * as it grows, so one tall item cannot go on absorbing everything under it.
383
+ */
384
+ function sameLine(anchor, item) {
385
+ const span = (i) => {
386
+ const top = i.y ?? 0;
387
+ return [top, top + (i.measuredHeight ?? i.h ?? 0)];
388
+ };
389
+
390
+ const [aTop, aBottom] = span(anchor);
391
+ const [bTop, bBottom] = span(item);
392
+ const overlap = Math.min(aBottom, bBottom) - Math.max(aTop, bTop);
393
+
394
+ return overlap >= Math.min(aBottom - aTop, bBottom - bTop) / 2;
395
+ }
396
+
397
+
398
+ /**
399
+ * Adds a table's rows to the output, in the order items.js draws them, each
400
+ * at the height it is drawn down the page.
401
+ *
402
+ * The grouped shape repeats the column labels for every group that starts one,
403
+ * and wraps each fragment's rows in the group's own header and footer bands -
404
+ * which are bands, so they are written by the same code as any other.
405
+ *
406
+ * @param {object} table
407
+ * @param {object[]} out
408
+ * @param {{page: number, origin: number, graphics: object[]}} context origin
409
+ * is the table's top on the page
410
+ */
411
+ function collectTable(table, out, context) {
412
+ const shared = tableDesign(table);
413
+ const { page } = context;
414
+ let cursor = context.origin;
415
+
416
+ const labels = () => {
417
+ const height = headerHeight(table);
418
+ out.push({
419
+ cells: table.columns.map(columnLabel),
420
+ header: true,
421
+ design: table.columns.map(column => ({ kind: 'head', column, table: shared })),
422
+ page, top: cursor, height
423
+ });
424
+ cursor += Number(height) || 0;
425
+ };
426
+
427
+ const cells = (row, height) => {
428
+ out.push({
429
+ cells: table.columns.map(c => row?.[c.field]),
430
+ header: false,
431
+ design: table.columns.map(column => ({ kind: 'cell', column, table: shared })),
432
+ page, top: cursor, height
433
+ });
434
+ cursor += Number(height) || 0;
435
+ };
436
+
437
+ const groupBand = (band) => {
438
+ collectBand(band, out, { ...context, origin: cursor });
439
+ cursor += bandHeight(band);
440
+ };
441
+
442
+ if (!table.groups) {
443
+ if (table.showHeader) labels();
444
+ (table.row ?? []).forEach((row, n) => cells(row, rowHeight(table, table.rowHeights, n)));
445
+ return;
446
+ }
447
+
448
+ for (const fragment of table.groups) {
449
+ if (fragment.showHeader && table.showHeader) labels();
450
+ if (fragment.headerBand) groupBand(fragment.headerBand);
451
+
452
+ fragment.rows.forEach((row, n) => cells(row, rowHeight(table, fragment.rowHeights, n)));
453
+
454
+ if (fragment.showFooter && fragment.footerBand) groupBand(fragment.footerBand);
455
+ }
456
+ }