report-studio 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +238 -4
  3. package/dist/designer.js +3209 -0
  4. package/dist/index.js +2 -4
  5. package/dist/viewer-D-c0lKzQ.js +1576 -0
  6. package/package.json +66 -33
  7. package/src/asset/images/icon.png +0 -0
  8. package/src/asset/images/logo.png +0 -0
  9. package/src/cli/index.js +282 -0
  10. package/src/cli/serve.js +135 -0
  11. package/src/designer/blank.js +53 -0
  12. package/src/designer/canvas.js +518 -0
  13. package/src/designer/designer.js +1900 -0
  14. package/src/designer/dialog.js +708 -0
  15. package/src/designer/fields.js +584 -0
  16. package/src/designer/geometry.js +154 -0
  17. package/src/designer/guides.js +370 -0
  18. package/src/designer/history.js +113 -0
  19. package/src/designer/icons.js +118 -0
  20. package/src/designer/index.html +28 -0
  21. package/src/designer/main.js +39 -0
  22. package/src/designer/menu.js +126 -0
  23. package/src/designer/panel.js +478 -0
  24. package/src/designer/preview.js +95 -0
  25. package/src/designer/rulers.js +231 -0
  26. package/src/designer/sample-data.js +240 -0
  27. package/src/designer/select.js +699 -0
  28. package/src/designer/structure.js +604 -0
  29. package/src/designer/styles.css +1616 -0
  30. package/src/designer/toast.js +62 -0
  31. package/src/designer/tokens.js +284 -0
  32. package/src/engine/csv.js +315 -0
  33. package/src/engine/group.js +304 -0
  34. package/src/engine/index.js +34 -0
  35. package/src/engine/measure.js +390 -0
  36. package/src/engine/paginate.js +861 -0
  37. package/src/engine/regions.js +175 -0
  38. package/src/engine/resolve.js +171 -0
  39. package/src/engine/search.js +129 -0
  40. package/src/engine/text-metrics.js +206 -0
  41. package/src/engine/validate.js +328 -0
  42. package/src/index.html +79 -0
  43. package/src/index.js +50 -0
  44. package/src/preview/chrome.css +505 -0
  45. package/src/preview/chrome.js +147 -0
  46. package/src/preview/index.html +28 -0
  47. package/src/preview/main.js +66 -0
  48. package/src/preview/styles.css +16 -0
  49. package/src/preview/viewer.js +745 -0
  50. package/src/render/items.js +425 -0
  51. package/src/render/render.js +98 -0
  52. package/src/render/report.css +202 -0
  53. package/src/server/routes.js +331 -0
  54. package/src/shared/brand.css +29 -0
  55. package/src/shared/dropdown.css +136 -0
  56. package/src/shared/dropdown.js +166 -0
  57. package/src/shared/modal.css +125 -0
  58. package/src/shared/prefix.js +13 -0
  59. package/src/shared/store.js +145 -0
  60. package/src/shared/theme.css +72 -0
  61. package/src/shared/window.js +138 -0
  62. package/src/vite/index.js +53 -0
  63. package/dist/react.js +0 -4
