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,138 @@
1
+ /**
2
+ * zip.js writes a ZIP archive, which is what an .xlsx file is.
3
+ *
4
+ * Only as much of the format as a spreadsheet needs (PKWARE APPNOTE 6.3):
5
+ * entries are STORED, not deflated, so there is no compressor to carry and the
6
+ * whole thing stays synchronous - the export it serves returns at once, the way
7
+ * the CSV download does. The cost is a larger file, and a report is text that
8
+ * already downloads in a blink.
9
+ *
10
+ * No ZIP64: four gigabytes of report would not fit in a browser string long
11
+ * before it reached this file. Timestamps are fixed at the format's epoch, so
12
+ * the same report always zips to the same bytes.
13
+ */
14
+
15
+
16
+ /** 1980-01-01 00:00 in MS-DOS date and time fields - the earliest ZIP can say */
17
+ const DOS_TIME = 0;
18
+ const DOS_DATE = (0 << 9) | (1 << 5) | 1;
19
+
20
+ /** general purpose bit 11: names are UTF-8 */
21
+ const UTF8_NAMES = 0x0800;
22
+
23
+ /** 2.0, the version that introduced folders - what every reader accepts */
24
+ const VERSION = 20;
25
+
26
+
27
+ /** the CRC-32 lookup table (the IEEE polynomial, reflected), built on first use */
28
+ let table = null;
29
+
30
+ function crcTable() {
31
+ if (table) return table;
32
+
33
+ table = new Uint32Array(256);
34
+ for (let n = 0; n < 256; n++) {
35
+ let c = n;
36
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;
37
+ table[n] = c >>> 0;
38
+ }
39
+
40
+ return table;
41
+ }
42
+
43
+
44
+ /**
45
+ * The CRC-32 of some bytes, as ZIP records it.
46
+ * @param {Uint8Array} bytes
47
+ * @returns {number} unsigned 32-bit
48
+ */
49
+ export function crc32(bytes) {
50
+ const t = crcTable();
51
+ let crc = 0xFFFFFFFF;
52
+
53
+ for (let i = 0; i < bytes.length; i++) crc = t[(crc ^ bytes[i]) & 0xFF] ^ (crc >>> 8);
54
+
55
+ return (crc ^ 0xFFFFFFFF) >>> 0;
56
+ }
57
+
58
+
59
+ /**
60
+ * Packs files into a ZIP archive.
61
+ *
62
+ * @param {{name: string, data: Uint8Array|string}[]} files in the order they
63
+ * go in; a string is written as UTF-8
64
+ * @returns {Uint8Array} the archive
65
+ */
66
+ export function zip(files) {
67
+ const encoder = new TextEncoder();
68
+
69
+ const entries = files.map(({ name, data }) => {
70
+ const bytes = typeof data === 'string' ? encoder.encode(data) : data;
71
+ return { name: encoder.encode(name), bytes, crc: crc32(bytes), offset: 0 };
72
+ });
73
+
74
+ const localSize = entries.reduce((n, e) => n + 30 + e.name.length + e.bytes.length, 0);
75
+ const centralSize = entries.reduce((n, e) => n + 46 + e.name.length, 0);
76
+
77
+ const out = new Uint8Array(localSize + centralSize + 22);
78
+ const view = new DataView(out.buffer);
79
+ let at = 0;
80
+
81
+ const u16 = (v) => { view.setUint16(at, v, true); at += 2; };
82
+ const u32 = (v) => { view.setUint32(at, v, true); at += 4; };
83
+ const put = (bytes) => { out.set(bytes, at); at += bytes.length; };
84
+
85
+ for (const e of entries) {
86
+ e.offset = at;
87
+
88
+ u32(0x04034B50); // local file header signature
89
+ u16(VERSION); // version needed to extract
90
+ u16(UTF8_NAMES); // general purpose flags
91
+ u16(0); // compression: stored
92
+ u16(DOS_TIME);
93
+ u16(DOS_DATE);
94
+ u32(e.crc);
95
+ u32(e.bytes.length); // compressed size
96
+ u32(e.bytes.length); // uncompressed size
97
+ u16(e.name.length);
98
+ u16(0); // extra field length
99
+ put(e.name);
100
+ put(e.bytes);
101
+ }
102
+
103
+ const centralStart = at;
104
+
105
+ for (const e of entries) {
106
+ u32(0x02014B50); // central directory header signature
107
+ u16(VERSION); // version made by
108
+ u16(VERSION); // version needed to extract
109
+ u16(UTF8_NAMES);
110
+ u16(0); // stored
111
+ u16(DOS_TIME);
112
+ u16(DOS_DATE);
113
+ u32(e.crc);
114
+ u32(e.bytes.length);
115
+ u32(e.bytes.length);
116
+ u16(e.name.length);
117
+ u16(0); // extra field length
118
+ u16(0); // comment length
119
+ u16(0); // disk number start
120
+ u16(0); // internal attributes
121
+ u32(0); // external attributes
122
+ u32(e.offset); // where the local header is
123
+ put(e.name);
124
+ }
125
+
126
+ const centralLength = at - centralStart;
127
+
128
+ u32(0x06054B50); // end of central directory signature
129
+ u16(0); // this disk
130
+ u16(0); // the disk the directory starts on
131
+ u16(entries.length); // entries on this disk
132
+ u16(entries.length); // entries in all
133
+ u32(centralLength); // size of the central directory
134
+ u32(centralStart); // where it starts
135
+ u16(0); // comment length
136
+
137
+ return out;
138
+ }
package/src/index.js CHANGED
@@ -26,6 +26,10 @@ export {
26
26
  toReportCSV,
27
27
  reportFilename,
28
28
  reportTables,
29
+ toXLSX,
30
+ toXLSXAsync,
31
+ reportImageSources,
32
+ XLSX_MIME,
29
33
  measureText,
30
34
  wrapLines,
31
35
  textHeight,
@@ -35,7 +39,7 @@ export {
35
39
  export { render } from './render/render.js';
36
40
 
37
41
  /**
38
- * The viewer: paging, zoom, search, print and CSV over a page list.
42
+ * The viewer: paging, zoom, search, print, CSV and Excel over a page list.
39
43
  *
40
44
  * It takes one empty element and builds the rest, the same way createDesigner
41
45
  * does. Link `report-studio/viewer.css` beside it - the report's own stylesheet
@@ -139,6 +139,14 @@ export function chrome({ title = 'Report Studio' } = {}) {
139
139
  <span class="format-note">Every text line and table row, in report order</span>
140
140
  </span>
141
141
  </label>
142
+
143
+ <label class="format">
144
+ <input type="radio" name="export-format" value="xlsx">
145
+ <span class="format-body">
146
+ <span class="format-name">Excel</span>
147
+ <span class="format-note">The report as it reads, plus a sheet per table</span>
148
+ </span>
149
+ </label>
142
150
  </div>
143
151
 
144
152
  <p class="modal-summary" data-role="export-summary" aria-live="polite"></p>
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * viewer.js turns a page list into a page-at-a-time viewer: navigation, zoom,
3
- * search, print and CSV.
3
+ * search, print, CSV and Excel.
4
4
  *
5
5
  * It takes one empty element and builds everything inside it - the chrome is
6
6
  * chrome.js and the report is render.js - so an application mounts it the same
@@ -14,6 +14,8 @@
14
14
 
15
15
  import { search, searchPages } from '../engine/search.js';
16
16
  import { toReportCSV, reportFilename } from '../engine/csv.js';
17
+ import { reportTables } from '../engine/rows.js';
18
+ import { toXLSX, toXLSXAsync, reportImageSources, XLSX_MIME } from '../engine/xlsx.js';
17
19
  import { openWindow, closeWithOpener } from '../shared/window.js';
18
20
  import { createDropdown } from '../shared/dropdown.js';
19
21
  import { render } from '../render/render.js';
@@ -286,6 +288,14 @@ export function createViewer({ mount, paginated, title } = {}) {
286
288
  ? `Downloads ${reportFilename(paginated, 'csv')}.`
287
289
  : 'This report has nothing to write out.',
288
290
  run: () => downloadCSV()
291
+ },
292
+ xlsx: {
293
+ /** a report with any text line or any table has a sheet to give */
294
+ available: () => FORMATS.csv.available() || reportTables(paginated.pages).length > 0,
295
+ summary: () => FORMATS.xlsx.available()
296
+ ? `Downloads ${reportFilename(paginated, 'xlsx')}.`
297
+ : 'This report has nothing to write out.',
298
+ run: () => downloadXLSX()
289
299
  }
290
300
  };
