report-studio 1.0.0 → 1.2.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 (53) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +171 -22
  3. package/dist/designer-qy59eEux.js +3416 -0
  4. package/dist/designer.js +2 -3209
  5. package/dist/index.js +2 -2
  6. package/dist/react-designer.js +41 -0
  7. package/dist/react.js +60 -0
  8. package/dist/{viewer-D-c0lKzQ.js → viewer-xa17tyMJ.js} +682 -537
  9. package/package.json +105 -66
  10. package/src/cli/serve.js +135 -135
  11. package/src/designer/designer.js +2054 -1900
  12. package/src/designer/dialog.js +708 -708
  13. package/src/designer/fields.js +51 -2
  14. package/src/designer/icons.js +5 -0
  15. package/src/designer/index.html +28 -28
  16. package/src/designer/main.js +39 -39
  17. package/src/designer/menu.js +2 -2
  18. package/src/designer/panel.js +21 -1
  19. package/src/designer/sample-data.js +180 -9
  20. package/src/designer/structure.js +87 -6
  21. package/src/designer/styles.css +1654 -1616
  22. package/src/designer/tokens.js +9 -0
  23. package/src/engine/csv.js +350 -315
  24. package/src/engine/group.js +128 -65
  25. package/src/engine/index.js +35 -34
  26. package/src/engine/measure.js +13 -12
  27. package/src/engine/paginate.js +8 -4
  28. package/src/engine/resolve.js +37 -0
  29. package/src/engine/tables.js +87 -0
  30. package/src/engine/validate.js +97 -22
  31. package/src/index.html +79 -79
  32. package/src/index.js +51 -50
  33. package/src/preview/chrome.css +505 -505
  34. package/src/preview/chrome.js +147 -147
  35. package/src/preview/index.html +28 -28
  36. package/src/preview/viewer.js +763 -745
  37. package/src/react/designer.js +87 -0
  38. package/src/react/index.js +117 -0
  39. package/src/render/items.js +94 -1
  40. package/src/render/report.css +30 -0
  41. package/src/server/routes.js +331 -331
  42. package/src/shared/brand.css +29 -29
  43. package/src/shared/dropdown.css +136 -136
  44. package/src/shared/modal.css +125 -125
  45. package/src/shared/store.js +145 -145
  46. package/src/shared/theme.css +72 -72
  47. package/src/shared/window.js +138 -138
  48. package/types/designer.d.ts +85 -0
  49. package/types/index.d.ts +204 -0
  50. package/types/layout.d.ts +179 -0
  51. package/types/react-designer.d.ts +29 -0
  52. package/types/react.d.ts +30 -0
  53. package/types/vite.d.ts +18 -0
