report-studio 1.3.0 → 1.3.1

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.
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * chrome.js is the viewer's own markup: the toolbar, the floating pager and the
3
- * export dialog.
3
+ * export menu.
4
4
  *
5
5
  * It lives here rather than in a page because the viewer is something an
6
6
  * application mounts, and an API whose first instruction is "copy these 144
@@ -13,6 +13,42 @@
13
13
  */
14
14
 
15
15
 
16
+ /**
17
+ * The toolbar's and the pager's glyphs, drawn rather than typed: a character
18
+ * such as ‹ sits on the font's baseline and varies with it, where these
19
+ * sit on one 16px grid and take their colour from the button.
20
+ */
21
+ const glyph = (body, size = 16) => `<svg viewBox="0 0 16 16" width="${size}" height="${size}"
22
+ fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
23
+ stroke-linejoin="round" aria-hidden="true" focusable="false">${body}</svg>`;
24
+
25
+ const GLYPHS = {
26
+ up: glyph('<path d="M4.5 10 8 6.5l3.5 3.5"/>', 14),
27
+ down: glyph('<path d="M4.5 6 8 9.5 11.5 6"/>', 14),
28
+ left: glyph('<path d="M9.5 4.5 6 8l3.5 3.5"/>'),
29
+ right: glyph('<path d="M6.5 4.5 10 8l-3.5 3.5"/>'),
30
+ minus: glyph('<path d="M4 8h8"/>'),
31
+ plus: glyph('<path d="M8 4v8M4 8h8"/>'),
32
+ print: glyph('<path d="M4.5 6V2.75h7V6"/><rect x="2.25" y="6" width="11.5" height="5.5" rx="1"/>'
33
+ + '<path d="M4.5 9.5h7v3.75h-7z"/>'),
34
+ caret: glyph('<path d="M5 6.5 8 9.5l3-3"/>', 14),
35
+ /** a sheet with its corner turned - a file, which is what each format makes */
36
+ file: glyph('<path d="M4 2.25h5.25L12 5v8.75H4z"/><path d="M9 2.25V5.25h3"/>')
37
+ };
38
+
39
+
40
+ /**
41
+ * The formats the export menu offers, in the order it lists them. The viewer
42
+ * fills in each one's note - how many pages, which file - and says which are
43
+ * available; this is only what they are called.
44
+ */
45
+ const EXPORT_FORMATS = [
46
+ { value: 'pdf', name: 'PDF', keys: 'Ctrl P' },
47
+ { value: 'csv', name: 'CSV', keys: '' },
48
+ { value: 'xlsx', name: 'Excel', keys: '' }
49
+ ];
50
+
51
+
16
52
  /**
17
53
  * @param {object} [options]
18
54
  * @param {string} [options.title] what the brand corner reads
@@ -44,15 +80,15 @@ export function chrome({ title = 'Report Studio' } = {}) {
44
80
  aria-label="Search the report" spellcheck="false">
45
81
  <span class="hits" data-role="hits" data-state="idle" aria-live="polite"></span>
46
82
  <button type="button" data-role="hit-prev" title="Previous match (shift+enter)"
47
- aria-label="Previous match">&#8593;</button>
83
+ aria-label="Previous match">${GLYPHS.up}</button>
48
84
  <button type="button" data-role="hit-next" title="Next match (enter)"
49
- aria-label="Next match">&#8595;</button>
85
+ aria-label="Next match">${GLYPHS.down}</button>
50
86
  </div>
51
87
  </div>
52
88
 
53
89
  <div class="toolbar-group toolbar-zoom">
54
90
  <button type="button" data-role="zoom-out" title="Zoom out (ctrl+-)"
55
- aria-label="Zoom out">&#8722;</button>
91
+ aria-label="Zoom out">${GLYPHS.minus}</button>
56
92
 
57
93
  <!--
58
94
  A listbox rather than a <select>: option items are drawn by
@@ -80,15 +116,39 @@ export function chrome({ title = 'Report Studio' } = {}) {
80
116
  </div>
81
117
 
82
118
  <button type="button" data-role="zoom-in" title="Zoom in (ctrl++)"
83
- aria-label="Zoom in">&#43;</button>
119
+ aria-label="Zoom in">${GLYPHS.plus}</button>
84
120
  </div>
85
121
  </div>
86
122
 
87
123
  <div class="toolbar-group toolbar-save">
88
124
  <button type="button" data-role="print" title="Print or save as PDF (ctrl+P)">
89
- Print</button>
90
- <button type="button" data-role="export" title="Export the report (ctrl+X)">
91
- Export&#8230;</button>
125
+ ${GLYPHS.print}<span>Print</span></button>
126
+ <!--
127
+ A menu rather than a dialog: choosing a format is the whole
128
+ of the decision, so it is made where the button is, in one
129
+ click - as a design tool's export menu does it. Each item
130
+ acts at once; there is no confirm step to come back to.
131
+ -->
132
+ <div class="export-menu">
133
+ <button type="button" data-role="export" title="Export the report (ctrl+X)"
134
+ aria-haspopup="menu" aria-expanded="false">
135
+ <span>Export</span>${GLYPHS.caret}</button>
136
+
137
+ <div class="export-list" data-role="export-menu" role="menu"
138
+ aria-label="Export as" hidden>
139
+ <p class="export-heading" aria-hidden="true">Export as</p>
140
+ ${EXPORT_FORMATS.map(f => `
141
+ <button type="button" class="format" role="menuitem" tabindex="-1"
142
+ data-format="${f.value}">
143
+ <span class="format-icon">${GLYPHS.file}</span>
144
+ <span class="format-body">
145
+ <span class="format-name">${f.name}</span>
146
+ <span class="format-note" data-role="export-note-${f.value}"></span>
147
+ </span>
148
+ ${f.keys ? `<kbd class="format-keys">${f.keys}</kbd>` : ''}
149
+ </button>`).join('')}
150
+ </div>
151
+ </div>
92
152
  </div>
93
153
  </div>
94
154
  </header>
@@ -98,7 +158,7 @@ export function chrome({ title = 'Report Studio' } = {}) {
98
158
  <!-- paging floats over the report rather than taking a strip of it -->
99
159
  <div class="pager" data-role="pager" role="toolbar" aria-label="Page navigation">
100
160
  <button type="button" data-role="prev" title="Previous page (left arrow)"
101
- aria-label="Previous page">&#8249;</button>
161
+ aria-label="Previous page">${GLYPHS.left}</button>
102
162
 
103
163
  <label class="page-of">
104
164
  <input type="number" data-role="current" min="1" value="1" aria-label="Current page">
@@ -107,55 +167,7 @@ export function chrome({ title = 'Report Studio' } = {}) {
107
167
  </label>
108
168
 
109
169
  <button type="button" data-role="next" title="Next page (right arrow)"
110
- aria-label="Next page">&#8250;</button>
111
- </div>
112
-
113
-
114
-
115
- <!--
116
- Hand-written rather than a <dialog>: the element is still unimplemented
117
- in the environment the specs run in, and a stubbed showModal would test
118
- the stub instead of the behaviour.
119
- -->
120
- <div class="modal" data-role="export-modal" hidden>
121
- <div class="modal-backdrop" data-role="export-backdrop"></div>
122
-
123
- <div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="export-title">
124
- <h2 id="export-title">Export report</h2>
125
-
126
- <div class="modal-formats" role="radiogroup" aria-labelledby="export-title">
127
- <label class="format">
128
- <input type="radio" name="export-format" value="pdf" checked>
129
- <span class="format-body">
130
- <span class="format-name">PDF</span>
131
- <span class="format-note">Opens the print dialog - choose "Save as PDF"</span>
132
- </span>
133
- </label>
134
-
135
- <label class="format">
136
- <input type="radio" name="export-format" value="csv">
137
- <span class="format-body">
138
- <span class="format-name">CSV</span>
139
- <span class="format-note">Every text line and table row, in report order</span>
140
- </span>
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>
150
- </div>
151
-
152
- <p class="modal-summary" data-role="export-summary" aria-live="polite"></p>
153
-
154
- <div class="modal-actions">
155
- <button type="button" data-role="export-cancel">Cancel</button>
156
- <button type="button" class="is-primary" data-role="export-confirm">Export</button>
157
- </div>
158
- </div>
170
+ aria-label="Next page">${GLYPHS.right}</button>
159
171
  </div>
160
172
  `;
161
173
  }
@@ -146,8 +146,6 @@ export function createViewer({ mount, paginated, title } = {}) {
146
146
  /** the report itself is what scrolls and what the highlighting sits in */