@@ -0,0 +1,745 @@
1
+ /**
2
+ * viewer.js turns a page list into a page-at-a-time viewer: navigation, zoom,
3
+ * search, print and CSV.
4
+ *
5
+ * It takes one empty element and builds everything inside it - the chrome is
6
+ * chrome.js and the report is render.js - so an application mounts it the same
7
+ * way it mounts the designer, with a div and nothing else.
8
+ *
9
+ * All it knows about the report is the page list, which it hands to the
10
+ * engine's search. That is the seam in spec 2.2: a viewer for another framework
11
+ * reuses the same search, the same CSV and the same rendering, and replaces
12
+ * only the event handlers in this file.
13
+ */
14
+
15
+ import { search, searchPages } from '../engine/search.js';
16
+ import { toReportCSV, reportFilename } from '../engine/csv.js';
17
+ import { openWindow, closeWithOpener } from '../shared/window.js';
18
+ import { createDropdown } from '../shared/dropdown.js';
19
+ import { render } from '../render/render.js';
20
+ import { chrome } from './chrome.js';
21
+
22
+
23
+ /**
24
+ * The zoom levels the -/+ buttons step through, matching the menu beside them.
25
+ *
26
+ * Exported because the designer steps through the same ones. A report zoomed to
27
+ * 125% while it is being arranged and to 130% while it is being read would be
28
+ * two tools rather than two views of one.
29
+ */
30
+ export const ZOOM_STEPS = [0.5, 0.75, 1, 1.25, 1.5, 2, 3];
31
+
32
+ export const MIN_ZOOM = ZOOM_STEPS[0];
33
+ export const MAX_ZOOM = ZOOM_STEPS[ZOOM_STEPS.length - 1];
34
+
35
+
36
+ /**
37
+ * Mounts the viewer.
38
+ *
39
+ * @param {object} options
40
+ * @param {Element|string} options.mount the element to take over, or a selector
41
+ * @param {object} options.paginated the buildPages result
42
+ * @param {string} [options.title] what the brand corner reads
43
+ * @returns {object} a handle: paging, zoom, search, print, export and destroy
44
+ */
45
+ /**
46
+ * Opens a report in a window of its own.
47
+ *
48
+ * The same viewer, mounted in a window this opens rather than in an element the
49
+ * host supplies - for an application that would rather the report were beside
50
+ * it than inside it. The host's stylesheets are carried across, so it looks the
51
+ * same either way.
52
+ *
53
+ * Call it from a click or a keystroke: a browser blocks a window opened from
54
+ * anything else, and a blocked one comes back as null rather than as a throw,
55
+ * so the caller can fall back to mounting in the page.
56
+ *
57
+ * @param {object} options what createViewer takes, less `mount`
58
+ * @param {object} options.paginated the buildPages result
59
+ * @param {string} [options.title] the window's title and the brand corner
60
+ * @param {number} [options.width]
61
+ * @param {number} [options.height]
62
+ * @param {string} [options.features] passed to window.open as given
63
+ * @returns {object|null} the viewer handle, with `window`; null if blocked
64
+ */
65
+ export function openViewerWindow({
66
+ paginated, title, width, height, features, ...rest
67
+ } = {}) {
68
+ const opened = openWindow({
69
+ title: title ?? 'Report', width, height, features
70
+ });
71
+
72
+ if (!opened) return null;
73
+
74
+ const viewer = createViewer({
75
+ ...rest, mount: opened.mount, paginated, title
76
+ });
77
+
78
+ /** the report was passed in memory, so the window outliving its opener shows nothing */
79
+ const unwatch = closeWithOpener(globalThis, opened.window, viewer.destroy);
80
+
81
+ return {
82
+ ...viewer,
83
+ window: opened.window,
84
+
85
+ destroy() {
86
+ unwatch();
87
+ viewer.destroy();
88
+ opened.close();
89
+ }
90
+ };
91
+ }
92
+
93
+
94
+ export function createViewer({ mount, paginated, title } = {}) {
95
+ const root = typeof mount === 'string' ? document.querySelector(mount) : mount;
96
+
97
+ if (!root) {
98
+ throw new Error(
99
+ `createViewer: no element for mount ${JSON.stringify(mount)}. ` +
100
+ `Add <div id="report"></div> to the page first.`
101
+ );
102
+ }
103
+
104
+ /**
105
+ * The document the viewer is mounted in, which is not always this one: a
106
+ * report opened in its own window lives in that window's document, and a
107
+ * listener - or a print stylesheet - left on the opener's would never reach
108
+ * the report it belongs to.
109
+ */
110
+ const doc = root.ownerDocument;
111
+
112
+ /**
113
+ * And the window it belongs to, which is the same point one step out.
114
+ *
115
+ * `window` in this module is whichever page loaded the script - the host's
116
+ * tab. A report opened in a window of its own is mounted from that tab, so
117
+ * every bare `window` here reached back into it: print() printed the
118
+ * application behind the report instead of the report, the print dialog
119
+ * appeared over the wrong window, and afterprint fired somewhere the
120
+ * highlights were not.
121
+ *
122
+ * A viewer mounted in the page resolves this to the same `window` it always
123
+ * was, so nothing changes there.
124
+ */
125
+ const view = doc.defaultView ?? globalThis;
126
+
127
+ if (!paginated?.pages) {
128
+ throw new Error(
129
+ 'createViewer: paginated must be a buildPages(layout, data) result.'
130
+ );
131
+ }
132
+
133
+ root.classList.add('report-viewer');
134
+ root.innerHTML = chrome({ title });
135
+
136
+ const viewport = root.querySelector('[data-role="viewport"]');
137
+ viewport.innerHTML = render(paginated);
138
+
139
+ const pages = [...viewport.querySelectorAll('.page')];
140
+ const total = pages.length;
141
+
142
+ const stack = viewport.querySelector('#main-page');
143
+
144
+ /** the report itself is what scrolls and what the highlighting sits in */
145
+ const mountEl = viewport;
146
+
147
+ const modal = root.querySelector('[data-role="export-modal"]');
148
+
149
+ /**
150
+ * One search root now that the viewer owns all of its chrome. A control is
151
+ * still found by its role rather than by which container holds it, so
152
+ * moving one between the toolbar and the pager stays a change to chrome.js
153
+ * alone.
154
+ */
155
+ const find = (role) => root.querySelector(`[data-role="${role}"]`);
156
+
157
+ const ui = {
158
+ prev: find('prev'),
159
+ next: find('next'),
160
+ current: find('current'),
161
+ total: find('total'),
162
+ /** a listbox with the two bits of the <select> API this file used */
163
+ zoom: createDropdown(find('zoom-dropdown')),
164
+ zoomIn: find('zoom-in'),
165
+ zoomOut: find('zoom-out'),
166
+ print: find('print'),
167
+ exportOpen: find('export'),
168
+ query: find('query'),
169
+ hits: find('hits'),
170
+ hitPrev: find('hit-prev'),
171
+ hitNext: find('hit-next')
172
+ };
173
+
174
+ const dialog = modal ? {
175
+ root: modal,
176
+ card: modal.querySelector('.modal-card'),
177
+ backdrop: modal.querySelector('[data-role="export-backdrop"]'),
178
+ summary: modal.querySelector('[data-role="export-summary"]'),
179
+ cancel: modal.querySelector('[data-role="export-cancel"]'),
180
+ confirm: modal.querySelector('[data-role="export-confirm"]'),
181
+ formats: [...modal.querySelectorAll('input[name="export-format"]')]
182
+ } : null;
183
+
184
+ let index = 0; // zero-based page index
185
+ let matches = []; // engine search results
186
+ let hitIndex = -1; // which match is focused
187
+ let zoom = 1; // the scale actually applied
188
+ let fitWidth = false; // recompute zoom from the viewport on resize
189
+ let returnFocusTo = null; // what had focus before the dialog opened
190
+
191
+ const afterPrintSupported = typeof view.onafterprint !== 'undefined';
192
+
193
+ ui.total.textContent = String(total);
194
+ ui.current.max = String(total);
195
+
196
+ /* ---------------- paging ---------------- */
197
+
198
+ function show(next) {
199
+ index = Math.min(Math.max(next, 0), total - 1);
200
+
201
+ pages.forEach((page, i) => page.classList.toggle('is-current', i === index));
202
+
203
+ ui.current.value = String(index + 1);
204
+ ui.prev.disabled = index === 0;
205
+ ui.next.disabled = index === total - 1;
206
+
207
+ paint();
208
+ /** absent in jsdom, so a consumer testing there is not stopped by it */
209
+ mountEl.scrollTo?.({ top: 0 });
210
+ }
211
+
212
+ /* ---------------- zoom ---------------- */
213
+
214
+ /**
215
+ * A CSS transform is what keeps the report faithful - scaling font sizes
216
+ * instead would re-wrap text and stop matching the paginated layout, which
217
+ * is the whole point of a print preview.
218
+ *
219
+ * transform does not affect layout, so the stack is given the scaled
220
+ * footprint explicitly, otherwise there is nothing to scroll at 200%.
221
+ * Its size comes from the layout file rather than the DOM, so it is right
222
+ * before first paint and does not depend on a live layout engine.
223
+ */
224
+ function applyZoom() {
225
+ mountEl.style.setProperty('--zoom', String(zoom));
226
+
227
+ if (stack) {
228
+ stack.style.width = `${paginated.page.width * zoom}px`;
229
+ stack.style.height = `${paginated.page.height * zoom}px`;
230
+ }
231
+
232
+ if (!fitWidth) {
233
+ const exact = ZOOM_STEPS.find(step => Math.abs(step - zoom) < 1e-9);
234
+ ui.zoom.value = exact !== undefined ? String(exact) : 'fit';
235
+ }
236
+
237
+ ui.zoomOut.disabled = !fitWidth && zoom <= MIN_ZOOM;
238
+ ui.zoomIn.disabled = !fitWidth && zoom >= MAX_ZOOM;
239
+ }
240
+
241
+ function setZoom(next) {
242
+ fitWidth = false;
243
+ zoom = Math.min(Math.max(next, MIN_ZOOM), MAX_ZOOM);
244
+ applyZoom();
245
+ }
246
+
247
+ /** the widest scale that still fits the viewport, ignoring the scrollbar */
248
+ function setFitWidth() {
249
+ fitWidth = true;
250
+ ui.zoom.value = 'fit';
251
+
252
+ const available = mountEl.clientWidth - 48;
253
+ if (available > 0) {
254
+ zoom = Math.min(Math.max(available / paginated.page.width, MIN_ZOOM), MAX_ZOOM);
255
+ }
256
+
257
+ applyZoom();
258
+ }
259
+
260
+ /** steps to the neighbouring preset rather than a blind multiply */
261
+ function stepZoom(direction) {
262
+ const from = zoom;
263
+ const next = direction > 0
264
+ ? ZOOM_STEPS.find(step => step > from + 1e-9)
265
+ : [...ZOOM_STEPS].reverse().find(step => step < from - 1e-9);
266
+
267
+ setZoom(next ?? from);
268
+ }
269
+
270
+ /* ---------------- exporting ---------------- */
271
+
272
+ /**
273
+ * One entry per offered format. Adding a third means a line here and a radio
274
+ * in the dialog; nothing else in the flow needs to know about it.
275
+ */
276
+ const FORMATS = {
277
+ pdf: {
278
+ available: () => true,
279
+ summary: () => `${total} page${total === 1 ? '' : 's'}, ` +
280
+ `${paginated.page.width}×${paginated.page.height}px each.`,
281
+ run: () => printReport()
282
+ },
283
+ csv: {
284
+ available: () => toReportCSV(paginated.pages) !== '',
285
+ summary: () => FORMATS.csv.available()
286
+ ? `Downloads ${reportFilename(paginated, 'csv')}.`
287
+ : 'This report has nothing to write out.',
288
+ run: () => downloadCSV()
289
+ }
290
+ };
291
+
292
+ /**
293
+ * Spec 6: PDF is window.print(). It costs nothing, and it matches the
294
+ * preview exactly because it *is* the preview - the print stylesheet just
295
+ * reveals every page and drops the chrome.
296
+ *
297
+ * Search highlights are cleared first so they do not end up in the file.
298
+ */
299
+ function printReport() {
300
+ clearMarks();
301
+
302
+ /** the window the report is in, which is not always the one this ran from */
303
+ view.print();
304
+
305
+ /**
306
+ * Firefox and Safari return from print() before the dialog has taken
307
+ * its snapshot, so restoring the highlights on the next line would put
308
+ * them back too early and print them. afterprint is the reliable point;
309
+ * the immediate call below covers browsers that never fire it.
310
+ */
311
+ if (!afterPrintSupported) restoreAfterPrint();
312
+ }
313
+
314
+ function restoreAfterPrint() {
315
+ if (ui.query.value.trim() !== '') paint();
316
+ }
317
+
318
+
319
+ /**
320
+ * The report already carries its own margins, so the sheet must add none -
321
+ * without this the browser's default print margin is added on top, the
322
+ * page no longer fits the paper, and every page spills a sliver onto a
323
+ * second sheet. The size comes from the layout, so a Letter or custom page
324
+ * prints as designed rather than as whatever A4 assumption was baked in.
325
+ */
326
+ function applyPrintPageSize() {
327
+ const { width, height } = paginated.page;
328
+
329
+ /**
330
+ * Into the viewer's own document: a report opened in its own window
331
+ * prints from that window, and an @page rule left in the opener would
332
+ * size the wrong sheet - or none.
333
+ */
334
+ let style = doc.getElementById('report-page-size');
335
+ if (!style) {
336
+ style = doc.createElement('style');
337
+ style.id = 'report-page-size';
338
+ doc.head.appendChild(style);
339
+ }
340
+
341
+ style.textContent = `@page { size: ${width}px ${height}px; margin: 0; }`;
342
+ }
343
+
344
+ /**
345
+ * The report as text: every line and every table row, in the order the
346
+ * pages draw them. Boxes and rules are the only things left behind, having
347
+ * nothing to write.
348
+ */
349
+ function downloadCSV() {
350
+ const csv = toReportCSV(paginated.pages);
351
+ if (csv === '') return false;
352
+
353
+ /** the BOM is what makes Excel read the file as UTF-8 rather than latin-1 */
354
+ download(
355
+ new Blob(['', csv], { type: 'text/csv;charset=utf-8' }),
356
+ reportFilename(paginated, 'csv')
357
+ );
358
+
359
+ return true;
360
+ }
361
+
362
+ function download(blob, filename) {
363
+ const url = URL.createObjectURL(blob);
364
+ const link = doc.createElement('a');
365
+
366
+ link.href = url;
367
+ link.download = filename;
368
+ doc.body.appendChild(link);
369
+ link.click();
370
+ link.remove();
371
+
372
+ /** give the browser a tick to start the download before dropping the url */
373
+ setTimeout(() => URL.revokeObjectURL(url), 0);
374
+ }
375
+
376
+ /* ---------------- the export dialog ---------------- */
377
+
378
+ function chosenFormat() {
379
+ return dialog?.formats.find(input => input.checked)?.value ?? 'pdf';
380
+ }
381
+
382
+ /** the note under the radios, plus whether Export can proceed at all */
383
+ function refreshDialog() {
384
+ if (!dialog) return;
385
+
386
+ for (const input of dialog.formats) {
387
+ const format = FORMATS[input.value];
388
+ input.disabled = format ? !format.available() : true;
389
+ input.closest('.format')?.classList.toggle('is-unavailable', input.disabled);
390
+ }
391
+
392
+ /** never leave a disabled option selected */
393
+ const current = dialog.formats.find(i => i.checked);
394
+ if (current?.disabled) {
395
+ const fallback = dialog.formats.find(i => !i.disabled);
396
+ if (fallback) fallback.checked = true;
397
+ }
398
+
399
+ const format = FORMATS[chosenFormat()];
400
+ dialog.summary.textContent = format ? format.summary() : '';
401
+ dialog.confirm.disabled = !format || !format.available();
402
+ }
403
+
404
+ function openExport() {
405
+ if (!dialog) return;
406
+
407
+ returnFocusTo = doc.activeElement;
408
+ dialog.root.hidden = false;
409
+ refreshDialog();
410
+
411
+ const focusOn = dialog.formats.find(i => i.checked && !i.disabled)
412
+ ?? dialog.formats.find(i => !i.disabled)
413
+ ?? dialog.cancel;
414
+ focusOn.focus();
415
+ }
416
+
417
+ function closeExport() {
418
+ if (!dialog || dialog.root.hidden) return;
419
+
420
+ dialog.root.hidden = true;
421
+ returnFocusTo?.focus?.();
422
+ returnFocusTo = null;
423
+ }
424
+
425
+ function confirmExport() {
426
+ const format = FORMATS[chosenFormat()];
427
+ if (!format?.available()) return;
428
+
429
+ /**
430
+ * Close first. The print dialog is modal and blocking, so leaving our
431
+ * own overlay up would put it in the printed page and in the way.
432
+ */
433
+ closeExport();
434
+ format.run();
435
+ }
436
+
437
+ /** keeps Tab inside the card while the dialog is up */
438
+ function trapFocus(event) {
439
+ const focusable = [...dialog.card.querySelectorAll('button, input')]
440
+ .filter(node => !node.disabled);
441
+ if (!focusable.length) return;
442
+
443
+ const first = focusable[0];
444
+ const last = focusable[focusable.length - 1];
445
+
446
+ if (event.shiftKey && doc.activeElement === first) {
447
+ event.preventDefault();
448
+ last.focus();
449
+ } else if (!event.shiftKey && doc.activeElement === last) {
450
+ event.preventDefault();
451
+ first.focus();
452
+ }
453
+ }
454
+
455
+ /* ---------------- search ---------------- */
456
+
457
+ function runSearch() {
458
+ const query = ui.query.value.trim();
459
+
460
+ clearMarks();
461
+
462
+ if (query === '') {
463
+ matches = [];
464
+ hitIndex = -1;
465
+ ui.hits.textContent = '';
466
+ ui.hits.dataset.state = 'idle';
467
+ setHitButtons();
468
+ return;
469
+ }
470
+
471
+ matches = search(paginated.pages, query);
472
+ hitIndex = matches.length ? 0 : -1;
473
+
474
+ ui.hits.dataset.state = matches.length ? 'found' : 'empty';
475
+ setHitButtons();
476
+
477
+ if (!matches.length) {
478
+ ui.hits.textContent = 'no matches';
479
+ return;
480
+ }
481
+
482
+ /**
483
+ * Jump straight to the first hit. Reporting how many pages carry it is
484
+ * more useful than a raw count when the viewer shows one page at a time.
485
+ */
486
+ const onPages = searchPages(paginated.pages, query).length;
487
+ ui.hits.textContent =
488
+ `${matches.length} on ${onPages} page${onPages === 1 ? '' : 's'}`;
489
+
490
+ goToHit(0);
491
+ }
492
+
493
+ function goToHit(next) {
494
+ if (!matches.length) return;
495
+
496
+ hitIndex = (next + matches.length) % matches.length;
497
+ const target = matches[hitIndex].pageNO - 1;
498
+
499
+ if (target !== index) show(target);
500
+ else paint();
501
+
502
+ ui.hits.textContent = `${hitIndex + 1} of ${matches.length}`;
503
+ focusMark();
504
+ }
505
+
506
+ function setHitButtons() {
507
+ ui.hitPrev.disabled = matches.length === 0;
508
+ ui.hitNext.disabled = matches.length === 0;
509
+ }
510
+
511
+ /* ---------------- highlighting ---------------- */
512
+
513
+ function clearMarks() {
514
+ for (const mark of mountEl.querySelectorAll('mark.hit')) {
515
+ const parent = mark.parentNode;
516
+ parent.replaceChild(doc.createTextNode(mark.textContent), mark);
517
+ parent.normalize();
518
+ }
519
+ }
520
+
521
+ /** marks every occurrence on the page currently on screen */
522
+ function paint() {
523
+ clearMarks();
524
+
525
+ const query = ui.query.value.trim();
526
+ if (query === '') return;
527
+
528
+ const page = pages[index];
529
+ if (!page) return;
530
+
531
+ const needle = query.toLowerCase();
532
+ const walker = doc.createTreeWalker(page, NodeFilter.SHOW_TEXT);
533
+ const targets = [];
534
+
535
+ while (walker.nextNode()) {
536
+ const node = walker.currentNode;
537
+ if (node.nodeValue.toLowerCase().includes(needle)) targets.push(node);
538
+ }
539
+
540
+ for (const node of targets) markNode(node, needle);
541
+ }
542
+
543
+ function markNode(node, needle) {
544
+ const text = node.nodeValue;
545
+ const fragment = doc.createDocumentFragment();
546
+
547
+ let from = 0;
548
+
549
+ for (; ;) {
550
+ const at = text.toLowerCase().indexOf(needle, from);
551
+ if (at === -1) break;
552
+
553
+ if (at > from) fragment.appendChild(doc.createTextNode(text.slice(from, at)));
554
+
555
+ const mark = doc.createElement('mark');
556
+ mark.className = 'hit';
557
+ mark.textContent = text.slice(at, at + needle.length);
558
+ fragment.appendChild(mark);
559
+
560
+ from = at + needle.length;
561
+ }
562
+
563
+ if (from < text.length) fragment.appendChild(doc.createTextNode(text.slice(from)));
564
+
565
+ node.parentNode.replaceChild(fragment, node);
566
+ }
567
+
568
+ /** the focused hit gets a stronger colour and is scrolled into view */
569
+ function focusMark() {
570
+ const marks = [...mountEl.querySelectorAll('mark.hit')];
571
+ if (!marks.length) return;
572
+
573
+ /** how many of the run of matches fall on this page before the focused one */
574
+ const onThisPage = matches.filter(m => m.pageNO === index + 1);
575
+ const offset = onThisPage.indexOf(matches[hitIndex]);
576
+ const mark = marks[Math.max(offset, 0)] ?? marks[0];
577
+
578
+ marks.forEach(m => m.classList.remove('is-focused'));
579
+ mark.classList.add('is-focused');
580
+ mark.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
581
+ }
582
+
583
+ /* ---------------- wiring ---------------- */
584
+
585
+ ui.prev.addEventListener('click', () => show(index - 1));
586
+ ui.next.addEventListener('click', () => show(index + 1));
587
+
588
+ ui.current.addEventListener('change', () => {
589
+ const asked = Number(ui.current.value);
590
+ if (Number.isFinite(asked)) show(asked - 1);
591
+ else ui.current.value = String(index + 1);
592
+ });
593
+
594
+ ui.print?.addEventListener('click', printReport);
595
+ ui.exportOpen.addEventListener('click', openExport);
596
+
597
+ if (dialog) {
598
+ dialog.cancel.addEventListener('click', closeExport);
599
+ dialog.backdrop.addEventListener('click', closeExport);
600
+ dialog.confirm.addEventListener('click', confirmExport);
601
+
602
+ for (const input of dialog.formats) {
603
+ input.addEventListener('change', refreshDialog);
604
+ }
605
+
606
+ dialog.root.addEventListener('keydown', (event) => {
607
+ if (event.key === 'Tab') trapFocus(event);
608
+ if (event.key === 'Enter') { event.preventDefault(); confirmExport(); }
609
+ });
610
+ }
611
+
612
+ ui.zoomIn.addEventListener('click', () => stepZoom(1));
613
+ ui.zoomOut.addEventListener('click', () => stepZoom(-1));
614
+
615
+ ui.zoom.addEventListener('change', () => {
616
+ if (ui.zoom.value === 'fit') setFitWidth();
617
+ else setZoom(Number(ui.zoom.value));
618
+ });
619
+
620
+ const onResize = () => { if (fitWidth) setFitWidth(); };
621
+ view.addEventListener('resize', onResize);
622
+
623
+ ui.hitPrev.addEventListener('click', () => goToHit(hitIndex - 1));
624
+ ui.hitNext.addEventListener('click', () => goToHit(hitIndex + 1));
625
+
626
+ let debounce;
627
+ ui.query.addEventListener('input', () => {
628
+ clearTimeout(debounce);
629
+ debounce = setTimeout(runSearch, 150);
630
+ });
631
+
632
+ ui.query.addEventListener('keydown', (event) => {
633
+ if (event.key !== 'Enter') return;
634
+ event.preventDefault();
635
+ if (matches.length) goToHit(hitIndex + (event.shiftKey ? -1 : 1));
636
+ else runSearch();
637
+ });
638
+
639
+ /** paging keys, as long as the user is not typing in the search box */
640
+ const onKeyDown = (event) => {
641
+ /** while the dialog is up it owns the keyboard, bar Escape */
642
+ if (dialog && !dialog.root.hidden) {
643
+ if (event.key === 'Escape') { event.preventDefault(); closeExport(); }
644
+ return;
645
+ }
646
+
647
+ /**
648
+ * ctrl+K reaches the search from anywhere, including from inside another
649
+ * field, so it sits above the guard that hands typing back to the inputs.
650
+ * ctrl+F comes along because it is what a browser's own find uses, and
651
+ * the report's search is more useful than searching the one page on screen.
652
+ */
653
+ if ((event.ctrlKey || event.metaKey) && ['k', 'f'].includes(event.key.toLowerCase())) {
654
+ event.preventDefault();
655
+ ui.query.focus();
656
+ ui.query.select();
657
+ return;
658
+ }
659
+
660
+ /**
661
+ * ctrl+P is taken from the browser deliberately: printing through
662
+ * printReport clears the search highlights first, so they do not end up
663
+ * in the PDF the way the browser's own shortcut would leave them.
664
+ */
665
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'p') {
666
+ event.preventDefault();
667
+ printReport();
668
+ return;
669
+ }
670
+
671
+ /**
672
+ * Everything below is held back while a field has focus, which is what
673
+ * keeps ctrl+X available for cutting text out of the search box.
674
+ */
675
+ if (event.target === ui.query || event.target === ui.current) return;
676
+
677
+ /** ctrl+X opens the export; ctrl+S too, since the browser's save is no use here */
678
+ if ((event.ctrlKey || event.metaKey) && ['x', 's'].includes(event.key.toLowerCase())) {
679
+ event.preventDefault();
680
+ openExport();
681
+ return;
682
+ }
683
+
684
+ if (event.key === 'ArrowRight' || event.key === 'PageDown') show(index + 1);
685
+ if (event.key === 'ArrowLeft' || event.key === 'PageUp') show(index - 1);
686
+ if (event.key === 'Home') show(0);
687
+ if (event.key === 'End') show(total - 1);
688
+
689
+ /** ctrl +/-/0 zooms the report, the way the browser would zoom a page */
690
+ if (event.ctrlKey || event.metaKey) {
691
+ if (event.key === '+' || event.key === '=') { event.preventDefault(); stepZoom(1); }
692
+ if (event.key === '-') { event.preventDefault(); stepZoom(-1); }
693
+ if (event.key === '0') { event.preventDefault(); setZoom(1); }
694
+ }
695
+ };
696
+
697
+ doc.addEventListener('keydown', onKeyDown);
698
+
699
+ if (afterPrintSupported) {
700
+ view.addEventListener('afterprint', restoreAfterPrint);
701
+ }
702
+
703
+ /**
704
+ * The listeners above are on the viewer's own document and window, which
705
+ * outlive this mount. Without a way to take them off, a second viewer on
706
+ * the same page - or a React <Preview /> remounting - leaves the first one
707
+ * still handling keys.
708
+ */
709
+ function destroy() {
710
+ ui.zoom.destroy();
711
+ doc.removeEventListener('keydown', onKeyDown);
712
+ view.removeEventListener('resize', onResize);
713
+ view.removeEventListener('afterprint', restoreAfterPrint);
714
+
715
+ /** the viewer built everything in here, so it takes it all away again */
716
+ root.innerHTML = '';
717
+ root.classList.remove('report-viewer');
718
+ }
719
+
720
+ applyPrintPageSize();
721
+ applyZoom();
722
+ show(0);
723
+ setHitButtons();
724
+
725
+ return {
726
+ show,
727
+ next: () => show(index + 1),
728
+ prev: () => show(index - 1),
729
+ find: (q) => { ui.query.value = q; runSearch(); },
730
+ print: printReport,
731
+ downloadCSV,
732
+ openExport,
733
+ closeExport,
734
+ confirmExport,
735
+ destroy,
736
+ get exportOpen() { return dialog ? !dialog.root.hidden : false; },
737
+ setZoom,
738
+ zoomIn: () => stepZoom(1),
739
+ zoomOut: () => stepZoom(-1),
740
+ fitWidth: setFitWidth,
741
+ get zoom() { return zoom; },
742
+ get page() { return index + 1; },
743
+ get pageCount() { return total; }
744
+ };
745
+ }