report-studio 1.2.1 → 1.2.3

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,457 @@
1
+ /**
2
+ * xlsx-style.js turns how a report cell was drawn into how an Excel cell is
3
+ * formatted, and keeps the workbook's table of formats.
4
+ *
5
+ * Two halves:
6
+ *
7
+ * - cellFormat reads a design descriptor from rows.js - a text item's style, or
8
+ * a table cell's column and table style - and says what the cell looks like
9
+ * in Excel's terms: a font, a fill, a border, an alignment. What the layout
10
+ * leaves unset is filled in from what report.css draws, so an unstyled table
11
+ * exports as it looks on screen, not as Excel's defaults.
12
+ *
13
+ * - createStyles is the registry. Excel keeps formats as indexed tables - every
14
+ * distinct font, fill and border once, and one cell format (xf) per distinct
15
+ * combination of them - so a cell refers to its format by number. The same
16
+ * look asked for twice is one entry.
17
+ *
18
+ * Padding becomes an indent, the only inset a cell has. What has no cell
19
+ * equivalent at all - line height, transparency - is left behind; rounded
20
+ * corners belong to boxes, which xlsx-drawing.js draws as shapes.
21
+ */
22
+
23
+
24
+ /**
25
+ * What report.css draws when a layout says nothing. Kept in step with that
26
+ * stylesheet by a spec, since the two have to agree for an export to look like
27
+ * the preview.
28
+ */
29
+ export const REPORT_DEFAULTS = Object.freeze({
30
+ fontFamily: 'Helvetica, Arial, sans-serif',
31
+ fontSize: 12,
32
+ headerWeight: 600,
33
+ headerBackground: '#f1f3f5',
34
+ ruleColor: '#cdd4db',
35
+ ruleWidth: 1,
36
+ ruleStyle: 'solid',
37
+ cellPadding: 8
38
+ });
39
+
40
+ /**
41
+ * Fonts every machine that opens a workbook is likely to have. A CSS stack
42
+ * names its first choice first, but the first choice is often Helvetica, which
43
+ * Windows does not have; the first of these in the stack is the better pick.
44
+ */
45
+ const OFFICE_FONTS = [
46
+ 'aptos', 'arial', 'calibri', 'cambria', 'candara', 'consolas', 'constantia',
47
+ 'corbel', 'courier new', 'georgia', 'segoe ui', 'tahoma', 'times new roman',
48
+ 'trebuchet ms', 'verdana'
49
+ ];
50
+
51
+ /** what a CSS generic family means in a workbook */
52
+ const GENERIC_FONTS = {
53
+ 'sans-serif': 'Arial',
54
+ 'serif': 'Times New Roman',
55
+ 'monospace': 'Courier New',
56
+ 'system-ui': 'Calibri',
57
+ '-apple-system': 'Calibri',
58
+ 'ui-sans-serif': 'Arial',
59
+ 'ui-serif': 'Times New Roman',
60
+ 'ui-monospace': 'Courier New',
61
+ 'cursive': 'Comic Sans MS',
62
+ 'fantasy': 'Impact'
63
+ };
64
+
65
+ /** Excel refuses a font name longer than this */
66
+ const FONT_NAME_LIMIT = 31;
67
+
68
+ /** the CSS colour names a hand-written layout is likely to use */
69
+ const NAMED_COLORS = {
70
+ black: '000000', white: 'FFFFFF', red: 'FF0000', green: '008000', blue: '0000FF',
71
+ gray: '808080', grey: '808080', silver: 'C0C0C0', maroon: '800000', navy: '000080',
72
+ teal: '008080', olive: '808000', purple: '800080', orange: 'FFA500', yellow: 'FFFF00',
73
+ lime: '00FF00', aqua: '00FFFF', cyan: '00FFFF', fuchsia: 'FF00FF', magenta: 'FF00FF',
74
+ darkgray: 'A9A9A9', darkgrey: 'A9A9A9', lightgray: 'D3D3D3', lightgrey: 'D3D3D3'
75
+ };
76
+
77
+ const RULE_STYLES = ['solid', 'dashed', 'dotted', 'double'];
78
+
79
+ const ALIGNMENTS = ['left', 'center', 'right'];
80
+
81
+ /** Excel's default column: 8.43 characters of Calibri 11, which is 64px */
82
+ export const DEFAULT_COLUMN_PX = 64;
83
+
84
+ /**
85
+ * One level of Excel's indent, in pixels: three spaces of the default font.
86
+ * Padding and an item's offset inside its column are both written as indents,
87
+ * the only inset Excel gives a cell.
88
+ */
89
+ export const INDENT_PX = 9;
90
+
91
+ /** Excel's cap on indent levels */
92
+ const MAX_INDENT = 15;
93
+
94
+
95
+ /**
96
+ * Pixels of inset as indent levels, to the nearest.
97
+ * @param {number} px
98
+ * @returns {number}
99
+ */
100
+ export function indentLevels(px) {
101
+ const n = Math.round((Number(px) || 0) / INDENT_PX);
102
+ return Math.max(0, Math.min(MAX_INDENT, n));
103
+ }
104
+
105
+
106
+ /* ---------------- converters ---------------- */
107
+
108
+
109
+ /**
110
+ * A CSS colour as Excel's ARGB hex, or null when there is none to give.
111
+ *
112
+ * Hex in its four lengths, rgb() and rgba() in either syntax, and the common
113
+ * names. Excel has no transparency, so alpha is dropped - except a colour that
114
+ * is fully transparent, which is no colour at all.
115
+ *
116
+ * @param {*} value
117
+ * @returns {string|null} such as 'FF1A2B3C'
118
+ */
119
+ export function argb(value) {
120
+ if (typeof value !== 'string') return null;
121
+ const css = value.trim().toLowerCase();
122
+ if (css === '' || css === 'transparent' || css === 'none' || css === 'inherit') return null;
123
+
124
+ if (NAMED_COLORS[css]) return `FF${NAMED_COLORS[css]}`;
125
+
126
+ const hex = css.match(/^#([0-9a-f]{3,8})$/);
127
+ if (hex) {
128
+ let digits = hex[1];
129
+ if (digits.length === 3 || digits.length === 4) {
130
+ digits = [...digits].map(d => d + d).join('');
131
+ }
132
+ if (digits.length === 8) {
133
+ if (digits.slice(6) === '00') return null;
134
+ digits = digits.slice(0, 6);
135
+ }
136
+ return digits.length === 6 ? `FF${digits.toUpperCase()}` : null;
137
+ }
138
+
139
+ const fn = css.match(/^rgba?\(\s*([^)]*)\)$/);
140
+ if (fn) {
141
+ const parts = fn[1].split(/[\s,/]+/).filter(Boolean);
142
+ if (parts.length < 3) return null;
143
+
144
+ const alpha = parts[3];
145
+ if (alpha !== undefined && parseFloat(alpha) === 0) return null;
146
+
147
+ const channels = parts.slice(0, 3).map((part) => {
148
+ /** 255 / 100 rather than 2.55, which leaves 50% a hair under 127.5 */
149
+ const n = part.endsWith('%') ? (parseFloat(part) * 255) / 100 : parseFloat(part);
150
+ return Number.isFinite(n) ? Math.max(0, Math.min(255, Math.round(n))) : null;
151
+ });
152
+ if (channels.includes(null)) return null;
153
+
154
+ return 'FF' + channels.map(n => n.toString(16).padStart(2, '0')).join('').toUpperCase();
155
+ }
156
+
157
+ return null;
158
+ }
159
+
160
+
161
+ /**
162
+ * One font name from a CSS font-family stack.
163
+ * @param {*} stack such as '"Segoe UI", Helvetica, sans-serif'
164
+ * @returns {string}
165
+ */
166
+ export function fontName(stack) {
167
+ const families = String(stack ?? '')
168
+ .split(',')
169
+ .map(f => f.trim().replace(/^['"]|['"]$/g, '').trim())
170
+ .filter(Boolean);
171
+
172
+ if (families.length === 0) return 'Arial';
173
+
174
+ const safe = families.find(f => OFFICE_FONTS.includes(f.toLowerCase()));
175
+ const chosen = safe ?? GENERIC_FONTS[families[0].toLowerCase()] ?? families[0];
176
+
177
+ return chosen.slice(0, FONT_NAME_LIMIT);
178
+ }
179
+
180
+
181
+ /** CSS pixels as points, to the half point Excel shows */
182
+ export function points(px) {
183
+ return Math.round(px * 0.75 * 2) / 2;
184
+ }
185
+
186
+
187
+ /**
188
+ * CSS pixels as an Excel column width, which is counted in characters of the
189
+ * default font: Calibri 11's digits are 7px wide, plus 5px of cell padding.
190
+ */
191
+ export function columnChars(px) {
192
+ return Math.max(1, Math.round(((px - 5) / 7) * 100) / 100);
193
+ }
194
+
195
+
196
+ /** whether a CSS font-weight is bold enough to be bold in Excel */
197
+ export function isBold(weight) {
198
+ if (weight === 'bold' || weight === 'bolder') return true;
199
+ const n = Number(weight);
200
+ return Number.isFinite(n) && n >= 600;
201
+ }
202
+
203
+
204
+ /**
205
+ * A rule as an Excel border style, by the nearest weight Excel has: it draws
206
+ * thin, medium and thick, and only a thin dot.
207
+ *
208
+ * @param {{style?: string, width?: number, color?: string}} rule
209
+ * @returns {{style: string, color: string|null}|null} null for no rule
210
+ */
211
+ export function excelBorder({ style = 'solid', width = 1, color = null } = {}) {
212
+ if (style === 'none' || style === 'hidden') return null;
213
+
214
+ const pen = RULE_STYLES.includes(style) ? style : 'solid';
215
+ const w = Number(width);
216
+ if (!Number.isFinite(w) || w <= 0) return null;
217
+
218
+ const excel = {
219
+ solid: w <= 1 ? 'thin' : w <= 2 ? 'medium' : 'thick',
220
+ dashed: w <= 1 ? 'dashed' : 'mediumDashed',
221
+ dotted: 'dotted',
222
+ double: 'double'
223
+ }[pen];
224
+
225
+ return { style: excel, color: argb(color) };
226
+ }
227
+
228
+
229
+ /* ---------------- what a cell looks like ---------------- */
230
+
231
+
232
+ /**
233
+ * The Excel format for one cell of a report.
234
+ *
235
+ * @param {object|null} design a descriptor from rows.js
236
+ * @returns {object|null} { font, fill, border, alignment }, null for the default
237
+ */
238
+ export function cellFormat(design) {
239
+ if (!design) return null;
240
+
241
+ if (design.kind === 'text') return textFormat(design.style ?? {});
242
+ if (design.kind === 'head' || design.kind === 'cell') {
243
+ return tableFormat(design.kind === 'head', design.column ?? {}, design.table ?? {});
244
+ }
245
+
246
+ return null;
247
+ }
248
+
249
+
250
+ /**
251
+ * A text item: its own font, colour and alignment. Text sits at the top of its
252
+ * box on the page and never wraps here - a cell's neighbours are empty more
253
+ * often than not, and spilling into them is how a long line stays one line.
254
+ *
255
+ * A text style may also carry background, border and padding, but items.js
256
+ * draws none of the three and the designer offers none of them, so neither
257
+ * does the export: the workbook shows what the preview shows. A filled or
258
+ * framed panel is a box, which the export does draw.
259
+ */
260
+ function textFormat(style) {
261
+ return {
262
+ font: {
263
+ name: fontName(style.fontFamily ?? REPORT_DEFAULTS.fontFamily),
264
+ size: points(positive(style.fontSize) ?? REPORT_DEFAULTS.fontSize),
265
+ bold: isBold(style.fontWeight),
266
+ italic: style.fontStyle === 'italic' || style.fontStyle === 'oblique',
267
+ color: argb(style.color)
268
+ },
269
+ fill: null,
270
+ border: null,
271
+ alignment: {
272
+ horizontal: ALIGNMENTS.includes(style.align) ? style.align : 'left',
273
+ vertical: 'top',
274
+ wrapText: false
275
+ }
276
+ };
277
+ }
278
+
279
+
280
+ /**
281
+ * A table cell: the table's font, the column's alignment, the grid on all four
282
+ * sides, and the header's fill and weight - each falling back to what
283
+ * report.css draws, which is what the reader saw.
284
+ */
285
+ function tableFormat(head, column, table) {
286
+ const style = table.style ?? {};
287
+
288
+ const color = head
289
+ ? argb(style.headerColor) ?? argb(style.color)
290
+ : argb(style.color);
291
+
292
+ return {
293
+ font: {
294
+ name: fontName(style.fontFamily ?? REPORT_DEFAULTS.fontFamily),
295
+ size: points(positive(style.fontSize) ?? REPORT_DEFAULTS.fontSize),
296
+ bold: head ? isBold(style.fontWeight ?? REPORT_DEFAULTS.headerWeight) : isBold(style.fontWeight),
297
+ italic: style.fontStyle === 'italic' || style.fontStyle === 'oblique',
298
+ color
299
+ },
300
+ fill: head
301
+ ? (style.headerBackground === null ? null
302
+ : argb(style.headerBackground ?? REPORT_DEFAULTS.headerBackground))
303
+ : argb(style.background),
304
+ border: excelBorder({
305
+ style: style.borderStyle ?? REPORT_DEFAULTS.ruleStyle,
306
+ width: style.borderWidth ?? REPORT_DEFAULTS.ruleWidth,
307
+ color: style.borderColor ?? REPORT_DEFAULTS.ruleColor
308
+ }),
309
+ alignment: {
310
+ horizontal: ALIGNMENTS.includes(column.align) ? column.align : 'left',
311
+ vertical: 'center',
312
+ wrapText: table.wrap !== false,
313
+ /** report.css pads a cell 8px either side; a centred cell has no side to pad */
314
+ indent: column.align === 'center' ? 0 : indentLevels(REPORT_DEFAULTS.cellPadding)
315
+ }
316
+ };
317
+ }
318
+
319
+
320
+ function positive(value) {
321
+ const n = Number(value);
322
+ return Number.isFinite(n) && n > 0 ? n : null;
323
+ }
324
+
325
+
326
+ /* ---------------- the registry ---------------- */
327
+
328
+
329
+ /**
330
+ * The workbook's formats. `xf` hands out a cell format's index, adding what it
331
+ * has not seen; `xml` writes styles.xml once every cell has asked.
332
+ *
333
+ * Entry 0 of each table is Excel's default and stays so - Calibri 11, no fill,
334
+ * no border - because the column widths are counted in that font. The two
335
+ * leading fills are required by Excel even though nothing uses gray125.
336
+ */
337
+ export function createStyles() {
338
+ const fonts = ['<font><sz val="11"/><name val="Calibri"/><family val="2"/></font>'];
339
+ const fills = [
340
+ '<fill><patternFill patternType="none"/></fill>',
341
+ '<fill><patternFill patternType="gray125"/></fill>'
342
+ ];
343
+ const borders = ['<border><left/><right/><top/><bottom/><diagonal/></border>'];
344
+ const xfs = ['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'];
345
+
346
+ const index = new Map([
347
+ ...fonts.map((x, i) => [x, i]),
348
+ ...fills.map((x, i) => [x, i]),
349
+ ...borders.map((x, i) => [x, i]),
350
+ ...xfs.map((x, i) => [x, i])
351
+ ]);
352
+
353
+ const add = (list, xml) => {
354
+ if (index.has(xml)) return index.get(xml);
355
+ list.push(xml);
356
+ index.set(xml, list.length - 1);
357
+ return list.length - 1;
358
+ };
359
+
360
+ function fontXml(font) {
361
+ if (!font) return null;
362
+ return '<font>' +
363
+ (font.bold ? '<b/>' : '') +
364
+ (font.italic ? '<i/>' : '') +
365
+ `<sz val="${font.size ?? 11}"/>` +
366
+ (font.color ? `<color rgb="${font.color}"/>` : '') +
367
+ `<name val="${escapeAttr(font.name ?? 'Calibri')}"/>` +
368
+ '</font>';
369
+ }
370
+
371
+ function fillXml(color) {
372
+ if (!color) return null;
373
+ return `<fill><patternFill patternType="solid"><fgColor rgb="${color}"/>` +
374
+ '<bgColor indexed="64"/></patternFill></fill>';
375
+ }
376
+
377
+ function borderXml(border) {
378
+ if (!border) return null;
379
+ const side = (name) => `<${name} style="${border.style}">` +
380
+ (border.color ? `<color rgb="${border.color}"/>` : '<color auto="1"/>') +
381
+ `</${name}>`;
382
+ return `<border>${side('left')}${side('right')}${side('top')}${side('bottom')}<diagonal/></border>`;
383
+ }
384
+
385
+ function alignmentXml(alignment) {
386
+ if (!alignment) return '';
387
+ const attrs = [];
388
+ if (alignment.horizontal && alignment.horizontal !== 'general') {
389
+ attrs.push(`horizontal="${alignment.horizontal}"`);
390
+ }
391
+ if (alignment.vertical && alignment.vertical !== 'bottom') {
392
+ attrs.push(`vertical="${alignment.vertical}"`);
393
+ }
394
+ if (alignment.wrapText) attrs.push('wrapText="1"');
395
+ if (Number(alignment.indent) > 0 &&
396
+ ['left', 'right', 'distributed'].includes(alignment.horizontal)) {
397
+ attrs.push(`indent="${Math.round(Number(alignment.indent))}"`);
398
+ }
399
+ return attrs.length ? `<alignment ${attrs.join(' ')}/>` : '';
400
+ }
401
+
402
+ /**
403
+ * @param {object|null} format from cellFormat, or { font: { bold } } and the like
404
+ * @param {number} [numFmtId=0] a built-in number format, such as 14 for a date
405
+ * @returns {number} the cell format's index
406
+ */
407
+ function xf(format, numFmtId = 0) {
408
+ if (!format && numFmtId === 0) return 0;
409
+
410
+ const font = fontXml(format?.font ? { name: 'Calibri', size: 11, ...format.font } : null);
411
+ const fill = fillXml(format?.fill);
412
+ const border = borderXml(format?.border);
413
+ const alignment = alignmentXml(format?.alignment);
414
+
415
+ const fontId = font ? add(fonts, font) : 0;
416
+ const fillId = fill ? add(fills, fill) : 0;
417
+ const borderId = border ? add(borders, border) : 0;
418
+
419
+ const applies = [
420
+ numFmtId ? ' applyNumberFormat="1"' : '',
421
+ fontId ? ' applyFont="1"' : '',
422
+ fillId ? ' applyFill="1"' : '',
423
+ borderId ? ' applyBorder="1"' : '',
424
+ alignment ? ' applyAlignment="1"' : ''
425
+ ].join('');
426
+
427
+ const xml = `<xf numFmtId="${numFmtId}" fontId="${fontId}" fillId="${fillId}" ` +
428
+ `borderId="${borderId}" xfId="0"${applies}` +
429
+ (alignment ? `>${alignment}</xf>` : '/>');
430
+
431
+ return add(xfs, xml);
432
+ }
433
+
434
+ function xml() {
435
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
436
+ '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
437
+ `<fonts count="${fonts.length}">${fonts.join('')}</fonts>` +
438
+ `<fills count="${fills.length}">${fills.join('')}</fills>` +
439
+ `<borders count="${borders.length}">${borders.join('')}</borders>` +
440
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
441
+ `<cellXfs count="${xfs.length}">${xfs.join('')}</cellXfs>` +
442
+ '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
443
+ '</styleSheet>';
444
+ }
445
+
446
+ return { xf, xml, get size() { return xfs.length; } };
447
+ }
448
+
449
+
450
+ function escapeAttr(text) {
451
+ return String(text)
452
+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '')
453
+ .replace(/&/g, '&amp;')
454
+ .replace(/</g, '&lt;')
455
+ .replace(/>/g, '&gt;')
456
+ .replace(/"/g, '&quot;');
457
+ }