147
147
  const mountEl = viewport;
148
148
 
149
- const modal = root.querySelector('[data-role="export-modal"]');
150
-
151
149
  /**
152
150
  * One search root now that the viewer owns all of its chrome. A control is
153
151
  * still found by its role rather than by which container holds it, so
@@ -173,22 +171,15 @@ export function createViewer({ mount, paginated, title } = {}) {
173
171
  hitNext: find('hit-next')
174
172
  };
175
173
 
176
- const dialog = modal ? {
177
- root: modal,
178
- card: modal.querySelector('.modal-card'),
179
- backdrop: modal.querySelector('[data-role="export-backdrop"]'),
180
- summary: modal.querySelector('[data-role="export-summary"]'),
181
- cancel: modal.querySelector('[data-role="export-cancel"]'),
182
- confirm: modal.querySelector('[data-role="export-confirm"]'),
183
- formats: [...modal.querySelectorAll('input[name="export-format"]')]
184
- } : null;
174
+ /** the export menu: the list under the Export button, and its formats */
175
+ const menu = find('export-menu');
176
+ const menuItems = menu ? [...menu.querySelectorAll('[data-format]')] : [];
185
177
 
186
178
  let index = 0; // zero-based page index
187
179
  let matches = []; // engine search results
188
180
  let hitIndex = -1; // which match is focused
