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.
- package/README.md +38 -2
- package/dist/{designer-qy59eEux.js → designer-DQlfKnTr.js} +928 -928
- package/dist/designer.js +1 -1
- package/dist/index.js +2 -2
- package/dist/react-designer.js +1 -1
- package/dist/react.js +2 -1
- package/dist/viewer-BSPNCNRU.js +2912 -0
- package/package.json +1 -1
- package/src/designer/index.html +1 -1
- package/src/designer/styles.css +31 -8
- package/src/engine/csv.js +12 -197
- package/src/engine/index.js +1 -0
- package/src/engine/rows.js +456 -0
- package/src/engine/xlsx-drawing.js +313 -0
- package/src/engine/xlsx-style.js +457 -0
- package/src/engine/xlsx.js +1200 -0
- package/src/engine/zip.js +138 -0
- package/src/index.html +1 -1
- package/src/index.js +5 -1
- package/src/preview/chrome.css +75 -12
- package/src/preview/chrome.js +69 -55
- package/src/preview/index.html +1 -1
- package/src/preview/viewer.js +42 -1
- package/src/react/index.js +3 -3
- package/src/shared/brand.css +3 -1
- package/src/shared/theme.css +15 -3
- package/types/index.d.ts +53 -0
- package/dist/viewer-xa17tyMJ.js +0 -1721
|
@@ -0,0 +1,1200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xlsx.js writes a report out as an Excel workbook (.xlsx, Office Open XML).
|
|
3
|
+
*
|
|
4
|
+
* The workbook holds the two shapes CSV offers, side by side, because a
|
|
5
|
+
* workbook has room for both:
|
|
6
|
+
*
|
|
7
|
+
* - a "Report" sheet: the report as it reads on paper - every text line and
|
|
8
|
+
* table row, in page order, the rows toReportCSV writes (a line whose items
|
|
9
|
+
* are stacked in one column takes a row per item);
|
|
10
|
+
* - one sheet per table: that table's rows as one rectangle, header row frozen
|
|
11
|
+
* and filterable, the same rows toCSV writes for it.
|
|
12
|
+
*
|
|
13
|
+
* Unlike CSV the cells are typed. A number in the data is a number Excel can
|
|
14
|
+
* sum, a boolean is a boolean, and a Date is a date. Strings stay strings - a
|
|
15
|
+
* "007" or a phone number is not second-guessed into a number. The one string
|
|
16
|
+
* that is read as a number is a text item that printed nothing but a
|
|
17
|
+
* placeholder's number, such as `{sum(amount)}`: a total, which belongs in a
|
|
18
|
+
* cell a reader can add up. Strings are written inline, which Excel never
|
|
19
|
+
* evaluates, so the formula guard CSV needs has no work to do here.
|
|
20
|
+
*
|
|
21
|
+
* And unlike CSV the workbook looks like the report. Fonts, colours,
|
|
22
|
+
* alignment, the table grid and the header's fill come across as cell formats
|
|
23
|
+
* (xlsx-style.js). On the Report sheet the page's geometry does too: a text
|
|
24
|
+
* item goes in the column under where it sat, inset by an indent to where it
|
|
25
|
+
* started; rows are as tall, and as far apart, as the lines on the page; and
|
|
26
|
+
* pictures, rules and boxes are drawn where the page has them (xlsx-drawing.js).
|
|
27
|
+
* `styled: false` gives plain data instead, headers bold and nothing else.
|
|
28
|
+
*
|
|
29
|
+
* An .xlsx file is a ZIP of XML parts; zip.js packs them. No dependency: the
|
|
30
|
+
* parts below are the minimum Excel opens without complaint (ECMA-376 Part 1,
|
|
31
|
+
* SpreadsheetML and DrawingML).
|
|
32
|
+
*
|
|
33
|
+
* Like every exporter (spec 2.2) it reads the built pages, through rows.js, and
|
|
34
|
+
* never the layout or the data.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
import { reportLayout, reportRows, tableRows, reportTables, columnLabel } from './rows.js';
|
|
38
|
+
import {
|
|
39
|
+
argb, cellFormat, createStyles, columnChars, indentLevels, DEFAULT_COLUMN_PX, points
|
|
40
|
+
} from './xlsx-style.js';
|
|
41
|
+
import {
|
|
42
|
+
box, decodeDataUri, drawingRels, drawingXml, fitImage, pen, picture, rule, sniffImage,
|
|
43
|
+
DRAWING_CONTENT_TYPE, IMAGE_TYPES, REL_DRAWING
|
|
44
|
+
} from './xlsx-drawing.js';
|
|
45
|
+
import { imageSrc } from '../render/items.js';
|
|
46
|
+
import { zip } from './zip.js';
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
/** Excel's hard limits; past them it refuses the whole file */
|
|
50
|
+
export const XLSX_LIMITS = Object.freeze({
|
|
51
|
+
rows: 1048576,
|
|
52
|
+
columns: 16384,
|
|
53
|
+
cellText: 32767,
|
|
54
|
+
sheetName: 31
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
export const XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
|
58
|
+
|
|
59
|
+
const NS_MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
|
|
60
|
+
const NS_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
|
|
61
|
+
const NS_PKG_REL = 'http://schemas.openxmlformats.org/package/2006/relationships';
|
|
62
|
+
const NS_TYPES = 'http://schemas.openxmlformats.org/package/2006/content-types';
|
|
63
|
+
const REL_DOC = `${NS_REL}/officeDocument`;
|
|
64
|
+
const REL_SHEET = `${NS_REL}/worksheet`;
|
|
65
|
+
const REL_STYLES = `${NS_REL}/styles`;
|
|
66
|
+
const CT_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml';
|
|
67
|
+
const CT_BOOK = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml';
|
|
68
|
+
const CT_STYLES = 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml';
|
|
69
|
+
|
|
70
|
+
const XML_HEAD = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
|
|
71
|
+
|
|
72
|
+
/** the one format an unstyled workbook has: a bold header */
|
|
73
|
+
const BOLD = Object.freeze({ font: Object.freeze({ bold: true }) });
|
|
74
|
+
|
|
75
|
+
/** built-in number formats, which follow the reader's locale */
|
|
76
|
+
const NUMFMT_DATE = 14;
|
|
77
|
+
const NUMFMT_DATE_TIME = 22;
|
|
78
|
+
|
|
79
|
+
/** characters XML 1.0 cannot carry at all, escaped or not */
|
|
80
|
+
const INVALID_XML = /[\x00-\x08\x0B\x0C\x0E-\x1F]/g;
|
|
81
|
+
|
|
82
|
+
/** Excel reads `_x0041_` in a string as an escaped character; this guards literal ones */
|
|
83
|
+
const EXCEL_ESCAPE = /_(x[0-9A-Fa-f]{4}_)/g;
|
|
84
|
+
|
|
85
|
+
/** characters a sheet name cannot hold */
|
|
86
|
+
const SHEET_NAME_BANNED = /[\[\]:*?\/\\\x00-\x1F]/g;
|
|
87
|
+
|
|
88
|
+
/** content-based column widths, in Excel's character units */
|
|
89
|
+
const MIN_WIDTH = 8;
|
|
90
|
+
const MAX_WIDTH = 60;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* How far right text placement will add columns past the last table column.
|
|
94
|
+
* Past it, text goes in the last column and spills - a band item at x 5000 is a
|
|
95
|
+
* layout mistake, not a reason for a sheet eighty columns wide.
|
|
96
|
+
*/
|
|
97
|
+
const MAX_PLACED_COLUMNS = 50;
|
|
98
|
+
|
|
99
|
+
/** the drop-down a filtered header row draws, about 16px, in characters */
|
|
100
|
+
const FILTER_BUTTON_CHARS = 2.5;
|
|
101
|
+
|
|
102
|
+
/** and as indent levels, for a right-aligned label to stand clear of it */
|
|
103
|
+
const FILTER_BUTTON_INDENT = 2;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The most white space a Report sheet row carries below its content. The page
|
|
107
|
+
* leaves gaps - between header lines, and a long one above the footer - and a
|
|
108
|
+
* row keeps the page's gap up to this much, so the sheet is spaced like the
|
|
109
|
+
* report without a screenful of empty row above every page footer.
|
|
110
|
+
*/
|
|
111
|
+
const MAX_GAP_PX = 24;
|
|
112
|
+
|
|
113
|
+
/** a row with nothing measured in it, which Excel draws at 20px */
|
|
114
|
+
const DEFAULT_ROW_PX = 20;
|
|
115
|
+
|
|
116
|
+
/** a text item that printed only a number: a total, read as one */
|
|
117
|
+
const NUMERIC_TEXT = /^-?(0|[1-9]\d*)(\.\d+)?$/;
|
|
118
|
+
|
|
119
|
+
/** a placeholder in a text template */
|
|
120
|
+
const PLACEHOLDER = /\{[^{}]+\}/;
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The report as an .xlsx workbook.
|
|
125
|
+
*
|
|
126
|
+
* @param {object[]} pages the `pages` array from buildPages
|
|
127
|
+
* @param {object} [options]
|
|
128
|
+
* @param {boolean} [options.report=true] include the "Report" sheet - the
|
|
129
|
+
* report as it reads, in page order
|
|
130
|
+
* @param {boolean} [options.tables=true] include one sheet per table
|
|
131
|
+
* @param {boolean} [options.styled=true] carry the report's look - formats,
|
|
132
|
+
* placement, spacing, pictures, rules and boxes; false writes plain data
|
|
133
|
+
* with bold headers
|
|
134
|
+
* @param {string} [options.reportSheetName='Report']
|
|
135
|
+
* @param {boolean} [options.groupColumn=true] prepend the group key on a
|
|
136
|
+
* grouped table's sheet, as toCSV does
|
|
137
|
+
* @param {string} [options.groupLabel='Group']
|
|
138
|
+
* @param {Object<string, Uint8Array|ArrayBuffer>|Map} [options.images] the
|
|
139
|
+
* bytes of pictures that are not `data:` URIs, keyed by their src - which is
|
|
140
|
+
* what toXLSXAsync fetches. A picture with no bytes is left out
|
|
141
|
+
* @returns {Uint8Array} the file's bytes; empty when the report writes nothing
|
|
142
|
+
* @throws {RangeError} when a sheet would pass Excel's row or column limit -
|
|
143
|
+
* Excel would refuse the file, so none is made
|
|
144
|
+
*/
|
|
145
|
+
export function toXLSX(pages, options = {}) {
|
|
146
|
+
const {
|
|
147
|
+
report = true,
|
|
148
|
+
tables = true,
|
|
149
|
+
styled = true,
|
|
150
|
+
reportSheetName = 'Report',
|
|
151
|
+
groupColumn = true,
|
|
152
|
+
groupLabel = 'Group',
|
|
153
|
+
images = null
|
|
154
|
+
} = options;
|
|
155
|
+
|
|
156
|
+
const sheets = [];
|
|
157
|
+
|
|
158
|
+
if (report && reportRows(pages).length > 0) {
|
|
159
|
+
sheets.push(reportSheet(pages, reportSheetName, styled, images));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (tables) {
|
|
163
|
+
for (const { id } of reportTables(pages)) {
|
|
164
|
+
sheets.push(tableSheet(tableRows(pages, id), styled, groupColumn, groupLabel));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (sheets.length === 0) return new Uint8Array(0);
|
|
169
|
+
|
|
170
|
+
const names = sheetNames(sheets.map(s => s.name));
|
|
171
|
+
sheets.forEach((sheet, i) => {
|
|
172
|
+
sheet.name = names[i];
|
|
173
|
+
sheet.width = sheet.rows.reduce((n, r) => Math.max(n, r.cells.length), 0);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
/** every sheet has asked for its formats before styles.xml is written */
|
|
177
|
+
const styles = createStyles();
|
|
178
|
+
const worksheets = sheets.map(sheet => worksheet(sheet, styles));
|
|
179
|
+
|
|
180
|
+
/** drawings, numbered in sheet order; only the Report sheet has one today */
|
|
181
|
+
const drawings = [];
|
|
182
|
+
const media = [];
|
|
183
|
+
sheets.forEach((sheet, i) => {
|
|
184
|
+
if (!sheet.drawing) return;
|
|
185
|
+
drawings.push({ sheet: i + 1, n: drawings.length + 1, ...sheet.drawing });
|
|
186
|
+
media.push(...sheet.drawing.media);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
return zip([
|
|
190
|
+
{ name: '[Content_Types].xml', data: contentTypes(sheets.length, drawings, media) },
|
|
191
|
+
{ name: '_rels/.rels', data: packageRels() },
|
|
192
|
+
{ name: 'xl/workbook.xml', data: workbook(sheets) },
|
|
193
|
+
{ name: 'xl/_rels/workbook.xml.rels', data: workbookRels(sheets.length) },
|
|
194
|
+
{ name: 'xl/styles.xml', data: styles.xml() },
|
|
195
|
+
...worksheets.map((data, i) => ({ name: `xl/worksheets/sheet${i + 1}.xml`, data })),
|
|
196
|
+
...drawings.flatMap(d => [
|
|
197
|
+
{ name: `xl/worksheets/_rels/sheet${d.sheet}.xml.rels`, data: sheetRels(d.n) },
|
|
198
|
+
{ name: `xl/drawings/drawing${d.n}.xml`, data: drawingXml(d.anchors) },
|
|
199
|
+
...(d.media.length
|
|
200
|
+
? [{ name: `xl/drawings/_rels/drawing${d.n}.xml.rels`, data: drawingRels(d.media) }]
|
|
201
|
+
: [])
|
|
202
|
+
]),
|
|
203
|
+
...media.map(m => ({ name: `xl/media/${m.file}`, data: m.bytes }))
|
|
204
|
+
]);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* toXLSX, with the report's pictures fetched first.
|
|
210
|
+
*
|
|
211
|
+
* A picture held in the layout as a `data:` URI needs nothing fetched, so
|
|
212
|
+
* toXLSX embeds it on its own. One given as a URL needs its bytes, which only
|
|
213
|
+
* a fetch can get, and a fetch is asynchronous - hence this. A picture that
|
|
214
|
+
* cannot be fetched (offline, refused by CORS) is left out of the workbook
|
|
215
|
+
* rather than failing it.
|
|
216
|
+
*
|
|
217
|
+
* @param {object[]} pages
|
|
218
|
+
* @param {object} [options] as toXLSX, plus
|
|
219
|
+
* @param {Function} [options.fetch] defaults to the global fetch
|
|
220
|
+
* @returns {Promise<Uint8Array>}
|
|
221
|
+
*/
|
|
222
|
+
export async function toXLSXAsync(pages, options = {}) {
|
|
223
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
224
|
+
const images = new Map(options.images instanceof Map
|
|
225
|
+
? options.images
|
|
226
|
+
: Object.entries(options.images ?? {}));
|
|
227
|
+
|
|
228
|
+
if (typeof fetcher === 'function') {
|
|
229
|
+
await Promise.all(reportImageSources(pages)
|
|
230
|
+
.filter(src => !images.has(src))
|
|
231
|
+
.map(async (src) => {
|
|
232
|
+
try {
|
|
233
|
+
const response = await fetcher(src);
|
|
234
|
+
if (response?.ok) images.set(src, new Uint8Array(await response.arrayBuffer()));
|
|
235
|
+
} catch {
|
|
236
|
+
/** left out, as a picture that failed to load prints nothing */
|
|
237
|
+
}
|
|
238
|
+
}));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return toXLSX(pages, { ...options, images });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The pictures a report shows that need fetching before they can be embedded:
|
|
247
|
+
* every distinct URL, leaving out `data:` URIs, which carry their own bytes.
|
|
248
|
+
*
|
|
249
|
+
* @param {object[]} pages
|
|
250
|
+
* @returns {string[]}
|
|
251
|
+
*/
|
|
252
|
+
export function reportImageSources(pages) {
|
|
253
|
+
const found = new Set();
|
|
254
|
+
|
|
255
|
+
for (const g of reportLayout(pages).graphics) {
|
|
256
|
+
if (g.kind !== 'image') continue;
|
|
257
|
+
const src = imageSrc(g.item.resolvedSrc);
|
|
258
|
+
if (src && !/^data:/i.test(src)) found.add(src);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return [...found];
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
/* ---------------- the sheets ---------------- */
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* A sheet is { name, rows, frozen, gridLines, widths, drawing }, where each row
|
|
270
|
+
* is { cells, height } and each cell is { value, format } - cells may have
|
|
271
|
+
* holes, which are empty cells. Formats are resolved to numbers only when the
|
|
272
|
+
* sheet is written.
|
|
273
|
+
*/
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The report as it reads. Styled, it is laid out like the page: table rows in
|
|
277
|
+
* their columns, text where it sat, rows spaced as the page spaces them,
|
|
278
|
+
* graphics drawn over, gridlines off so it looks like paper.
|
|
279
|
+
*/
|
|
280
|
+
function reportSheet(pages, name, styled, images) {
|
|
281
|
+
const { rows, graphics } = reportLayout(pages);
|
|
282
|
+
|
|
283
|
+
if (!styled) {
|
|
284
|
+
const plain = rows.filter(r => !r.spacer).map(({ cells, header }) => ({
|
|
285
|
+
cells: cells.map(value => ({ value, format: header ? BOLD : null })),
|
|
286
|
+
height: null
|
|
287
|
+
}));
|
|
288
|
+
|
|
289
|
+
return { name, rows: plain, frozen: false, gridLines: true, widths: contentWidths(plain) };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const grid = columnGrid(rows);
|
|
293
|
+
const formats = formatCache();
|
|
294
|
+
|
|
295
|
+
const laidOut = rows.flatMap((row) => {
|
|
296
|
+
if (row.spacer) return [{ cells: [], page: row.page, top: row.top, own: row.height }];
|
|
297
|
+
|
|
298
|
+
const isText = row.design?.length > 0 && row.design.every(d => d?.kind === 'text');
|
|
299
|
+
if (isText) return placeText(row, grid, formats);
|
|
300
|
+
|
|
301
|
+
return [{
|
|
302
|
+
cells: row.cells.map((value, i) => ({ value, format: formats(row.design?.[i]) })),
|
|
303
|
+
page: row.page, top: row.top, own: row.height
|
|
304
|
+
}];
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
spaceRows(laidOut);
|
|
308
|
+
|
|
309
|
+
const drawing = drawGraphics(graphics, laidOut, grid, images);
|
|
310
|
+
|
|
311
|
+
const width = laidOut.reduce((n, r) => Math.max(n, r.cells.length), grid.px.length);
|
|
312
|
+
const widths = Array.from({ length: width }, (_, i) => columnChars(grid.px[i] ?? DEFAULT_COLUMN_PX));
|
|
313
|
+
|
|
314
|
+
return {
|
|
315
|
+
name,
|
|
316
|
+
rows: laidOut.map(r => ({ cells: r.cells, height: r.height })),
|
|
317
|
+
frozen: false,
|
|
318
|
+
gridLines: false,
|
|
319
|
+
widths,
|
|
320
|
+
drawing: drawing.anchors.length ? drawing : null
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* 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.
|
|
329
|
+
*/
|
|
330
|
+
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);
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* One format object per column, so the writer resolves each once. A
|
|
337
|
+
* right-aligned label is indented clear of the filter button, which sits on
|
|
338
|
+
* the cell's right edge however wide the column is.
|
|
339
|
+
*/
|
|
340
|
+
const headFormats = columns.map((column) => {
|
|
341
|
+
if (!styled) return BOLD;
|
|
342
|
+
|
|
343
|
+
const format = cellFormat({ kind: 'head', column, table: table.table });
|
|
344
|
+
return format.alignment.horizontal === 'right'
|
|
345
|
+
? {
|
|
346
|
+
...format,
|
|
347
|
+
alignment: {
|
|
348
|
+
...format.alignment,
|
|
349
|
+
indent: Math.max(format.alignment.indent ?? 0, FILTER_BUTTON_INDENT)
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
: format;
|
|
353
|
+
});
|
|
354
|
+
const cellFormats = columns.map(column =>
|
|
355
|
+
styled ? cellFormat({ kind: 'cell', column, table: table.table }) : null);
|
|
356
|
+
|
|
357
|
+
const rows = [{
|
|
358
|
+
cells: labels.map((value, i) => ({ value, format: headFormats[i] })),
|
|
359
|
+
height: styled ? table.headerHeight : null
|
|
360
|
+
}];
|
|
361
|
+
|
|
362
|
+
for (const { group, row, height } of table.rows) {
|
|
363
|
+
const values = table.columns.map(c => row?.[c.field]);
|
|
364
|
+
const cells = grouped ? [group, ...values] : values;
|
|
365
|
+
|
|
366
|
+
rows.push({
|
|
367
|
+
cells: cells.map((value, i) => ({ value, format: cellFormats[i] })),
|
|
368
|
+
height: styled ? height : null
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** room for the filter button, which otherwise sits on a right-aligned label */
|
|
373
|
+
const fromContent = contentWidths(rows);
|
|
374
|
+
const widths = styled
|
|
375
|
+
? columns.map((c, i) => (Number(c.width) > 0 ? columnChars(Number(c.width)) : fromContent[i])
|
|
376
|
+
+ FILTER_BUTTON_CHARS)
|
|
377
|
+
: fromContent.map(w => w + FILTER_BUTTON_CHARS);
|
|
378
|
+
|
|
379
|
+
return { name: table.id, rows, frozen: true, gridLines: true, widths };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* The Report sheet's columns, in pixels: as wide as the widest table column
|
|
385
|
+
* drawn at each position. Text and graphics are placed against these edges,
|
|
386
|
+
* which works because a table, a text item and a picture all measure x from
|
|
387
|
+
* the same band edge - so sheet pixels and page pixels are the same pixels.
|
|
388
|
+
*
|
|
389
|
+
* `at` finds the column under an x, growing default-width columns past the
|
|
390
|
+
* last table column so anything further right still has somewhere to go.
|
|
391
|
+
*/
|
|
392
|
+
function columnGrid(rows) {
|
|
393
|
+
const px = [];
|
|
394
|
+
|
|
395
|
+
for (const row of rows) {
|
|
396
|
+
row.design?.forEach((d, i) => {
|
|
397
|
+
if (!d || d.kind === 'text') return;
|
|
398
|
+
const w = Number(d.column?.width);
|
|
399
|
+
px[i] = Math.max(px[i] ?? 0, w > 0 ? w : DEFAULT_COLUMN_PX);
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
for (let i = 0; i < px.length; i++) px[i] ??= DEFAULT_COLUMN_PX;
|
|
404
|
+
|
|
405
|
+
function at(x) {
|
|
406
|
+
let edge = 0;
|
|
407
|
+
|
|
408
|
+
for (let i = 0; ; i++) {
|
|
409
|
+
if (i === px.length) {
|
|
410
|
+
if (px.length >= MAX_PLACED_COLUMNS) return px.length - 1;
|
|
411
|
+
px.push(DEFAULT_COLUMN_PX);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
edge += px[i];
|
|
415
|
+
if (x < edge) return i;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const left = (col) => px.slice(0, col).reduce((sum, w) => sum + w, 0);
|
|
420
|
+
const right = (col) => left(col) + px[col];
|
|
421
|
+
|
|
422
|
+
return { px, at, left, right };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* A line of text items, each in the column under it.
|
|
428
|
+
*
|
|
429
|
+
* Left-aligned text goes where it starts and right-aligned where it ends, and
|
|
430
|
+
* Excel spills each into its empty neighbours the way it ran on the page. The
|
|
431
|
+
* distance between the item's edge and its column's is kept as an indent, so
|
|
432
|
+
* text that started 14px into a column still does. Centred text that spans
|
|
433
|
+
* several columns is centred across them with Excel's "centre across
|
|
434
|
+
* selection", which needs no merged cells and so keeps the sheet sortable.
|
|
435
|
+
*
|
|
436
|
+
* Two items wanting one column - a date stacked under a period on the right of
|
|
437
|
+
* a header, which share a line only because a tall title beside them spans
|
|
438
|
+
* both - cannot share a cell, and moving one sideways would put it where the
|
|
439
|
+
* page does not. So the later one goes on a row of its own beneath, in the
|
|
440
|
+
* same column, which is where the page has it.
|
|
441
|
+
*
|
|
442
|
+
* @returns {{cells: object[], page: number, top: number, own: number}[]} one
|
|
443
|
+
* row, or more; `top` and `own` are the page position and content height
|
|
444
|
+
*/
|
|
445
|
+
function placeText(row, grid, formats) {
|
|
446
|
+
const lines = [];
|
|
447
|
+
|
|
448
|
+
const lineFor = (columns) => {
|
|
449
|
+
let line = lines.find(l => columns.every(c => l.cells[c] === undefined));
|
|
450
|
+
if (!line) {
|
|
451
|
+
line = { cells: [], top: Infinity, bottom: -Infinity };
|
|
452
|
+
lines.push(line);
|
|
453
|
+
}
|
|
454
|
+
return line;
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
row.cells.forEach((raw, i) => {
|
|
458
|
+
const design = row.design[i];
|
|
459
|
+
const align = formats(design)?.alignment?.horizontal ?? 'left';
|
|
460
|
+
const value = numericText(raw, design.template);
|
|
461
|
+
|
|
462
|
+
const x = Math.max(0, Number(design.x) || 0);
|
|
463
|
+
const w = Math.max(1, Number(design.w) || 1);
|
|
464
|
+
const first = grid.at(x);
|
|
465
|
+
const last = Math.max(first, grid.at(x + w - 1));
|
|
466
|
+
|
|
467
|
+
let line;
|
|
468
|
+
|
|
469
|
+
if (align === 'center' && last > first) {
|
|
470
|
+
const span = Array.from({ length: last - first + 1 }, (_, k) => first + k);
|
|
471
|
+
const across = formats.text(design, { centred: true });
|
|
472
|
+
|
|
473
|
+
line = lineFor(span);
|
|
474
|
+
line.cells[first] = { value, format: across };
|
|
475
|
+
for (let c = first + 1; c <= last; c++) line.cells[c] = { value: null, format: across };
|
|
476
|
+
} else {
|
|
477
|
+
const c = align === 'right' ? last : first;
|
|
478
|
+
const inset = align === 'right' ? grid.right(c) - (x + w) : x - grid.left(c);
|
|
479
|
+
|
|
480
|
+
line = lineFor([c]);
|
|
481
|
+
line.cells[c] = { value, format: formats.text(design, { indent: indentLevels(inset) }) };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
line.top = Math.min(line.top, design.y);
|
|
485
|
+
line.bottom = Math.max(line.bottom, design.y + (Number(design.h) || 0));
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
return lines.map(l => ({ cells: l.cells, page: row.page, top: l.top, own: l.bottom - l.top }));
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* A text item's value, as a number when it is a total: the item's template
|
|
494
|
+
* holds a placeholder and what it printed is a plain number and nothing else.
|
|
495
|
+
*
|
|
496
|
+
* Kept as text when it could be anything else - a leading zero ("007"), a
|
|
497
|
+
* label beside the figure ("Total: 1200"), a literal number typed into the
|
|
498
|
+
* layout, or more digits than Excel shows without switching to 1.2E+11 or
|
|
499
|
+
* than a double holds exactly.
|
|
500
|
+
*/
|
|
501
|
+
function numericText(value, template) {
|
|
502
|
+
if (typeof value !== 'string' || typeof template !== 'string') return value;
|
|
503
|
+
if (!PLACEHOLDER.test(template)) return value;
|
|
504
|
+
|
|
505
|
+
const text = value.trim();
|
|
506
|
+
if (!NUMERIC_TEXT.test(text)) return value;
|
|
507
|
+
|
|
508
|
+
const whole = text.replace(/^-/, '').split('.')[0];
|
|
509
|
+
const digits = text.replace(/[-.]/g, '');
|
|
510
|
+
if (whole.length > 11 || digits.length > 15) return value;
|
|
511
|
+
|
|
512
|
+
return Number(text);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Row heights for the Report sheet: each row as tall as its content, plus the
|
|
518
|
+
* page's gap below it - up to MAX_GAP_PX - so the sheet is spaced the way the
|
|
519
|
+
* page is. Also where each row starts down the sheet, which is how a graphic
|
|
520
|
+
* finds the row to anchor to.
|
|
521
|
+
*/
|
|
522
|
+
function spaceRows(rows) {
|
|
523
|
+
let sheetTop = 0;
|
|
524
|
+
|
|
525
|
+
rows.forEach((row, i) => {
|
|
526
|
+
const own = row.own > 0 ? row.own : DEFAULT_ROW_PX;
|
|
527
|
+
const next = rows[i + 1];
|
|
528
|
+
|
|
529
|
+
let height = own;
|
|
530
|
+
if (next && next.page === row.page) {
|
|
531
|
+
const gap = next.top - row.top;
|
|
532
|
+
if (gap > own) height = Math.min(gap, own + MAX_GAP_PX);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** the height Excel will draw: points, to the half point, back to pixels */
|
|
536
|
+
row.height = points(height) / 0.75;
|
|
537
|
+
row.sheetTop = sheetTop;
|
|
538
|
+
sheetTop += row.height;
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Where a page position lands on the sheet: the row it falls in and how far
|
|
545
|
+
* down that row, the column and how far across.
|
|
546
|
+
*
|
|
547
|
+
* A row is found by its page position, the last one on that page starting at
|
|
548
|
+
* or above y, and the offset is kept inside it - a row whose gap was capped is
|
|
549
|
+
* shorter on the sheet than on the page, and what fell in the gap lands at its
|
|
550
|
+
* foot rather than in the next row.
|
|
551
|
+
*/
|
|
552
|
+
function locator(rows, grid) {
|
|
553
|
+
const byPage = new Map();
|
|
554
|
+
rows.forEach((row, i) => {
|
|
555
|
+
if (!byPage.has(row.page)) byPage.set(row.page, []);
|
|
556
|
+
byPage.get(row.page).push(i);
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
function y(page, value) {
|
|
560
|
+
const list = byPage.get(page) ?? [rows.length - 1];
|
|
561
|
+
|
|
562
|
+
let pick = list[0];
|
|
563
|
+
for (const i of list) {
|
|
564
|
+
if (rows[i].top <= value && rows[i].top >= rows[pick].top) pick = i;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const r = rows[pick];
|
|
568
|
+
const offset = Math.max(0, Math.min(value - r.top, r.height));
|
|
569
|
+
return { row: pick, offset, sheet: r.sheetTop + offset };
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function x(value) {
|
|
573
|
+
const col = grid.at(Math.max(0, value));
|
|
574
|
+
const offset = Math.max(0, Math.min(value - grid.left(col), grid.px[col]));
|
|
575
|
+
return { col, offset, sheet: grid.left(col) + offset };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
return { x, y };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* The graphics, drawn over the laid-out rows.
|
|
584
|
+
*
|
|
585
|
+
* Pictures and rules are drawings. A box is a drawing too, unless text sits
|
|
586
|
+
* on it: drawings are always above the cells, so a filled box would hide the
|
|
587
|
+
* very text it was put behind. Such a box paints its fill into the cells it
|
|
588
|
+
* covers instead, and draws only its outline - rounded corners and all.
|
|
589
|
+
*
|
|
590
|
+
* @returns {{anchors: object[], media: object[]}}
|
|
591
|
+
*/
|
|
592
|
+
function drawGraphics(graphics, rows, grid, images) {
|
|
593
|
+
const where = locator(rows, grid);
|
|
594
|
+
const anchors = [];
|
|
595
|
+
const media = mediaStore(images);
|
|
596
|
+
|
|
597
|
+
/** a page rectangle in sheet pixels, with the anchor for its top-left */
|
|
598
|
+
const place = (page, x, y, w, h) => {
|
|
599
|
+
const from = where.x(x);
|
|
600
|
+
const top = where.y(page, y);
|
|
601
|
+
const to = where.x(x + w);
|
|
602
|
+
const bottom = where.y(page, y + h);
|
|
603
|
+
|
|
604
|
+
return {
|
|
605
|
+
anchor: { col: from.col, colOff: from.offset, row: top.row, rowOff: top.offset },
|
|
606
|
+
sheet: { x1: from.sheet, x2: to.sheet, y1: top.sheet, y2: bottom.sheet }
|
|
607
|
+
};
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
for (const g of graphics) {
|
|
611
|
+
if (g.kind === 'image') {
|
|
612
|
+
const embedded = media.get(imageSrc(g.item.resolvedSrc));
|
|
613
|
+
if (!embedded) continue;
|
|
614
|
+
|
|
615
|
+
const fit = fitImage(g.item.fit, { w: g.w, h: g.h }, embedded.natural);
|
|
616
|
+
const { anchor } = place(g.page, g.x + fit.x, g.y + fit.y, fit.w, fit.h);
|
|
617
|
+
|
|
618
|
+
anchors.push({
|
|
619
|
+
...anchor, cx: fit.w, cy: fit.h,
|
|
620
|
+
shape: picture({ rId: embedded.rId, alt: g.item.alt, crop: fit.crop })
|
|
621
|
+
});
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
if (g.kind === 'line') {
|
|
626
|
+
const style = g.item.style ?? {};
|
|
627
|
+
const thickness = Math.max(0, Number(style.thickness ?? 1)) || 1;
|
|
628
|
+
const linePen = pen({
|
|
629
|
+
style: ['solid', 'dashed', 'dotted', 'double'].includes(style.lineStyle) ? style.lineStyle : 'solid',
|
|
630
|
+
width: thickness,
|
|
631
|
+
color: argb(style.color) ?? 'FF000000'
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
const vertical = g.item.orientation === 'vertical';
|
|
635
|
+
const at = vertical
|
|
636
|
+
? place(g.page, g.x + g.w / 2, g.y, 0, g.h)
|
|
637
|
+
: place(g.page, g.x, g.y + g.h / 2, g.w, 0);
|
|
638
|
+
|
|
639
|
+
anchors.push({
|
|
640
|
+
...at.anchor,
|
|
641
|
+
cx: vertical ? 0 : at.sheet.x2 - at.sheet.x1,
|
|
642
|
+
cy: vertical ? at.sheet.y2 - at.sheet.y1 : 0,
|
|
643
|
+
shape: rule(linePen)
|
|
644
|
+
});
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
if (g.kind === 'box') {
|
|
649
|
+
const style = g.item.style ?? {};
|
|
650
|
+
const fill = argb(style.background);
|
|
651
|
+
const width = Math.max(0, Number(style.borderWidth ?? 1)) || 1;
|
|
652
|
+
const outline = style.borderStyle === 'none' ? null : pen({
|
|
653
|
+
style: ['solid', 'dashed', 'dotted', 'double'].includes(style.borderStyle) ? style.borderStyle : 'solid',
|
|
654
|
+
width,
|
|
655
|
+
color: argb(style.borderColor) ?? 'FF000000'
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
const area = place(g.page, g.x, g.y, g.w, g.h);
|
|
659
|
+
const behindText = fill && coversText(rows, grid, area.sheet);
|
|
660
|
+
|
|
661
|
+
if (behindText) paintFill(rows, grid, area.sheet, fill);
|
|
662
|
+
if (!outline && (behindText || !fill)) continue;
|
|
663
|
+
|
|
664
|
+
/** a border is drawn inside the box, as border-box draws it; a stroke straddles its path */
|
|
665
|
+
const inset = outline ? outline.width / 2 : 0;
|
|
666
|
+
const shape = place(g.page, g.x + inset, g.y + inset, g.w - 2 * inset, g.h - 2 * inset);
|
|
667
|
+
const w = Math.max(0, shape.sheet.x2 - shape.sheet.x1);
|
|
668
|
+
const h = Math.max(0, shape.sheet.y2 - shape.sheet.y1);
|
|
669
|
+
|
|
670
|
+
anchors.push({
|
|
671
|
+
...shape.anchor, cx: w, cy: h,
|
|
672
|
+
shape: box({
|
|
673
|
+
fill: behindText ? null : fill,
|
|
674
|
+
outline,
|
|
675
|
+
/** the stroke's path runs inset, so its corners curve that much tighter */
|
|
676
|
+
radius: Math.max(0, (Number(style.radius) || 0) - inset),
|
|
677
|
+
w, h
|
|
678
|
+
})
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
return { anchors, media: media.list };
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* The pictures embedded in a sheet, each stored once however many pages show
|
|
689
|
+
* it - a logo in the page header is one file, drawn on every page.
|
|
690
|
+
*/
|
|
691
|
+
function mediaStore(images) {
|
|
692
|
+
const supplied = images instanceof Map ? images : new Map(Object.entries(images ?? {}));
|
|
693
|
+
const bySrc = new Map();
|
|
694
|
+
const list = [];
|
|
695
|
+
|
|
696
|
+
function get(src) {
|
|
697
|
+
if (!src) return null;
|
|
698
|
+
if (bySrc.has(src)) return bySrc.get(src);
|
|
699
|
+
|
|
700
|
+
let bytes = decodeDataUri(src);
|
|
701
|
+
if (!bytes) {
|
|
702
|
+
const given = supplied.get(src);
|
|
703
|
+
bytes = given instanceof ArrayBuffer ? new Uint8Array(given)
|
|
704
|
+
: given instanceof Uint8Array ? given : null;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const kind = bytes ? sniffImage(bytes) : null;
|
|
708
|
+
if (!kind || !IMAGE_TYPES[kind.ext]) {
|
|
709
|
+
bySrc.set(src, null);
|
|
710
|
+
return null;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const n = list.length + 1;
|
|
714
|
+
const entry = {
|
|
715
|
+
rId: `rId${n}`,
|
|
716
|
+
file: `image${n}.${kind.ext}`,
|
|
717
|
+
ext: kind.ext,
|
|
718
|
+
bytes,
|
|
719
|
+
natural: { width: kind.width, height: kind.height }
|
|
720
|
+
};
|
|
721
|
+
|
|
722
|
+
list.push(entry);
|
|
723
|
+
bySrc.set(src, entry);
|
|
724
|
+
return entry;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
return { get, list };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
/** the rows and columns a sheet rectangle covers at least half of; or the one under its middle */
|
|
732
|
+
function coveredCells(rows, grid, area) {
|
|
733
|
+
const half = (a1, a2, b1, b2) => Math.min(a2, b2) - Math.max(a1, b1) >= (b2 - b1) / 2;
|
|
734
|
+
|
|
735
|
+
const rowIndexes = [];
|
|
736
|
+
rows.forEach((row, i) => {
|
|
737
|
+
if (row.height > 0 && half(area.y1, area.y2, row.sheetTop, row.sheetTop + row.height)) rowIndexes.push(i);
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
const colIndexes = [];
|
|
741
|
+
for (let c = 0; c < grid.px.length; c++) {
|
|
742
|
+
if (half(area.x1, area.x2, grid.left(c), grid.right(c))) colIndexes.push(c);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (rowIndexes.length && colIndexes.length) return { rowIndexes, colIndexes };
|
|
746
|
+
|
|
747
|
+
const midY = (area.y1 + area.y2) / 2;
|
|
748
|
+
const midRow = rows.findIndex(r => midY >= r.sheetTop && midY < r.sheetTop + r.height);
|
|
749
|
+
const midCol = grid.at((area.x1 + area.x2) / 2);
|
|
750
|
+
|
|
751
|
+
return midRow < 0 ? { rowIndexes: [], colIndexes: [] } : { rowIndexes: [midRow], colIndexes: [midCol] };
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
/** whether any cell with something in it overlaps a sheet rectangle at all */
|
|
756
|
+
function coversText(rows, grid, area) {
|
|
757
|
+
return rows.some((row, r) => {
|
|
758
|
+
if (row.sheetTop >= area.y2 || row.sheetTop + row.height <= area.y1) return false;
|
|
759
|
+
return row.cells.some((cell, c) => {
|
|
760
|
+
if (!cell || cell.value === null || cell.value === undefined || cell.value === '') return false;
|
|
761
|
+
return grid.left(c) < area.x2 && grid.right(c) > area.x1;
|
|
762
|
+
});
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* A box's fill, painted into the cells under it. A cell with a fill of its own
|
|
769
|
+
* - a table header - keeps it, because that cell is drawn over the box.
|
|
770
|
+
*/
|
|
771
|
+
function paintFill(rows, grid, area, fill) {
|
|
772
|
+
const { rowIndexes, colIndexes } = coveredCells(rows, grid, area);
|
|
773
|
+
const painted = new Map();
|
|
774
|
+
|
|
775
|
+
const withFill = (format) => {
|
|
776
|
+
if (format?.fill) return format;
|
|
777
|
+
if (!painted.has(format)) painted.set(format, { ...(format ?? {}), fill });
|
|
778
|
+
return painted.get(format);
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
for (const r of rowIndexes) {
|
|
782
|
+
for (const c of colIndexes) {
|
|
783
|
+
const cell = rows[r].cells[c];
|
|
784
|
+
rows[r].cells[c] = cell ? { ...cell, format: withFill(cell.format) } : { value: null, format: withFill(null) };
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* cellFormat, remembered per descriptor shape - a table's column, or a text
|
|
792
|
+
* item's style - so a thousand rows of one table share one format object and
|
|
793
|
+
* the writer resolves it once.
|
|
794
|
+
*
|
|
795
|
+
* `formats.text` gives a text item's format with its placement applied:
|
|
796
|
+
* centred across a span, or indented by so many levels.
|
|
797
|
+
*/
|
|
798
|
+
function formatCache() {
|
|
799
|
+
const byColumn = new WeakMap();
|
|
800
|
+
const byStyle = new WeakMap();
|
|
801
|
+
|
|
802
|
+
function formats(design) {
|
|
803
|
+
if (!design) return null;
|
|
804
|
+
|
|
805
|
+
if (design.kind === 'text') return formats.text(design);
|
|
806
|
+
|
|
807
|
+
const key = design.column ?? design;
|
|
808
|
+
if (!byColumn.has(key)) byColumn.set(key, {});
|
|
809
|
+
const entry = byColumn.get(key);
|
|
810
|
+
entry[design.kind] ??= cellFormat(design);
|
|
811
|
+
return entry[design.kind];
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
formats.text = (design, { centred = false, indent = 0 } = {}) => {
|
|
815
|
+
const key = design.style ?? design;
|
|
816
|
+
if (!byStyle.has(key)) byStyle.set(key, new Map());
|
|
817
|
+
const variants = byStyle.get(key);
|
|
818
|
+
|
|
819
|
+
const variant = `${centred}|${indent}`;
|
|
820
|
+
if (!variants.has(variant)) {
|
|
821
|
+
const base = cellFormat(design);
|
|
822
|
+
variants.set(variant, {
|
|
823
|
+
...base,
|
|
824
|
+
alignment: {
|
|
825
|
+
...base.alignment,
|
|
826
|
+
...(centred ? { horizontal: 'centerContinuous' } : {}),
|
|
827
|
+
indent: centred ? 0 : indent
|
|
828
|
+
}
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
return variants.get(variant);
|
|
832
|
+
};
|
|
833
|
+
|
|
834
|
+
return formats;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Widths from the content, for plain sheets and for a column the design gives
|
|
840
|
+
* no width - the group column, say.
|
|
841
|
+
*/
|
|
842
|
+
function contentWidths(rows) {
|
|
843
|
+
const widths = [];
|
|
844
|
+
|
|
845
|
+
for (const { cells } of rows) {
|
|
846
|
+
cells.forEach((cell, i) => {
|
|
847
|
+
widths[i] ??= MIN_WIDTH;
|
|
848
|
+
const value = cell?.value;
|
|
849
|
+
if (value === null || value === undefined) return;
|
|
850
|
+
|
|
851
|
+
const longest = value instanceof Date
|
|
852
|
+
? 18
|
|
853
|
+
: String(value).split('\n').reduce((n, line) => Math.max(n, line.length), 0);
|
|
854
|
+
|
|
855
|
+
widths[i] = Math.max(widths[i], Math.min(MAX_WIDTH, longest + 2));
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
for (let i = 0; i < widths.length; i++) widths[i] ??= MIN_WIDTH;
|
|
860
|
+
return widths;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
/* ---------------- worksheet ---------------- */
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* A sheet's XML. Children follow the order CT_Worksheet fixes - dimension,
|
|
869
|
+
* sheetViews, cols, sheetData, autoFilter, ignoredErrors, drawing - because
|
|
870
|
+
* Excel rejects them in any other.
|
|
871
|
+
*/
|
|
872
|
+
function worksheet({ name, rows, frozen, gridLines, widths, width, drawing }, styles) {
|
|
873
|
+
if (rows.length > XLSX_LIMITS.rows) {
|
|
874
|
+
throw new RangeError(
|
|
875
|
+
`Sheet "${name}" has ${rows.length} rows; Excel allows ${XLSX_LIMITS.rows}.`);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (width > XLSX_LIMITS.columns) {
|
|
879
|
+
throw new RangeError(
|
|
880
|
+
`Sheet "${name}" has ${width} columns; Excel allows ${XLSX_LIMITS.columns}.`);
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
const range = usedRange(width, rows.length);
|
|
884
|
+
const xfFor = xfResolver(styles);
|
|
885
|
+
|
|
886
|
+
const out = [XML_HEAD, `<worksheet xmlns="${NS_MAIN}" xmlns:r="${NS_REL}">`];
|
|
887
|
+
|
|
888
|
+
out.push(`<dimension ref="${range}"/>`);
|
|
889
|
+
|
|
890
|
+
out.push(`<sheetViews><sheetView${gridLines ? '' : ' showGridLines="0"'} workbookViewId="0">`);
|
|
891
|
+
if (frozen && rows.length > 1) {
|
|
892
|
+
out.push('<pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>' +
|
|
893
|
+
'<selection pane="bottomLeft" activeCell="A2" sqref="A2"/>');
|
|
894
|
+
}
|
|
895
|
+
out.push('</sheetView></sheetViews>');
|
|
896
|
+
|
|
897
|
+
if (width > 0) {
|
|
898
|
+
out.push('<cols>');
|
|
899
|
+
for (let i = 0; i < width; i++) {
|
|
900
|
+
const w = widths?.[i] ?? MIN_WIDTH;
|
|
901
|
+
out.push(`<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`);
|
|
902
|
+
}
|
|
903
|
+
out.push('</cols>');
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
out.push('<sheetData>');
|
|
907
|
+
rows.forEach((row, r) => {
|
|
908
|
+
let cells = '';
|
|
909
|
+
row.cells.forEach((c, i) => {
|
|
910
|
+
if (c) cells += cell(`${columnName(i)}${r + 1}`, c.value, c.format, xfFor);
|
|
911
|
+
});
|
|
912
|
+
|
|
913
|
+
const height = Number(row.height) > 0
|
|
914
|
+
? ` ht="${points(Number(row.height))}" customHeight="1"`
|
|
915
|
+
: '';
|
|
916
|
+
|
|
917
|
+
out.push(`<row r="${r + 1}"${height}>${cells}</row>`);
|
|
918
|
+
});
|
|
919
|
+
out.push('</sheetData>');
|
|
920
|
+
|
|
921
|
+
if (frozen && width > 0) out.push(`<autoFilter ref="${range}"/>`);
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* Text that looks like a number is text on purpose here - a "007", or a
|
|
925
|
+
* figure beside a label - so Excel's green "number stored as text" flag on
|
|
926
|
+
* every one of them is noise.
|
|
927
|
+
*/
|
|
928
|
+
if (width > 0) {
|
|
929
|
+
out.push(`<ignoredErrors><ignoredError sqref="${range}" numberStoredAsText="1"/></ignoredErrors>`);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
if (drawing) out.push('<drawing r:id="rId1"/>');
|
|
933
|
+
|
|
934
|
+
out.push('</worksheet>');
|
|
935
|
+
return out.join('');
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
function usedRange(width, height) {
|
|
940
|
+
if (width === 0 || height === 0) return 'A1';
|
|
941
|
+
const last = `${columnName(width - 1)}${height}`;
|
|
942
|
+
return last === 'A1' ? 'A1' : `A1:${last}`;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
/** format object and number format to a cell format index, each pair resolved once */
|
|
947
|
+
function xfResolver(styles) {
|
|
948
|
+
const cache = new WeakMap();
|
|
949
|
+
const plain = new Map();
|
|
950
|
+
|
|
951
|
+
return (format, numFmt) => {
|
|
952
|
+
if (!format) {
|
|
953
|
+
if (!plain.has(numFmt)) plain.set(numFmt, styles.xf(null, numFmt));
|
|
954
|
+
return plain.get(numFmt);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
if (!cache.has(format)) cache.set(format, new Map());
|
|
958
|
+
const byNumFmt = cache.get(format);
|
|
959
|
+
if (!byNumFmt.has(numFmt)) byNumFmt.set(numFmt, styles.xf(format, numFmt));
|
|
960
|
+
return byNumFmt.get(numFmt);
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
/**
|
|
966
|
+
* One cell. An empty value with no format writes nothing - an absent <c> is an
|
|
967
|
+
* empty cell. One with a format still writes the cell, so a blank in a table
|
|
968
|
+
* keeps its grid and fill.
|
|
969
|
+
*
|
|
970
|
+
* @param {string} ref such as "B7"
|
|
971
|
+
* @param {*} value the raw value from the row
|
|
972
|
+
* @param {object|null} format
|
|
973
|
+
* @param {Function} xfFor
|
|
974
|
+
*/
|
|
975
|
+
function cell(ref, value, format, xfFor) {
|
|
976
|
+
const empty = value === null || value === undefined || value === '';
|
|
977
|
+
const isDate = value instanceof Date && !Number.isNaN(value.getTime());
|
|
978
|
+
|
|
979
|
+
let numFmt = 0;
|
|
980
|
+
let serial = null;
|
|
981
|
+
if (isDate) {
|
|
982
|
+
serial = excelSerial(value);
|
|
983
|
+
numFmt = Number.isInteger(serial) ? NUMFMT_DATE : NUMFMT_DATE_TIME;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
const xf = xfFor(format, numFmt);
|
|
987
|
+
const s = xf ? ` s="${xf}"` : '';
|
|
988
|
+
|
|
989
|
+
if (empty) return xf ? `<c r="${ref}"${s}/>` : '';
|
|
990
|
+
|
|
991
|
+
if (isDate) return `<c r="${ref}"${s}><v>${serial}</v></c>`;
|
|
992
|
+
|
|
993
|
+
if (typeof value === 'number') {
|
|
994
|
+
/** NaN and Infinity have no spreadsheet form, so they keep their words */
|
|
995
|
+
if (!Number.isFinite(value)) return inlineString(ref, String(value), s);
|
|
996
|
+
return `<c r="${ref}"${s}><v>${value}</v></c>`;
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
if (typeof value === 'boolean') {
|
|
1000
|
+
return `<c r="${ref}"${s} t="b"><v>${value ? 1 : 0}</v></c>`;
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
return inlineString(ref, String(value), s);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
function inlineString(ref, text, s) {
|
|
1008
|
+
let clean = text.replace(INVALID_XML, '');
|
|
1009
|
+
|
|
1010
|
+
if (clean.length > XLSX_LIMITS.cellText) {
|
|
1011
|
+
clean = clean.slice(0, XLSX_LIMITS.cellText);
|
|
1012
|
+
/** never leave half a surrogate pair at the cut */
|
|
1013
|
+
if (/[\uD800-\uDBFF]$/.test(clean)) clean = clean.slice(0, -1);
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/** without this, Excel trims leading and trailing spaces and folds line breaks */
|
|
1017
|
+
const preserve = /^\s|\s$|\n/.test(clean) ? ' xml:space="preserve"' : '';
|
|
1018
|
+
|
|
1019
|
+
return `<c r="${ref}"${s} t="inlineStr"><is><t${preserve}>` +
|
|
1020
|
+
`${escapeText(clean.replace(EXCEL_ESCAPE, '_x005F_$1'))}</t></is></c>`;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
/**
|
|
1025
|
+
* A Date as an Excel serial number: days since 1899-12-30, the fraction the
|
|
1026
|
+
* time of day.
|
|
1027
|
+
*
|
|
1028
|
+
* Read in local time, because a spreadsheet has no time zones and the reader
|
|
1029
|
+
* expects the date the report showed them, not the UTC instant behind it.
|
|
1030
|
+
*/
|
|
1031
|
+
function excelSerial(date) {
|
|
1032
|
+
const local = Date.UTC(
|
|
1033
|
+
date.getFullYear(), date.getMonth(), date.getDate(),
|
|
1034
|
+
date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()
|
|
1035
|
+
);
|
|
1036
|
+
|
|
1037
|
+
return local / 86400000 + 25569;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* A zero-based column index as Excel letters: 0 is A, 25 is Z, 26 is AA.
|
|
1043
|
+
* Bijective base 26 - there is no zero digit, which is why it is not toString(26).
|
|
1044
|
+
*/
|
|
1045
|
+
export function columnName(index) {
|
|
1046
|
+
let name = '';
|
|
1047
|
+
let n = index + 1;
|
|
1048
|
+
|
|
1049
|
+
while (n > 0) {
|
|
1050
|
+
const rem = (n - 1) % 26;
|
|
1051
|
+
name = String.fromCharCode(65 + rem) + name;
|
|
1052
|
+
n = Math.floor((n - 1) / 26);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
return name;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
/**
|
|
1060
|
+
* Names Excel will accept: at most 31 characters, none of []:*?/\, not starting
|
|
1061
|
+
* or ending with an apostrophe, never blank, and unique ignoring case.
|
|
1062
|
+
* "History" is reserved by Excel, so it counts as taken.
|
|
1063
|
+
*
|
|
1064
|
+
* @param {string[]} wanted
|
|
1065
|
+
* @returns {string[]}
|
|
1066
|
+
*/
|
|
1067
|
+
export function sheetNames(wanted) {
|
|
1068
|
+
const used = new Set(['history']);
|
|
1069
|
+
|
|
1070
|
+
return wanted.map((raw) => {
|
|
1071
|
+
let base = String(raw ?? '')
|
|
1072
|
+
.replace(SHEET_NAME_BANNED, '-')
|
|
1073
|
+
.trim()
|
|
1074
|
+
.replace(/^'+|'+$/g, '')
|
|
1075
|
+
.trim() || 'Sheet';
|
|
1076
|
+
|
|
1077
|
+
base = clip(base, XLSX_LIMITS.sheetName);
|
|
1078
|
+
|
|
1079
|
+
let name = base;
|
|
1080
|
+
for (let n = 2; used.has(name.toLowerCase()); n++) {
|
|
1081
|
+
const suffix = ` (${n})`;
|
|
1082
|
+
name = clip(base, XLSX_LIMITS.sheetName - suffix.length) + suffix;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
used.add(name.toLowerCase());
|
|
1086
|
+
return name;
|
|
1087
|
+
});
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
|
|
1091
|
+
/** cut to a length without splitting a surrogate pair */
|
|
1092
|
+
function clip(text, length) {
|
|
1093
|
+
if (text.length <= length) return text;
|
|
1094
|
+
const cut = text.slice(0, length);
|
|
1095
|
+
return /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut;
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
/* ---------------- package parts ---------------- */
|
|
1100
|
+
|
|
1101
|
+
|
|
1102
|
+
function contentTypes(sheetCount, drawings = [], media = []) {
|
|
1103
|
+
const sheets = Array.from({ length: sheetCount }, (_, i) =>
|
|
1104
|
+
`<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="${CT_SHEET}"/>`
|
|
1105
|
+
).join('');
|
|
1106
|
+
|
|
1107
|
+
const drawingParts = drawings.map(d =>
|
|
1108
|
+
`<Override PartName="/xl/drawings/drawing${d.n}.xml" ContentType="${DRAWING_CONTENT_TYPE}"/>`
|
|
1109
|
+
).join('');
|
|
1110
|
+
|
|
1111
|
+
const imageDefaults = [...new Set(media.map(m => m.ext))].map(ext =>
|
|
1112
|
+
`<Default Extension="${ext}" ContentType="${IMAGE_TYPES[ext]}"/>`
|
|
1113
|
+
).join('');
|
|
1114
|
+
|
|
1115
|
+
return XML_HEAD +
|
|
1116
|
+
`<Types xmlns="${NS_TYPES}">` +
|
|
1117
|
+
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
|
1118
|
+
'<Default Extension="xml" ContentType="application/xml"/>' +
|
|
1119
|
+
imageDefaults +
|
|
1120
|
+
`<Override PartName="/xl/workbook.xml" ContentType="${CT_BOOK}"/>` +
|
|
1121
|
+
`<Override PartName="/xl/styles.xml" ContentType="${CT_STYLES}"/>` +
|
|
1122
|
+
sheets +
|
|
1123
|
+
drawingParts +
|
|
1124
|
+
'</Types>';
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
function packageRels() {
|
|
1129
|
+
return XML_HEAD +
|
|
1130
|
+
`<Relationships xmlns="${NS_PKG_REL}">` +
|
|
1131
|
+
`<Relationship Id="rId1" Type="${REL_DOC}" Target="xl/workbook.xml"/>` +
|
|
1132
|
+
'</Relationships>';
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
|
|
1136
|
+
/** a worksheet's relationships: its drawing, which is the one it can have */
|
|
1137
|
+
function sheetRels(drawingNumber) {
|
|
1138
|
+
return XML_HEAD +
|
|
1139
|
+
`<Relationships xmlns="${NS_PKG_REL}">` +
|
|
1140
|
+
`<Relationship Id="rId1" Type="${REL_DRAWING}" Target="../drawings/drawing${drawingNumber}.xml"/>` +
|
|
1141
|
+
'</Relationships>';
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
/**
|
|
1146
|
+
* The sheet list, plus the hidden name Excel keeps for each sheet's filter
|
|
1147
|
+
* range - it opens a filter without one, but repairs the file the first time
|
|
1148
|
+
* the filter is touched.
|
|
1149
|
+
*/
|
|
1150
|
+
function workbook(sheets) {
|
|
1151
|
+
const list = sheets.map((sheet, i) =>
|
|
1152
|
+
`<sheet name="${escapeAttr(sheet.name)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`
|
|
1153
|
+
).join('');
|
|
1154
|
+
|
|
1155
|
+
const filters = sheets.map((sheet, i) => {
|
|
1156
|
+
if (!sheet.frozen || sheet.width === 0) return '';
|
|
1157
|
+
|
|
1158
|
+
const quoted = `'${sheet.name.replace(/'/g, "''")}'`;
|
|
1159
|
+
const ref = `${quoted}!$A$1:$${columnName(sheet.width - 1)}$${sheet.rows.length}`;
|
|
1160
|
+
|
|
1161
|
+
return `<definedName name="_xlnm._FilterDatabase" localSheetId="${i}" hidden="1">` +
|
|
1162
|
+
`${escapeText(ref)}</definedName>`;
|
|
1163
|
+
}).join('');
|
|
1164
|
+
|
|
1165
|
+
return XML_HEAD +
|
|
1166
|
+
`<workbook xmlns="${NS_MAIN}" xmlns:r="${NS_REL}">` +
|
|
1167
|
+
'<bookViews><workbookView/></bookViews>' +
|
|
1168
|
+
`<sheets>${list}</sheets>` +
|
|
1169
|
+
(filters ? `<definedNames>${filters}</definedNames>` : '') +
|
|
1170
|
+
'</workbook>';
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
|
|
1174
|
+
function workbookRels(sheetCount) {
|
|
1175
|
+
const sheets = Array.from({ length: sheetCount }, (_, i) =>
|
|
1176
|
+
`<Relationship Id="rId${i + 1}" Type="${REL_SHEET}" Target="worksheets/sheet${i + 1}.xml"/>`
|
|
1177
|
+
).join('');
|
|
1178
|
+
|
|
1179
|
+
return XML_HEAD +
|
|
1180
|
+
`<Relationships xmlns="${NS_PKG_REL}">` +
|
|
1181
|
+
sheets +
|
|
1182
|
+
`<Relationship Id="rId${sheetCount + 1}" Type="${REL_STYLES}" Target="styles.xml"/>` +
|
|
1183
|
+
'</Relationships>';
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
/* ---------------- escaping ---------------- */
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
function escapeText(text) {
|
|
1191
|
+
return text
|
|
1192
|
+
.replace(/&/g, '&')
|
|
1193
|
+
.replace(/</g, '<')
|
|
1194
|
+
.replace(/>/g, '>');
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
|
|
1198
|
+
function escapeAttr(text) {
|
|
1199
|
+
return escapeText(text.replace(INVALID_XML, '')).replace(/"/g, '"');
|
|
1200
|
+
}
|