package/src/engine/csv.js CHANGED
@@ -1,315 +1,350 @@
1
- /**
2
- * csv.js writes a report out as CSV, in two shapes.
3
- *
4
- * toCSV is the data rectangle: the table's rows and nothing else, one header
5
- * row and uniform columns, which is what a spreadsheet needs to sort, filter
6
- * and pivot. Rows split across a page break come back in one piece.
7
- *
8
- * toReportCSV is the report as it reads on paper: every text line and every
9
- * table row, in the order the page draws them. Lines and boxes have no text to
10
- * give, so they are the two item types that cannot come along.
11
- *
12
- * Spec 5.1: "extract table rows from the page list, download as a file", and
13
- * spec 2.2 lists CSV export as a page-list consumer. So both read the built
14
- * pages - the same thing the renderer draws - and never the layout or the raw
15
- * data.
16
- */
17
-
18
-
19
- /** cells starting with these are executed as formulas by Excel and Sheets */
20
- const FORMULA_LEAD = /^[=+\-@\t\r]/;
21
-
22
-
23
- /**
24
- * The report's table as CSV text.
25
- *
26
- * @param {object[]} pages the `pages` array from buildPages
27
- * @param {object} [options]
28
- * @param {string} [options.delimiter=','] use ';' for locales where Excel expects it
29
- * @param {string} [options.newline='\r\n'] RFC 4180 line ending
30
- * @param {boolean} [options.header=true] emit the column labels as the first row
31
- * @param {boolean} [options.groupColumn=true] prepend the group key on a grouped report
32
- * @param {string} [options.groupLabel='Group']
33
- * @param {boolean} [options.neutraliseFormulas=true] see below
34
- * @returns {string} CSV text, empty when the report holds no table
35
- */
36
- export function toCSV(pages, options = {}) {
37
- const {
38
- delimiter = ',',
39
- newline = '\r\n',
40
- header = true,
41
- groupColumn = true,
42
- groupLabel = 'Group',
43
- neutraliseFormulas = true
44
- } = options;
45
-
46
- const table = collect(pages);
47
- if (!table) return '';
48
-
49
- const grouped = groupColumn && table.rows.some(r => r.group !== null);
50
- const labels = table.columns.map(c => c.label ?? c.field);
51
-
52
- const lines = [];
53
-
54
- if (header) {
55
- lines.push(encodeRow(grouped ? [groupLabel, ...labels] : labels,
56
- delimiter, neutraliseFormulas));
57
- }
58
-
59
- for (const { group, row } of table.rows) {
60
- const cells = table.columns.map(c => row?.[c.field]);
61
- lines.push(encodeRow(grouped ? [group, ...cells] : cells,
62
- delimiter, neutraliseFormulas));
63
- }
64
-
65
- return lines.join(newline);
66
- }
67
-
68
-
69
- /**
70
- * The whole report as CSV, in the order it is read.
71
- *
72
- * One CSV row per line of the report: text items that share a line become the
73
- * cells of one row, and a table contributes its column labels and then its
74
- * rows, where the table sits. So the file re-reads as the report does, at the
75
- * cost of the rectangle toCSV keeps - the rows are ragged, because the report
76
- * is.
77
- *
78
- * Boxes and lines are left out. They are drawn rather than written, and a CSV
79
- * has nowhere to put a rule or a filled panel.
80
- *
81
- * Nothing is gathered across pages the way toCSV gathers table rows: a page
82
- * header drawn on all three pages is written three times, because that is what
83
- * the report has. The order is the paper's, not the layout array's - bands are
84
- * anchored to a zone, so `top` is what says which is read first.
85
- *
86
- * @param {object[]} pages the `pages` array from buildPages
87
- * @param {object} [options]
88
- * @param {string} [options.delimiter=',']
89
- * @param {string} [options.newline='\r\n'] RFC 4180 line ending
90
- * @param {boolean} [options.neutraliseFormulas=true] as toCSV
91
- * @returns {string} CSV text, empty when the report writes nothing
92
- */
93
- export function toReportCSV(pages, options = {}) {
94
- const {
95
- delimiter = ',',
96
- newline = '\r\n',
97
- neutraliseFormulas = true
98
- } = options;
99
-
100
- const out = [];
101
-
102
- for (const page of (pages ?? [])) {
103
- for (const band of readingOrder(page?.bands)) collectBand(band, out);
104
- }
105
-
106
- if (out.length === 0) return '';
107
-
108
- return out
109
- .map(cells => encodeRow(cells, delimiter, neutraliseFormulas))
110
- .join(newline);
111
- }
112
-
113
-
114
- /**
115
- * A page's bands, top of the paper first.
116
- *
117
- * The array they arrive in is the order they were built, which is not the order
118
- * they are read: a page footer is anchored to the bottom edge and is often
119
- * second in the list. `top` is the position the renderer places them at, so it
120
- * is the only thing that knows.
121
- */
122
- function readingOrder(bands) {
123
- return [...(bands ?? [])].sort((a, b) => (a?.top ?? 0) - (b?.top ?? 0));
124
- }
125
-
126
-
127
- /**
128
- * Adds a band's lines to the output.
129
- *
130
- * Items are sorted down the band and then across it, and neighbours that share
131
- * a line are written as one row - so a caption and the figure beside it arrive
132
- * as two cells rather than as two rows, which is how the band was designed to
133
- * be read.
134
- *
135
- * @param {object} band
136
- * @param {Array[]} out gathered rows, appended to
137
- */
138
- function collectBand(band, out) {
139
- const drawn = (band?.items ?? [])
140
- .filter(item => item?.type === 'text' || item?.type === 'table')
141
- .sort((a, b) => (a.y ?? 0) - (b.y ?? 0) || (a.x ?? 0) - (b.x ?? 0));
142
-
143
- /** the run of text items being gathered, and the item that anchors its line */
144
- let line = null;
145
- const flush = () => {
146
- if (line) out.push(line.cells);
147
- line = null;
148
- };
149
-
150
- for (const item of drawn) {
151
- if (item.type === 'table') {
152
- flush();
153
- collectTable(item, out);
154
- continue;
155
- }
156
-
157
- if (line && sameLine(line.anchor, item)) {
158
- line.cells.push(item.text);
159
- continue;
160
- }
161
-
162
- flush();
163
- line = { anchor: item, cells: [item.text] };
164
- }
165
-
166
- flush();
167
- }
168
-
169
-
170
- /**
171
- * Whether two items are on the same line of the band.
172
- *
173
- * By overlap rather than by an equal y: a heading and the date beside it are
174
- * set in different sizes, so they are placed a few pixels apart and still read
175
- * as one line. Half the shorter item is the threshold - enough that a genuine
176
- * second line, which clears the first, is never folded into it.
177
- *
178
- * Measured against the item that opened the line rather than against the line
179
- * as it grows, so one tall item cannot go on absorbing everything under it.
180
- */
181
- function sameLine(anchor, item) {
182
- const span = (i) => {
183
- const top = i.y ?? 0;
184
- return [top, top + (i.measuredHeight ?? i.h ?? 0)];
185
- };
186
-
187
- const [aTop, aBottom] = span(anchor);
188
- const [bTop, bBottom] = span(item);
189
- const overlap = Math.min(aBottom, bBottom) - Math.max(aTop, bTop);
190
-
191
- return overlap >= Math.min(aBottom - aTop, bBottom - bTop) / 2;
192
- }
193
-
194
-
195
- /**
196
- * Adds a table's rows to the output, in the order items.js draws them.
197
- *
198
- * The grouped shape repeats the column labels for every group that starts one,
199
- * and wraps each fragment's rows in the group's own header and footer bands -
200
- * which are bands, so they are written by the same code as any other.
201
- *
202
- * @param {object} table
203
- * @param {Array[]} out
204
- */
205
- function collectTable(table, out) {
206
- const labels = () => table.columns.map(c => c.label ?? c.field);
207
- const cells = (row) => table.columns.map(c => row?.[c.field]);
208
-
209
- if (!table.groups) {
210
- if (table.showHeader) out.push(labels());
211
- for (const row of (table.row ?? [])) out.push(cells(row));
212
- return;
213
- }
214
-
215
- for (const fragment of table.groups) {
216
- if (fragment.showHeader && table.showHeader) out.push(labels());
217
- if (fragment.headerBand) collectBand(fragment.headerBand, out);
218
-
219
- for (const row of fragment.rows) out.push(cells(row));
220
-
221
- if (fragment.showFooter && fragment.footerBand) {
222
- collectBand(fragment.footerBand, out);
223
- }
224
- }
225
- }
226
-
227
-
228
- /**
229
- * A filename for the download, derived from the layout's name.
230
- * @param {object} paginated the buildPages result
231
- * @param {string} [extension='csv']
232
- * @returns {string}
233
- */
234
- export function reportFilename(paginated, extension = 'csv') {
235
- const name = String(paginated?.name ?? 'report')
236
- .replace(/[\\/:*?"<>|]+/g, '-')
237
- .replace(/\s+/g, ' ')
238
- .trim() || 'report';
239
-
240
- return `${name}.${extension}`;
241
- }
242
-
243
-
244
- /**
245
- * Walks the page list for the first table, gathering its rows across every page
246
- * and every group fragment. One table per report today; if that ever changes,
247
- * this is the single place that has to decide what a multi-table export means.
248
- * @param {object[]} pages
249
- * @returns {{columns: object[], rows: {group: string|null, row: object}[]}|null}
250
- */
251
- function collect(pages) {
252
- let columns = null;
253
- let id = null;
254
- const rows = [];
255
-
256
- for (const page of (pages ?? [])) {
257
- for (const band of (page.bands ?? [])) {
258
- for (const item of (band.items ?? [])) {
259
- if (item.type !== 'table') continue;
260
- if (id !== null && item.id !== id) continue;
261
-
262
- if (columns === null) {
263
- id = item.id;
264
- columns = item.columns ?? [];
265
- }
266
-
267
- if (item.row) {
268
- for (const row of item.row) rows.push({ group: null, row });
269
- continue;
270
- }
271
-
272
- for (const fragment of (item.groups ?? [])) {
273
- for (const row of fragment.rows) {
274
- rows.push({ group: fragment.key, row });
275
- }
276
- }
277
- }
278
- }
279
- }
280
-
281
- return columns === null ? null : { columns, rows };
282
- }
283
-
284
-
285
- function encodeRow(cells, delimiter, neutraliseFormulas) {
286
- return cells.map(cell => encodeCell(cell, delimiter, neutraliseFormulas)).join(delimiter);
287
- }
288
-
289
-
290
- /**
291
- * RFC 4180 quoting: wrap when the value holds the delimiter, a quote, or a line
292
- * break, and double any quote inside.
293
- *
294
- * A leading =, +, - or @ is prefixed with a tab as well. A spreadsheet treats
295
- * such a cell as a formula, which turns an exported report into an execution
296
- * vector the moment someone opens it. The tab keeps the text readable and is
297
- * dropped on import; pass neutraliseFormulas:false for a byte-exact export.
298
- */
299
- function encodeCell(value, delimiter, neutraliseFormulas) {
300
- if (value === null || value === undefined) return '';
301
-
302
- let text = String(value);
303
-
304
- if (neutraliseFormulas && FORMULA_LEAD.test(text)) {
305
- text = `\t${text}`;
306
- }
307
-
308
- const mustQuote =
309
- text.includes(delimiter) ||
310
- text.includes('"') ||
311
- text.includes('\n') ||
312
- text.includes('\r');
313
-
314
- return mustQuote ? `"${text.replace(/"/g, '""')}"` : text;
315
- }
1
+ /**
2
+ * csv.js writes a report out as CSV, in two shapes.
3
+ *
4
+ * toCSV is the data rectangle: one table's rows and nothing else, one header
5
+ * row and uniform columns, which is what a spreadsheet needs to sort, filter
6
+ * and pivot. Rows split across a page break come back in one piece. A report
7
+ * with several tables is several rectangles, so it is asked for one of them by
8
+ * id - the first when it is not told.
9
+ *
10
+ * toReportCSV is the report as it reads on paper: every text line and every
11
+ * table row, in the order the page draws them. Lines and boxes have no text to
12
+ * give, so they are the two item types that cannot come along.
13
+ *
14
+ * Spec 5.1: "extract table rows from the page list, download as a file", and
15
+ * spec 2.2 lists CSV export as a page-list consumer. So both read the built
16
+ * pages - the same thing the renderer draws - and never the layout or the raw
17
+ * data.
18
+ */
19
+
20
+
21
+ /** cells starting with these are executed as formulas by Excel and Sheets */
22
+ const FORMULA_LEAD = /^[=+\-@\t\r]/;
23
+
24
+
25
+ /**
26
+ * One of the report's tables as CSV text.
27
+ *
28
+ * @param {object[]} pages the `pages` array from buildPages
29
+ * @param {object} [options]
30
+ * @param {string} [options.table] the id of the table to write; the first
31
+ * table in the report when absent. reportTables lists what there is
32
+ * @param {string} [options.delimiter=','] use ';' for locales where Excel expects it
33
+ * @param {string} [options.newline='\r\n'] RFC 4180 line ending
34
+ * @param {boolean} [options.header=true] emit the column labels as the first row
35
+ * @param {boolean} [options.groupColumn=true] prepend the group key on a grouped report
36
+ * @param {string} [options.groupLabel='Group']
37
+ * @param {boolean} [options.neutraliseFormulas=true] see below
38
+ * @returns {string} CSV text, empty when the report holds no such table
39
+ */
40
+ export function toCSV(pages, options = {}) {
41
+ const {
42
+ delimiter = ',',
43
+ newline = '\r\n',
44
+ header = true,
45
+ groupColumn = true,
46
+ groupLabel = 'Group',
47
+ neutraliseFormulas = true,
48
+ table: only = null
49
+ } = options;
50
+
51
+ const table = collect(pages, only);
52
+ if (!table) return '';
53
+
54
+ const grouped = groupColumn && table.rows.some(r => r.group !== null);
55
+ const labels = table.columns.map(c => c.label ?? c.field);
56
+
57
+ const lines = [];
58
+
59
+ if (header) {
60
+ lines.push(encodeRow(grouped ? [groupLabel, ...labels] : labels,
61
+ delimiter, neutraliseFormulas));
62
+ }
63
+
64
+ for (const { group, row } of table.rows) {
65
+ const cells = table.columns.map(c => row?.[c.field]);
66
+ lines.push(encodeRow(grouped ? [group, ...cells] : cells,
67
+ delimiter, neutraliseFormulas));
68
+ }
69
+
70
+ return lines.join(newline);
71
+ }
72
+
73
+
74
+ /**
75
+ * The whole report as CSV, in the order it is read.
76
+ *
77
+ * One CSV row per line of the report: text items that share a line become the
78
+ * cells of one row, and a table contributes its column labels and then its
79
+ * rows, where the table sits. So the file re-reads as the report does, at the
80
+ * cost of the rectangle toCSV keeps - the rows are ragged, because the report
81
+ * is.
82
+ *
83
+ * Boxes and lines are left out. They are drawn rather than written, and a CSV
84
+ * has nowhere to put a rule or a filled panel.
85
+ *
86
+ * Nothing is gathered across pages the way toCSV gathers table rows: a page
87
+ * header drawn on all three pages is written three times, because that is what
88
+ * the report has. The order is the paper's, not the layout array's - bands are
89
+ * anchored to a zone, so `top` is what says which is read first.
90
+ *
91
+ * @param {object[]} pages the `pages` array from buildPages
92
+ * @param {object} [options]
93
+ * @param {string} [options.delimiter=',']
94
+ * @param {string} [options.newline='\r\n'] RFC 4180 line ending
95
+ * @param {boolean} [options.neutraliseFormulas=true] as toCSV
96
+ * @returns {string} CSV text, empty when the report writes nothing
97
+ */
98
+ export function toReportCSV(pages, options = {}) {
99
+ const {
100
+ delimiter = ',',
101
+ newline = '\r\n',
102
+ neutraliseFormulas = true
103
+ } = options;
104
+
105
+ const out = [];
106
+
107
+ for (const page of (pages ?? [])) {
108
+ for (const band of readingOrder(page?.bands)) collectBand(band, out);
109
+ }
110
+
111
+ if (out.length === 0) return '';
112
+
113
+ return out
114
+ .map(cells => encodeRow(cells, delimiter, neutraliseFormulas))
115
+ .join(newline);
116
+ }
117
+
118
+
119
+ /**
120
+ * A page's bands, top of the paper first.
121
+ *
122
+ * The array they arrive in is the order they were built, which is not the order
123
+ * they are read: a page footer is anchored to the bottom edge and is often
124
+ * second in the list. `top` is the position the renderer places them at, so it
125
+ * is the only thing that knows.
126
+ */
127
+ function readingOrder(bands) {
128
+ return [...(bands ?? [])].sort((a, b) => (a?.top ?? 0) - (b?.top ?? 0));
129
+ }
130
+
131
+
132
+ /**
133
+ * Adds a band's lines to the output.
134
+ *
135
+ * Items are sorted down the band and then across it, and neighbours that share
136
+ * a line are written as one row - so a caption and the figure beside it arrive
137
+ * as two cells rather than as two rows, which is how the band was designed to
138
+ * be read.
139
+ *
140
+ * @param {object} band
141
+ * @param {Array[]} out gathered rows, appended to
142
+ */
143
+ function collectBand(band, out) {
144
+ const drawn = (band?.items ?? [])
145
+ .filter(item => item?.type === 'text' || item?.type === 'table')
146
+ .sort((a, b) => (a.y ?? 0) - (b.y ?? 0) || (a.x ?? 0) - (b.x ?? 0));
147
+
148
+ /** the run of text items being gathered, and the item that anchors its line */
149
+ let line = null;
150
+ const flush = () => {
151
+ if (line) out.push(line.cells);
152
+ line = null;
153
+ };
154
+
155
+ for (const item of drawn) {
156
+ if (item.type === 'table') {
157
+ flush();
158
+ collectTable(item, out);
159
+ continue;
160
+ }
161
+
162
+ if (line && sameLine(line.anchor, item)) {
163
+ line.cells.push(item.text);
164
+ continue;
165
+ }
166
+
167
+ flush();
168
+ line = { anchor: item, cells: [item.text] };
169
+ }
170
+
171
+ flush();
172
+ }
173
+
174
+
175
+ /**
176
+ * Whether two items are on the same line of the band.
177
+ *
178
+ * By overlap rather than by an equal y: a heading and the date beside it are
179
+ * set in different sizes, so they are placed a few pixels apart and still read
180
+ * as one line. Half the shorter item is the threshold - enough that a genuine
181
+ * second line, which clears the first, is never folded into it.
182
+ *
183
+ * Measured against the item that opened the line rather than against the line
184
+ * as it grows, so one tall item cannot go on absorbing everything under it.
185
+ */
186
+ function sameLine(anchor, item) {
187
+ const span = (i) => {
188
+ const top = i.y ?? 0;
189
+ return [top, top + (i.measuredHeight ?? i.h ?? 0)];
190
+ };
191
+
192
+ const [aTop, aBottom] = span(anchor);
193
+ const [bTop, bBottom] = span(item);
194
+ const overlap = Math.min(aBottom, bBottom) - Math.max(aTop, bTop);
195
+
196
+ return overlap >= Math.min(aBottom - aTop, bBottom - bTop) / 2;
197
+ }
198
+
199
+
200
+ /**
201
+ * Adds a table's rows to the output, in the order items.js draws them.
202
+ *
203
+ * The grouped shape repeats the column labels for every group that starts one,
204
+ * and wraps each fragment's rows in the group's own header and footer bands -
205
+ * which are bands, so they are written by the same code as any other.
206
+ *
207
+ * @param {object} table
208
+ * @param {Array[]} out
209
+ */
210
+ function collectTable(table, out) {
211
+ const labels = () => table.columns.map(c => c.label ?? c.field);
212
+ const cells = (row) => table.columns.map(c => row?.[c.field]);
213
+
214
+ if (!table.groups) {
215
+ if (table.showHeader) out.push(labels());
216
+ for (const row of (table.row ?? [])) out.push(cells(row));
217
+ return;
218
+ }
219
+
220
+ for (const fragment of table.groups) {
221
+ if (fragment.showHeader && table.showHeader) out.push(labels());
222
+ if (fragment.headerBand) collectBand(fragment.headerBand, out);
223
+
224
+ for (const row of fragment.rows) out.push(cells(row));
225
+
226
+ if (fragment.showFooter && fragment.footerBand) {
227
+ collectBand(fragment.footerBand, out);
228
+ }
229
+ }
230
+ }
231
+
232
+
233
+ /**
234
+ * A filename for the download, derived from the layout's name.
235
+ * @param {object} paginated the buildPages result
236
+ * @param {string} [extension='csv']
237
+ * @returns {string}
238
+ */
239
+ export function reportFilename(paginated, extension = 'csv') {
240
+ const name = String(paginated?.name ?? 'report')
241
+ .replace(/[\\/:*?"<>|]+/g, '-')
242
+ .replace(/\s+/g, ' ')
243
+ .trim() || 'report';
244
+
245
+ return `${name}.${extension}`;
246
+ }
247
+
248
+
249
+ /**
250
+ * The tables a built report holds, in the order they first appear - what a
251
+ * host offers when it asks which one to export with toCSV.
252
+ *
253
+ * Read from the pages rather than the layout, like everything in this file:
254
+ * a table split over three pages is listed once, by its id.
255
+ *
256
+ * @param {object[]} pages the `pages` array from buildPages
257
+ * @returns {{id: string, columns: string[]}[]}
258
+ */
259
+ export function reportTables(pages) {
260
+ const found = new Map();
261
+
262
+ for (const page of (pages ?? [])) {
263
+ for (const band of (page.bands ?? [])) {
264
+ for (const item of (band.items ?? [])) {
265
+ if (item.type !== 'table' || found.has(item.id)) continue;
266
+
267
+ found.set(item.id, {
268
+ id: item.id,
269
+ columns: (item.columns ?? []).map(c => c.label ?? c.field)
270
+ });
271
+ }
272
+ }
273
+ }
274
+
275
+ return [...found.values()];
276
+ }
277
+
278
+
279
+ /**
280
+ * Walks the page list for one table, gathering its rows across every page and
281
+ * every group fragment.
282
+ * @param {object[]} pages
283
+ * @param {string|null} [only] the table's id; the first table met when absent
284
+ * @returns {{columns: object[], rows: {group: string|null, row: object}[]}|null}
285
+ */
286
+ function collect(pages, only = null) {
287
+ let columns = null;
288
+ let id = only;
289
+ const rows = [];
290
+
291
+ for (const page of (pages ?? [])) {
292
+ for (const band of (page.bands ?? [])) {
293
+ for (const item of (band.items ?? [])) {
294
+ if (item.type !== 'table') continue;
295
+ if (id !== null && item.id !== id) continue;
296
+
297
+ if (columns === null) {
298
+ id = item.id;
299
+ columns = item.columns ?? [];
300
+ }
301
+
302
+ if (item.row) {
303
+ for (const row of item.row) rows.push({ group: null, row });
304
+ continue;
305
+ }
306
+
307
+ for (const fragment of (item.groups ?? [])) {
308
+ for (const row of fragment.rows) {
309
+ rows.push({ group: fragment.key, row });
310
+ }
311
+ }
312
+ }
313
+ }
314
+ }
315
+
316
+ return columns === null ? null : { columns, rows };
317
+ }
318
+
319
+
320
+ function encodeRow(cells, delimiter, neutraliseFormulas) {
321
+ return cells.map(cell => encodeCell(cell, delimiter, neutraliseFormulas)).join(delimiter);
322
+ }
323
+
324
+
325
+ /**
326
+ * RFC 4180 quoting: wrap when the value holds the delimiter, a quote, or a line
327
+ * break, and double any quote inside.
328
+ *
329
+ * A leading =, +, - or @ is prefixed with a tab as well. A spreadsheet treats
330
+ * such a cell as a formula, which turns an exported report into an execution
331
+ * vector the moment someone opens it. The tab keeps the text readable and is
332
+ * dropped on import; pass neutraliseFormulas:false for a byte-exact export.
333
+ */
334
+ function encodeCell(value, delimiter, neutraliseFormulas) {
335
+ if (value === null || value === undefined) return '';
336
+
337
+ let text = String(value);
338
+
339
+ if (neutraliseFormulas && FORMULA_LEAD.test(text)) {
340
+ text = `\t${text}`;
341
+ }
342
+
343
+ const mustQuote =
344
+ text.includes(delimiter) ||
345
+ text.includes('"') ||
346
+ text.includes('\n') ||
347
+ text.includes('\r');
348
+
349
+ return mustQuote ? `"${text.replace(/"/g, '""')}"` : text;
350
+ }