291
301
 
@@ -377,6 +387,36 @@ export function createViewer({ mount, paginated, title } = {}) {
377
387
  return true;
378
388
  }
379
389
 
390
+ /**
391
+ * The report as an Excel workbook: a sheet that reads like the report, and
392
+ * a sheet per table with typed, sortable cells.
393
+ *
394
+ * A report whose pictures come from URLs has to fetch them before they can
395
+ * be embedded, so its download starts a moment later; true still means a
396
+ * file is on its way. Should building with the fetched pictures fail, the
397
+ * workbook goes without them rather than not at all.
398
+ */
399
+ function downloadXLSX() {
400
+ if (!FORMATS.xlsx.available()) return false;
401
+
402
+ const save = (bytes) => {
403
+ if (bytes.length > 0) {
404
+ download(new Blob([bytes], { type: XLSX_MIME }), reportFilename(paginated, 'xlsx'));
405
+ }
406
+ };
407
+
408
+ if (reportImageSources(paginated.pages).length > 0) {
409
+ toXLSXAsync(paginated.pages).then(save, () => save(toXLSX(paginated.pages)));
410
+ return true;
411
+ }
412
+
413
+ const bytes = toXLSX(paginated.pages);
414
+ if (bytes.length === 0) return false;
415
+
416
+ save(bytes);
417
+ return true;
418
+ }
419
+
380
420
  function download(blob, filename) {
381
421
  const url = URL.createObjectURL(blob);
382
422
  const link = doc.createElement('a');
@@ -747,6 +787,7 @@ export function createViewer({ mount, paginated, title } = {}) {
747
787
  find: (q) => { ui.query.value = q; runSearch(); },
748
788
  print: printReport,
749
789
  downloadCSV,
790
+ downloadXLSX,
750
791
  openExport,
751
792
  closeExport,
752
793
  confirmExport,
@@ -24,14 +24,14 @@ import { createViewer } from '../preview/viewer.js';
24
24
 
25
25
  /** the viewer's methods, forwarded from the ref to whichever viewer is mounted */
26
26
  const VIEWER_METHODS = [
27
- 'show', 'next', 'prev', 'find', 'print', 'downloadCSV',
27
+ 'show', 'next', 'prev', 'find', 'print', 'downloadCSV', 'downloadXLSX',
28
28
  'openExport', 'closeExport', 'confirmExport',
29
29
  'setZoom', 'zoomIn', 'zoomOut', 'fitWidth'
30
30
  ];
31
31
 
32
32
 
33
33
  /**
34
- * The report viewer: paging, zoom, search, print and CSV.
34
+ * The report viewer: paging, zoom, search, print, CSV and Excel.
35
35
  *
36
36
  * Give it a layout and data, or pages already built with buildPages. New data
37
37
  * builds new pages and remounts the viewer inside the same element, keeping the
@@ -52,7 +52,7 @@ const VIEWER_METHODS = [
52
52
  * @param {string} [props.className]
53
53
  * @param {object} [props.style]
54
54
  * @param {object} ref receives the viewer's controls: show, next, prev, find,
55
- * print, downloadCSV, setZoom, zoomIn, zoomOut, fitWidth, and page, pageCount
55
+ * print, downloadCSV, downloadXLSX, setZoom, zoomIn, zoomOut, fitWidth, and page, pageCount
56
56
  * and zoom
57
57
  */
58
58
  export const ReportViewer = forwardRef(function ReportViewer(
package/types/index.d.ts CHANGED
@@ -101,6 +101,54 @@ export function toCSV(pages: Page[], options?: CSVOptions): string;
101
101
  /** the whole report as CSV, one row per line in the order it is read */
102
102
  export function toReportCSV(pages: Page[], options?: ReportCSVOptions): string;
103
103
 
104
+ export interface XLSXOptions {
105
+ /** include the "Report" sheet, the report as it reads; default true */
106
+ report?: boolean;
107
+ /** include one sheet per table; default true */
108
+ tables?: boolean;
109
+ /**
110
+ * carry the report's look: fonts, colours, alignment, table grid, row
111
+ * heights and column widths, text placed where it sits on the page, and
112
+ * pictures, lines and boxes drawn. False writes plain data with bold
113
+ * headers. Default true
114
+ */
115
+ styled?: boolean;
116
+ /**
117
+ * the bytes of pictures given as URLs, keyed by their src; `data:` URIs
118
+ * need none. A picture with no bytes is left out. toXLSXAsync fills this in
119
+ */
120
+ images?: Record<string, Uint8Array | ArrayBuffer> | Map<string, Uint8Array | ArrayBuffer>;
121
+ /** default `'Report'` */
122
+ reportSheetName?: string;
123
+ /** prepend the group key on a grouped table's sheet; default true */
124
+ groupColumn?: boolean;
125
+ /** default `'Group'` */
126
+ groupLabel?: string;
127
+ }
128
+
129
+ /**
130
+ * the report as an .xlsx workbook; empty when the report writes nothing.
131
+ * Throws a RangeError when a sheet would pass Excel's row or column limit
132
+ */
133
+ export function toXLSX(pages: Page[], options?: XLSXOptions): Uint8Array;
134
+
135
+ export interface XLSXAsyncOptions extends XLSXOptions {
136
+ /** what fetches a picture's URL; the global fetch by default */
137
+ fetch?: (url: string) => Promise<{ ok: boolean; arrayBuffer(): Promise<ArrayBuffer> }>;
138
+ }
139
+
140
+ /**
141
+ * toXLSX with the report's URL pictures fetched first; a picture that cannot
142
+ * be fetched is left out rather than failing the workbook
143
+ */
144
+ export function toXLSXAsync(pages: Page[], options?: XLSXAsyncOptions): Promise<Uint8Array>;
145
+
146
+ /** the picture URLs a report shows that need fetching to be embedded */
147
+ export function reportImageSources(pages: Page[]): string[];
148
+
149
+ /** the MIME type to give a Blob of toXLSX's bytes */
150
+ export const XLSX_MIME: string;
151
+
104
152
  /** a download filename from the report's name */
105
153
  export function reportFilename(paginated: { name?: string }, extension?: string): string;
106
154
 
@@ -155,6 +203,11 @@ export interface ViewerHandle {
155
203
  print(): void;
156
204
  /** false when the report has nothing to write */
157
205
  downloadCSV(): boolean;
206
+ /**
207
+ * false when the report has nothing to write. A report with pictures
208
+ * from URLs fetches them first, so its download starts a moment later
209
+ */
210
+ downloadXLSX(): boolean;
158
211
  openExport(): void;
159
212
  closeExport(): void;
160
213
  confirmExport(): void;