189
181
  let zoom = 1; // the scale actually applied
190
182
  let fitWidth = false; // recompute zoom from the viewport on resize
191
- let returnFocusTo = null; // what had focus before the dialog opened
192
183
 
193
184
  const afterPrintSupported = typeof view.onafterprint !== 'undefined';
194
185
 
@@ -272,8 +263,8 @@ export function createViewer({ mount, paginated, title } = {}) {
272
263
  /* ---------------- exporting ---------------- */
273
264
 
274
265
  /**
275
- * One entry per offered format. Adding a third means a line here and a radio
276
- * in the dialog; nothing else in the flow needs to know about it.
266
+ * One entry per offered format. Adding another means a line here and an
267
+ * entry in chrome.js's export list; nothing else in the flow needs to know.
277
268
  */
278
269
  const FORMATS = {
279
270
  pdf: {
@@ -431,83 +422,114 @@ export function createViewer({ mount, paginated, title } = {}) {
431
422
  setTimeout(() => URL.revokeObjectURL(url), 0);
432
423
  }
433
424
 
434
- /* ---------------- the export dialog ---------------- */
435
-
436
- function chosenFormat() {
437
- return dialog?.formats.find(input => input.checked)?.value ?? 'pdf';
438
- }
425
+ /* ---------------- the export menu ---------------- */
439
426
 
440
- /** the note under the radios, plus whether Export can proceed at all */
441
- function refreshDialog() {
442
- if (!dialog) return;
427
+ /**
428
+ * Each item's note, and whether it can be chosen at all - worked out as
429
+ * the menu opens, since a report with nothing tabular has no CSV to give.
430
+ * An item that cannot be chosen says why, in the note it would otherwise
431
+ * use for the file it makes.
432
+ */
433
+ function refreshMenu() {
434
+ for (const item of menuItems) {
435
+ const format = FORMATS[item.dataset.format];
436
+ const available = Boolean(format?.available());
443
437
 
444
- for (const input of dialog.formats) {
445
- const format = FORMATS[input.value];
446
- input.disabled = format ? !format.available() : true;
447
- input.closest('.format')?.classList.toggle('is-unavailable', input.disabled);
448
- }
438
+ item.disabled = !available;
439
+ item.setAttribute('aria-disabled', String(!available));
440
+ item.classList.toggle('is-unavailable', !available);
449
441
 
450
- /** never leave a disabled option selected */
451
- const current = dialog.formats.find(i => i.checked);
452
- if (current?.disabled) {
453
- const fallback = dialog.formats.find(i => !i.disabled);
454
- if (fallback) fallback.checked = true;
442
+ const note = item.querySelector('.format-note');
443
+ if (note) note.textContent = format ? format.summary() : '';
455
444
  }
456
-
457
- const format = FORMATS[chosenFormat()];
458
- dialog.summary.textContent = format ? format.summary() : '';
459
- dialog.confirm.disabled = !format || !format.available();
460
445
  }
461
446
 
447
+ const enabledItems = () => menuItems.filter(item => !item.disabled);
448
+
462
449
  function openExport() {
463
- if (!dialog) return;
450
+ if (!menu || !menu.hidden) return;
464
451
 
465
- returnFocusTo = doc.activeElement;
466
- dialog.root.hidden = false;
467
- refreshDialog();
452
+ refreshMenu();
453
+ menu.hidden = false;
454
+ ui.exportOpen.setAttribute('aria-expanded', 'true');
468
455
 
469
- const focusOn = dialog.formats.find(i => i.checked && !i.disabled)
470
- ?? dialog.formats.find(i => !i.disabled)
471
- ?? dialog.cancel;
472
- focusOn.focus();
456
+ enabledItems()[0]?.focus();
457
+
458
+ /**
459
+ * On the next tick, or the press that opened the menu would reach this
460
+ * listener on its way up and close it again.
461
+ */
462
+ view.setTimeout(() => {
463
+ if (!menu.hidden) doc.addEventListener('pointerdown', onOutside, true);
464
+ }, 0);
473
465
  }
474
466
 
475
- function closeExport() {
476
- if (!dialog || dialog.root.hidden) return;
467
+ /**
468
+ * @param {object} [options]
469
+ * @param {boolean} [options.refocus] put the focus back on the Export
470
+ * button - not when the menu closed because something else was clicked
471
+ */
472
+ function closeExport({ refocus = true } = {}) {
473
+ if (!menu || menu.hidden) return;
477
474
 
478
- dialog.root.hidden = true;
479
- returnFocusTo?.focus?.();
480
- returnFocusTo = null;
475
+ menu.hidden = true;
476
+ ui.exportOpen.setAttribute('aria-expanded', 'false');
477
+ doc.removeEventListener('pointerdown', onOutside, true);
478
+
479
+ if (refocus && menu.contains(doc.activeElement)) ui.exportOpen.focus();
480
+ else if (refocus && doc.activeElement === doc.body) ui.exportOpen.focus();
481
481
  }
482
482
 
483
- function confirmExport() {
484
- const format = FORMATS[chosenFormat()];
483
+ /**
484
+ * Exports in a format: the one asked for, or the item the keys are on, or
485
+ * PDF - the first in the list and the one every report can give.
486
+ *
487
+ * @param {'pdf'|'csv'|'xlsx'} [asked]
488
+ */
489
+ function confirmExport(asked) {
490
+ const focused = menuItems.find(item => item === doc.activeElement);
491
+ const value = typeof asked === 'string' ? asked : focused?.dataset.format ?? 'pdf';
492
+
493
+ const format = FORMATS[value];
485
494
  if (!format?.available()) return;
486
495
 
487
496
  /**
488
- * Close first. The print dialog is modal and blocking, so leaving our
489
- * own overlay up would put it in the printed page and in the way.
497
+ * Close first. The print dialog is modal and blocking, so leaving the
498
+ * menu open would put it in the printed page and in the way.
490
499
  */
491
500
  closeExport();
492
501
  format.run();
493
502
  }
494
503
 
495
- /** keeps Tab inside the card while the dialog is up */
496
- function trapFocus(event) {
497
- const focusable = [...dialog.card.querySelectorAll('button, input')]
498
- .filter(node => !node.disabled);
499
- if (!focusable.length) return;
500
-
501
- const first = focusable[0];
502
- const last = focusable[focusable.length - 1];
504
+ function onOutside(event) {
505
+ if (menu.contains(event.target) || ui.exportOpen.contains(event.target)) return;
506
+ closeExport({ refocus: false });
507
+ }
503
508
 
504
- if (event.shiftKey && doc.activeElement === first) {
505
- event.preventDefault();
506
- last.focus();
507
- } else if (!event.shiftKey && doc.activeElement === last) {
508
- event.preventDefault();
509
- first.focus();
510
- }
509
+ /**
510
+ * The menu's keys: up and down through what can be chosen, Home and End,
511
+ * Escape back to the button, Tab on past it. Enter and Space are the
512
+ * items' own, being buttons. Every key it handles stops here, so the
513
+ * report does not page behind an open menu.
514
+ */
515
+ function onMenuKey(event) {
516
+ const items = enabledItems();
517
+ const at = items.indexOf(doc.activeElement);
518
+
519
+ const handled = {
520
+ ArrowDown: () => items[(at + 1) % items.length]?.focus(),
521
+ ArrowUp: () => items[(at - 1 + items.length) % items.length]?.focus(),
522
+ Home: () => items[0]?.focus(),
523
+ End: () => items.at(-1)?.focus(),
524
+ Escape: () => closeExport(),
525
+ Tab: () => closeExport({ refocus: false })
526
+ }[event.key];
527
+
528
+ if (!handled) return;
529
+
530
+ if (event.key !== 'Tab') event.preventDefault();
531
+ event.stopPropagation();
532
+ handled();
511
533
  }
512
534
 
513
535
  /* ---------------- search ---------------- */
@@ -574,6 +596,13 @@ export function createViewer({ mount, paginated, title } = {}) {
574
596
  parent.replaceChild(doc.createTextNode(mark.textContent), mark);
575
597
  parent.normalize();
576
598
  }
599
+
600
+ /** and the runs that held a cell's marks together go back to plain text */
601
+ for (const run of mountEl.querySelectorAll('span.hit-run')) {
602
+ const parent = run.parentNode;
603
+ parent.replaceChild(doc.createTextNode(run.textContent), run);
604
+ parent.normalize();
605
+ }
577
606
  }
578
607
 
579
608
  /** marks every occurrence on the page currently on screen */
@@ -620,7 +649,24 @@ export function createViewer({ mount, paginated, title } = {}) {
620
649
 
621
650
  if (from < text.length) fragment.appendChild(doc.createTextNode(text.slice(from)));
622
651
 
623
- node.parentNode.replaceChild(fragment, node);
652
+ /**
653
+ * A table cell lays its text out as a flex column, to centre it
654
+ * whatever it wraps to - and every child of a flex box is a block of
655
+ * its own. Split into text, mark, text, a cell reading "Northgate
656
+ * Stores" stacked "North" over "gate Stores" on lines the row had no
657
+ * room for. Kept together in one inline run, it reads as it did.
658
+ */
659
+ const parent = node.parentNode;
660
+
661
+ if (parent.classList?.contains('cell')) {
662
+ const run = doc.createElement('span');
663
+ run.className = 'hit-run';
664
+ run.appendChild(fragment);
665
+ parent.replaceChild(run, node);
666
+ return;
667
+ }
668
+
669
+ parent.replaceChild(fragment, node);
624
670
  }
625
671
 
626
672
  /** the focused hit gets a stronger colour and is scrolled into view */
@@ -650,21 +696,26 @@ export function createViewer({ mount, paginated, title } = {}) {
650
696
  });
651
697
 
652
698
  ui.print?.addEventListener('click', printReport);
653
- ui.exportOpen.addEventListener('click', openExport);
699
+ ui.exportOpen.addEventListener('click', () => {
700
+ if (menu && !menu.hidden) closeExport();
701
+ else openExport();
702
+ });
654
703
 
655
- if (dialog) {
656
- dialog.cancel.addEventListener('click', closeExport);
657
- dialog.backdrop.addEventListener('click', closeExport);
658
- dialog.confirm.addEventListener('click', confirmExport);
704
+ /** the arrows open the menu from its button, as they would a select */
705
+ ui.exportOpen.addEventListener('keydown', (event) => {
706
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
659
707
 
660
- for (const input of dialog.formats) {
661
- input.addEventListener('change', refreshDialog);
662
- }
708
+ event.preventDefault();
709
+ event.stopPropagation();
710
+ openExport();
711
+ });
663
712
 
664
- dialog.root.addEventListener('keydown', (event) => {
665
- if (event.key === 'Tab') trapFocus(event);
666
- if (event.key === 'Enter') { event.preventDefault(); confirmExport(); }
667
- });
713
+ if (menu) {
714
+ menu.addEventListener('keydown', onMenuKey);
715
+
716
+ for (const item of menuItems) {
717
+ item.addEventListener('click', () => confirmExport(item.dataset.format));
718
+ }
668
719
  }
669
720
 
670
721
  ui.zoomIn.addEventListener('click', () => stepZoom(1));
@@ -696,8 +747,8 @@ export function createViewer({ mount, paginated, title } = {}) {
696
747
 
697
748
  /** paging keys, as long as the user is not typing in the search box */
698
749
  const onKeyDown = (event) => {
699
- /** while the dialog is up it owns the keyboard, bar Escape */
700
- if (dialog && !dialog.root.hidden) {
750
+ /** while the export menu is open it owns the keyboard, bar Escape */
751
+ if (menu && !menu.hidden) {
701
752
  if (event.key === 'Escape') { event.preventDefault(); closeExport(); }
702
753
  return;
703
754
  }
@@ -732,7 +783,7 @@ export function createViewer({ mount, paginated, title } = {}) {
732
783
  */
733
784
  if (event.target === ui.query || event.target === ui.current) return;
734
785
 
735
- /** ctrl+X opens the export; ctrl+S too, since the browser's save is no use here */
786
+ /** ctrl+X opens the export menu; ctrl+S too, since the browser's save is no use here */
736
787
  if ((event.ctrlKey || event.metaKey) && ['x', 's'].includes(event.key.toLowerCase())) {
737
788
  event.preventDefault();
738
789
  openExport();
@@ -766,6 +817,7 @@ export function createViewer({ mount, paginated, title } = {}) {
766
817
  */
767
818
  function destroy() {
768
819
  ui.zoom.destroy();
820
+ doc.removeEventListener('pointerdown', onOutside, true);
769
821
  doc.removeEventListener('keydown', onKeyDown);
770
822
  view.removeEventListener('resize', onResize);
771
823
  view.removeEventListener('afterprint', restoreAfterPrint);
@@ -792,7 +844,7 @@ export function createViewer({ mount, paginated, title } = {}) {
792
844
  closeExport,
793
845
  confirmExport,
794
846
  destroy,
795
- get exportOpen() { return dialog ? !dialog.root.hidden : false; },
847
+ get exportOpen() { return menu ? !menu.hidden : false; },
796
848
  setZoom,
797
849
  zoomIn: () => stepZoom(1),
798
850
  zoomOut: () => stepZoom(-1),