report-studio 1.0.0 → 1.2.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 (53) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +171 -22
  3. package/dist/designer-qy59eEux.js +3416 -0
  4. package/dist/designer.js +2 -3209
  5. package/dist/index.js +2 -2
  6. package/dist/react-designer.js +41 -0
  7. package/dist/react.js +60 -0
  8. package/dist/{viewer-D-c0lKzQ.js → viewer-xa17tyMJ.js} +682 -537
  9. package/package.json +105 -66
  10. package/src/cli/serve.js +135 -135
  11. package/src/designer/designer.js +2054 -1900
  12. package/src/designer/dialog.js +708 -708
  13. package/src/designer/fields.js +51 -2
  14. package/src/designer/icons.js +5 -0
  15. package/src/designer/index.html +28 -28
  16. package/src/designer/main.js +39 -39
  17. package/src/designer/menu.js +2 -2
  18. package/src/designer/panel.js +21 -1
  19. package/src/designer/sample-data.js +180 -9
  20. package/src/designer/structure.js +87 -6
  21. package/src/designer/styles.css +1654 -1616
  22. package/src/designer/tokens.js +9 -0
  23. package/src/engine/csv.js +350 -315
  24. package/src/engine/group.js +128 -65
  25. package/src/engine/index.js +35 -34
  26. package/src/engine/measure.js +13 -12
  27. package/src/engine/paginate.js +8 -4
  28. package/src/engine/resolve.js +37 -0
  29. package/src/engine/tables.js +87 -0
  30. package/src/engine/validate.js +97 -22
  31. package/src/index.html +79 -79
  32. package/src/index.js +51 -50
  33. package/src/preview/chrome.css +505 -505
  34. package/src/preview/chrome.js +147 -147
  35. package/src/preview/index.html +28 -28
  36. package/src/preview/viewer.js +763 -745
  37. package/src/react/designer.js +87 -0
  38. package/src/react/index.js +117 -0
  39. package/src/render/items.js +94 -1
  40. package/src/render/report.css +30 -0
  41. package/src/server/routes.js +331 -331
  42. package/src/shared/brand.css +29 -29
  43. package/src/shared/dropdown.css +136 -136
  44. package/src/shared/modal.css +125 -125
  45. package/src/shared/store.js +145 -145
  46. package/src/shared/theme.css +72 -72
  47. package/src/shared/window.js +138 -138
  48. package/types/designer.d.ts +85 -0
  49. package/types/index.d.ts +204 -0
  50. package/types/layout.d.ts +179 -0
  51. package/types/react-designer.d.ts +29 -0
  52. package/types/react.d.ts +30 -0
  53. package/types/vite.d.ts +18 -0
@@ -1,1900 +1,2054 @@
1
- /**
2
- * designer.js is the package's designer entry point.
3
- *
4
- * createDesigner({ mount: '#report-designer', layout })
5
- *
6
- * The host supplies one empty element and nothing else - the designer builds
7
- * its own chrome inside it. Asking a consumer to copy a screenful of toolbar
8
- * markup is how the preview playground works, and it is not an API.
9
- *
10
- * Nothing here imports React, and nothing here touches the filesystem: reading
11
- * and writing report files is the dev server's job (phase 5), reached over
12
- * fetch. This module knows about a layout object and a DOM node.
13
- */
14
-
15
- import { validateLayout } from '../engine/validate.js';
16
- import { allFields, allReportFields, fieldsFor, reportFields } from './fields.js';
17
- import { blankLayout, isEmptyLayout } from './blank.js';
18
- import {
19
- drawSheet, selectionBox, selectionBoxes, bandUnder, bandBox, drawGuides,
20
- guideLines, guideNubs
21
- } from './canvas.js';
22
- import { attachEditing } from './select.js';
23
- import {
24
- drawPanel, drawReportPanel, drawManyPanel, attachPanel, syncPanel
25
- } from './panel.js';
26
- import { icon } from './icons.js';
27
- import { createDropdown } from '../shared/dropdown.js';
28
- import { menuActions, drawMenu, menuPosition } from './menu.js';
29
- import { openWindow, closeWithOpener } from '../shared/window.js';
30
- import {
31
- openViewerWindow, ZOOM_STEPS, MIN_ZOOM, MAX_ZOOM
32
- } from '../preview/viewer.js';
33
- import { buildPages } from '../engine/index.js';
34
- import { drawProblems, sameIssues } from './toast.js';
35
- import { askColumns, askReport, askName, askData, askToken, askDiscard } from './dialog.js';
36
- import { sampleData } from './sample-data.js';
37
- import { drawPreview } from './preview.js';
38
- import { createHistory } from './history.js';
39
- import { createStore, StoreError, toId } from '../shared/store.js';
40
- import {
41
- addBand, removeBand, findBand, addItem, removeItem, duplicateItem, pasteItems,
42
- moveItemToBand, createText, createTable, createLine, createBox, addColumn,
43
- removeColumn, targetBand, canAddTable
44
- } from './structure.js';
45
-
46
-
47
- /**
48
- * Mounts the designer.
49
- *
50
- * @param {object} options
51
- * @param {Element|string} options.mount the element to take over, or a selector
52
- * @param {object} [options.layout] the report to edit; empty or absent starts a new one
53
- * @param {string} [options.id] the report's filename stem, when it has one
54
- * @param {object} [options.store] where reports are read and written; the dev
55
- * server's routes by default
56
- * @param {boolean} [options.guardUnload=true] ask the browser to confirm before
57
- * the tab or window closes on unsaved changes. The browser words that prompt
58
- * itself and will not take ours; pass false in a host that has its own.
59
- * @returns {object} a handle: the current layout, redraw, and destroy
60
- */
61
- /**
62
- * Opens the designer in a window of its own.
63
- *
64
- * The same designer, mounted in a window this opens rather than in an element
65
- * the host supplies - a report is a page-shaped thing, and a page suits a
66
- * window better than a panel in somebody's application. The host's stylesheets
67
- * are carried across, so it looks the same either way.
68
- *
69
- * Call it from a click or a keystroke, or the browser blocks it; a blocked
70
- * window is null rather than a throw, so a host can fall back to the page.
71
- *
72
- * @param {object} options what createDesigner takes, less `mount`
73
- * @param {number} [options.width]
74
- * @param {number} [options.height]
75
- * @param {string} [options.features] passed to window.open as given
76
- * @returns {object|null} the designer handle, with `window`; null if blocked
77
- */
78
- export function openDesignerWindow({
79
- width, height, features, ...rest
80
- } = {}) {
81
- const opened = openWindow({
82
- title: rest.layout?.name ? `${rest.layout.name} - Designer` : 'Report designer',
83
- width, height, features
84
- });
85
-
86
- if (!opened) return null;
87
-
88
- const designer = createDesigner({ ...rest, mount: opened.mount });
89
-
90
- /** what is being edited is held in memory, so it goes when the opener does */
91
- const unwatch = closeWithOpener(globalThis, opened.window, designer.destroy);
92
-
93
- return {
94
- ...designer,
95
- window: opened.window,
96
-
97
- destroy() {
98
- unwatch();
99
- designer.destroy();
100
- opened.close();
101
- }
102
- };
103
- }
104
-
105
-
106
- export function createDesigner({
107
- mount, layout, id = null, store, guardUnload = true
108
- } = {}) {
109
- const root = typeof mount === 'string'
110
- ? document.querySelector(mount)
111
- : mount;
112
-
113
- if (!root) {
114
- throw new Error(
115
- `createDesigner: no element for mount ${JSON.stringify(mount)}. ` +
116
- `Add <div id="report-designer"></div> to the page first.`
117
- );
118
- }
119
-
120
- /**
121
- * The document the screen is mounted in, which is not always this one: a
122
- * designer or a viewer opened in its own window lives in that window's
123
- * document, and a listener put on the opener's would never hear it.
124
- */
125
- const doc = root.ownerDocument;
126
-
127
- const files = store ?? createStore();
128
-
129
- const state = {
130
- /** page pixels per screen pixel; 1 until somebody says otherwise */
131
- zoom: 1,
132
-
133
- /** whether the zoom is being recomputed from the viewport on resize */
134
- fitWidth: false,
135
-
136
- /**
137
- * Whether the rulers are showing. A view preference, not part of the
138
- * report - the guides dragged off them are saved with the file, but
139
- * whether somebody has the rulers up while they work is theirs.
140
- */
141
- rulers: false,
142
-
143
- layout: isEmptyLayout(layout) ? blankLayout() : layout,
144
- /**
145
- * The selected items, oldest first, as `{ band, id }` - the band type
146
- * and the item id, because ids are only unique within a band
147
- * (validate.js does not require more).
148
- *
149
- * A list rather than one, so several can be moved together. The last is
150
- * the primary: it is the one the rail describes and the one whose
151
- * handles are drawn, because resizing six things at once has no single
152
- * answer.
153
- */
154
- selection: [],
155
- /** the filename stem this report is saved under, or null if never saved */
156
- id,
157
- /** whether there are changes the disk has not seen */
158
- dirty: false,
159
- /**
160
- * What ctrl+C took, as `{ band, item }` - the item deep-copied, so a
161
- * later edit to the original does not reach back into the clipboard,
162
- * and the band it came from, which a paste elsewhere needs to know to
163
- * reposition it.
164
- *
165
- * The designer's own, not the system's: reading the platform clipboard
166
- * needs a permission prompt, and nothing outside this screen can use a
167
- * layout item anyway.
168
- */
169
- clipboard: [],
170
- /** 'design' arranges the bands; 'preview' runs the report */
171
- mode: 'design',
172
- /**
173
- * The problems the author has already been shown and closed, so the
174
- * toast does not reopen on every keystroke. It comes back the moment
175
- * what is wrong changes - see sameIssues in toast.js.
176
- */
177
- dismissed: null
178
- };
179
-
180
- const history = createHistory(state.layout);
181
-
182
- root.classList.add('report-designer');
183
-
184
- /**
185
- * The designer has to be able to hold the focus.
186
- *
187
- * Its shortcuts are bound per designer rather than to the document, so a
188
- * second one on the page does not answer for this one - which only works if
189
- * the focus can get in here, and a div cannot take it without being told.
190
- * -1 rather than 0: it is reachable by clicking, not by tabbing to it, so
191
- * it never becomes a stop on the way to the controls inside it.
192
- */
193
- root.tabIndex = -1;
194
- root.innerHTML = chrome(state.layout);
195
-
196
- const canvas = root.querySelector('[data-role="canvas"]');
197
- const stage = root.querySelector('[data-role="stage"]');
198
- /** everything drawn lives in here, so the scale has one thing to act on */
199
- const surface = root.querySelector('[data-role="zoom-layer"]');
200
- const panel = root.querySelector('[data-role="panel"]');
201
- const bar = root.querySelector('[data-role="bar"]');
202
- const foot = root.querySelector('[data-role="foot"]');
203
- /** the pill is drawn into the page area, which is the box it must stay inside */
204
- const main = root.querySelector('.dz-main');
205
- const toasts = root.querySelector('[data-role="toasts"]');
206
- const pages = root.querySelector('[data-role="pages"]');
207
-
208
-
209
- /** the most recently selected `{ band, id }`, or null */
210
- function primary() {
211
- return state.selection.at(-1) ?? null;
212
- }
213
-
214
-
215
- /** the layout item behind a `{ band, id }`, or null if it has since gone */
216
- function itemAt(one) {
217
- if (!one) return null;
218
-
219
- const band = findBand(state.layout, one.band);
220
- return (band?.items || []).find(i => i.id === one.id) ?? null;
221
- }
222
-
223
-
224
- /** the item the rail describes */
225
- function selected() {
226
- return itemAt(primary());
227
- }
228
-
229
-
230
- /** every selected item, skipping any that have since been removed */
231
- function selectedItems() {
232
- return state.selection.map(itemAt).filter(Boolean);
233
- }
234
-
235
-
236
- function draw() {
237
- /**
238
- * Spec 9.1: a layout is hand-written as often as it is designed, so a
239
- * broken one is named field by field rather than drawn as a blank page
240
- * and left to look like the library is broken.
241
- *
242
- * The issues are said in the corner rather than drawn over the
243
- * design, because most of them are survivable - setting groupBy before
244
- * adding a group band is one keystroke, and pushing the page down the
245
- * canvas to say so is a punishment. Only a layout that cannot be drawn
246
- * at all leaves nothing behind it.
247
- */
248
- const issues = validateLayout(state.layout);
249
-
250
- if (state.mode === 'preview') {
251
- const run = drawPreview(state.layout, state.data);
252
-
253
- surface.innerHTML = run.markup;
254
- pages.textContent = run.error
255
- ? ''
256
- : `${run.pageCount} page${run.pageCount === 1 ? '' : 's'}`;
257
-
258
- /** the preview says what stopped it in the page itself */
259
- showProblems(issues);
260
- applyZoom();
261
- return issues;
262
- }
263
-
264
- pages.textContent = '';
265
-
266
- let sheet = '';
267
-
268
- try {
269
- sheet = drawSheet(state.layout, state.selection,
270
- { rulers: state.rulers });
271
- } catch {
272
- sheet = '';
273
- }
274
-
275
- surface.innerHTML = sheet;
276
- showProblems(issues);
277
-
278
- /** what was drawn may be a different size; the stage has to match it */
279
- applyZoom();
280
-
281
- return issues;
282
- }
283
-
284
-
285
- /**
286
- * Puts the validator's findings in the corner, or takes them away again.
287
- *
288
- * Never while the report is being previewed: the run says what stopped it in
289
- * the page itself, and two accounts of one fault is one too many.
290
- *
291
- * @param {string[]} issues
292
- */
293
- function showProblems(issues) {
294
- const hidden = state.mode !== 'design'
295
- || issues.length === 0
296
- || sameIssues(issues, state.dismissed);
297
-
298
- toasts.innerHTML = hidden ? '' : drawProblems(issues);
299
-
300
- /** a layout that validates forgets the dismissal, so the next fault is announced */
301
- if (issues.length === 0) state.dismissed = null;
302
- }
303
-
304
-
305
- /**
306
- * A drag redraws sixty times a second, and rebuilding the page's markup that
307
- * often is how a hand-written drag ends up feeling worse than the library it
308
- * replaced. While the pointer is down only the two boxes that moved are
309
- * touched; the full redraw happens once, when it is let go.
310
- */
311
- function patch() {
312
- patchRules();
313
-
314
- const boxes = selectionBoxes(state.layout, state.selection);
315
-
316
- for (const [index, { item, box }] of boxes.entries()) {
317
- const where = state.selection[index];
318
-
319
- const outline = canvas.querySelector(
320
- `[data-role="select"][data-select-id="${cssEscape(item.id)}"]`);
321
-
322
- if (outline) {
323
- Object.assign(outline.style, {
324
- top: `${box.y}px`, left: `${box.x}px`,
325
- width: `${box.w}px`, height: `${box.h}px`
326
- });
327
- }
328
-
329
- const drawn = canvas.querySelector(
330
- `[data-band-type="${cssEscape(where.band)}"] ` +
331
- `[data-item-id="${cssEscape(item.id)}"]`);
332
-
333
- if (!drawn) continue;
334
-
335
- Object.assign(drawn.style, {
336
- top: `${item.y}px`, left: `${item.x}px`, width: `${item.w}px`
337
- });
338
- /** a table's height is its rows', so it is never written here */
339
- if (item.type !== 'table') drawn.style.height = `${item.h}px`;
340
- }
341
- }
342
-
343
-
344
- /**
345
- * The ruler guides, redrawn without rebuilding the sheet.
346
- *
347
- * Two small containers rather than the whole page: the ticks never move and
348
- * there are two hundred of them, and a guide being dragged is the same sixty
349
- * frames a second an item drag is.
350
- */
351
- function patchRules() {
352
- const rules = canvas.querySelector('[data-role="rules"]');
353
- if (rules) rules.innerHTML = state.rulers ? guideLines(state.layout) : '';
354
-
355
- for (const host of canvas.querySelectorAll('[data-role="ruler-guides"]')) {
356
- host.innerHTML = guideNubs(state.layout, host.dataset.axis);
357
- }
358
- }
359
-
360
-
361
- function drawRail() {
362
- /** a rendered report has no item to describe and no report to restructure */
363
- if (state.mode === 'preview') return;
364
-
365
- const many = state.selection.length;
366
-
367
- panel.innerHTML = many > 1
368
- ? drawManyPanel(selectedItems())
369
- : (selected() ? drawPanel(selected()) : drawReportPanel(state.layout));
370
- }
371
-
372
-
373
- const sameOne = (a, b) => a?.band === b?.band && a?.id === b?.id;
374
-
375
-
376
- /**
377
- * Sets or extends the selection.
378
- *
379
- * @param {object|object[]|null} next
380
- * @param {object} [options]
381
- * @param {boolean} [options.add] shift-click: add it, or take it out again
382
- * if it was already in - toggling is what makes a mis-click recoverable
383
- * without starting the whole selection over
384
- */
385
- function setSelection(next, { add = false } = {}) {
386
- const wanted = next == null ? [] : [].concat(next);
387
-
388
- let list;
389
-
390
- if (!add) {
391
- list = wanted;
392
- } else {
393
- list = [...state.selection];
394
-
395
- for (const one of wanted) {
396
- const at = list.findIndex(s => sameOne(s, one));
397
-
398
- if (at === -1) list.push(one);
399
- else list.splice(at, 1);
400
- }
401
- }
402
-
403
- const unchanged = list.length === state.selection.length
404
- && list.every((one, i) => sameOne(one, state.selection[i]));
405
-
406
- if (unchanged) return;
407
-
408
- state.selection = list;
409
- draw();
410
- drawRail();
411
- }
412
-
413
-
414
- /**
415
- * Records a step and marks the report as unsaved.
416
- *
417
- * Edits sharing a key coalesce into one undo step - typing "250" into a
418
- * width arrives as three edits, and three undo presses to get back past one
419
- * number is not undo but punishment.
420
- */
421
- function record(key = null) {
422
- if (history.push(state.layout, key)) {
423
- state.dirty = true;
424
- refreshBar();
425
- }
426
- }
427
-
428
-
429
- /** a change that alters the rail's own shape, not just its values */
430
- function restructured(key = null) {
431
- draw();
432
- drawRail();
433
- record(key);
434
- }
435
-
436
-
437
- function refreshBar() {
438
- bar.querySelector('[data-role="name"]').textContent = state.layout.name ?? '';
439
-
440
- /**
441
- * The preview screen reads the report off disk, so it can only show one
442
- * that has been saved. Rather than opening it to an error, the link is
443
- * inert until there is a file for it to open, and says why.
444
- */
445
- bar.querySelector('[data-role="undo"]').disabled = !history.canUndo;
446
- bar.querySelector('[data-role="redo"]').disabled = !history.canRedo;
447
-
448
- /** a toggle, so it says which way it is set rather than what it does */
449
- const size = bar.querySelector('[data-role="size"]');
450
-
451
- if (size && state.layout.page) {
452
- size.innerHTML =
453
- `${state.layout.page.width} &times; ${state.layout.page.height}`;
454
- }
455
-
456
- const rulers = bar.querySelector('[data-role="rulers"]');
457
-
458
- rulers.setAttribute('aria-pressed', String(state.rulers));
459
- rulers.classList.toggle('is-on', state.rulers);
460
-
461
- /** greyed rather than absent: it says the tool exists and why it cannot be used */
462
- const addTable = foot.querySelector('[data-role="add-table"]');
463
-
464
- addTable.disabled = !canAddTable(state.layout);
465
- addTable.title = addTable.disabled
466
- ? 'A report binds one table'
467
- : 'Add a table';
468
- bar.dataset.dirty = String(state.dirty);
469
-
470
- const saved = bar.querySelector('[data-role="status"]');
471
- saved.textContent = state.dirty
472
- ? 'Unsaved changes'
473
- : (state.id ? `Saved as ${state.id}.json` : 'Not saved yet');
474
- }
475
-
476
-
477
- /**
478
- * Replaces the whole layout, as undo, redo and opening all do.
479
- *
480
- * The selection is dropped rather than carried over: the item it named may
481
- * not exist in the layout being restored, and a selection pointing at
482
- * nothing draws an outline round empty space.
483
- */
484
- function replaceLayout(next, { id: nextId, dirty }) {
485
- state.layout = next;
486
- state.selection = [];
487
-
488
- /** another report is another design; its pages have not been run yet */
489
- state.mode = 'design';
490
- state.data = null;
491
-
492
- if (nextId !== undefined) state.id = nextId;
493
- if (dirty !== undefined) state.dirty = dirty;
494
-
495
- drawMode();
496
- }
497
-
498
-
499
- /** puts a new item on a band and leaves it selected, rail and all */
500
- function place(bandType, item) {
501
- addItem(state.layout, bandType, item);
502
-
503
- state.selection = [{ band: bandType, id: item.id }];
504
- restructured(`add:${item.id}`);
505
-
506
- /**
507
- * The band is lit for a moment afterwards. Where an inserted item lands
508
- * is a decision the designer made rather than the user, so it says
509
- * where - a page number appearing somewhere unexpected is otherwise
510
- * found by hunting for it.
511
- */
512
- flashBand(bandType);
513
- }
514
-
515
-
516
- /** which band is lit, and why - a drop target, or somewhere just inserted */
517
- function markTarget(types) {
518
- /** one band or several: a group can straddle a boundary */
519
- const lit = new Set(types == null ? [] : [].concat(types));
520
-
521
- for (const zone of canvas.querySelectorAll('[data-band-type]')) {
522
- zone.classList.toggle('is-target', lit.has(zone.dataset.bandType));
523
- }
524
-
525
- /** the name in the gutter lights too, so the band is named not just lit */
526
- for (const tag of canvas.querySelectorAll('[data-band-tag]')) {
527
- tag.classList.toggle('is-target', lit.has(tag.dataset.bandTag));
528
- }
529
- }
530
-
531
-
532
- /**
533
- * Draws the alignment guides, or takes them away.
534
- *
535
- * Into a layer of its own rather than into the outlines, for the reason the
536
- * outlines are a layer of their own: a guide belongs to the gesture, not to
537
- * an item, and an item that is redrawn mid-drag would take its guides with
538
- * it. The layer survives patch() because patch() only touches boxes.
539
- *
540
- * @param {{band: string, lines: object[], gaps: object[]}|null} found
541
- */
542
- function drawAlignment(found) {
543
- const layer = canvas.querySelector('[data-role="guides"]');
544
- if (!layer) return;
545
-
546
- layer.innerHTML = found
547
- ? drawGuides(bandBox(state.layout, found.band), found.lines, found.gaps)
548
- : '';
549
- }
550
-
551
-
552
- /* ---------------- zoom ---------------- */
553
-
554
- /**
555
- * Scales the drawing rather than the numbers in it.
556
- *
557
- * The same choice the viewer makes, and for the same reason: re-computing
558
- * type at 150% would re-wrap the text and stop matching what the engine
559
- * paginated, so what is on screen would no longer be what would print.
560
- *
561
- * A transform does not affect layout, so the stage is given the scaled
562
- * footprint explicitly - measured off the drawing rather than worked out
563
- * from the page, because the gutter and the rulers are part of what has to
564
- * fit and only the browser knows how wide they came out.
565
- */
566
- function applyZoom() {
567
- surface.style.transformOrigin = 'top left';
568
- surface.style.transform = `scale(${state.zoom})`;
569
-
570
- const width = surface.offsetWidth;
571
- const height = surface.offsetHeight;
572
-
573
- /** jsdom lays nothing out, and neither does a canvas nobody has drawn yet */
574
- if (width && height) {
575
- stage.style.width = `${width * state.zoom}px`;
576
- stage.style.height = `${height * state.zoom}px`;
577
- }
578
-
579
- refreshZoom();
580
- }
581
-
582
-
583
- function refreshZoom() {
584
- /**
585
- * Fit width has no step to light, and setFitWidth has already said so -
586
- * writing a percentage over it here would take the label away from the
587
- * mode that is actually on.
588
- */
589
- if (zoomPicker && !state.fitWidth) {
590
- const exact = ZOOM_STEPS.find(
591
- step => Math.abs(step - state.zoom) < 1e-9);
592
-
593
- zoomPicker.value = exact !== undefined ? String(exact) : 'fit';
594
- }
595
-
596
- bar.querySelector('[data-role="zoom-out"]').disabled =
597
- !state.fitWidth && state.zoom <= MIN_ZOOM;
598
- bar.querySelector('[data-role="zoom-in"]').disabled =
599
- !state.fitWidth && state.zoom >= MAX_ZOOM;
600
- }
601
-
602
-
603
- function setZoom(next) {
604
- state.fitWidth = false;
605
- state.zoom = Math.min(Math.max(next, MIN_ZOOM), MAX_ZOOM);
606
- applyZoom();
607
- }
608
-
609
-
610
- /** the widest scale that still fits the canvas, less its own padding */
611
- function setFitWidth() {
612
- state.fitWidth = true;
613
- if (zoomPicker) zoomPicker.value = 'fit';
614
-
615
- const available = canvas.clientWidth - 48;
616
- const natural = surface.offsetWidth;
617
-
618
- if (available > 0 && natural > 0) {
619
- state.zoom = Math.min(Math.max(available / natural, MIN_ZOOM), MAX_ZOOM);
620
- }
621
-
622
- applyZoom();
623
- }
624
-
625
-
626
- /** to the neighbouring preset rather than a blind multiply */
627
- function stepZoom(direction) {
628
- const from = state.zoom;
629
-
630
- const next = direction > 0
631
- ? ZOOM_STEPS.find(step => step > from + 1e-9)
632
- : [...ZOOM_STEPS].reverse().find(step => step < from - 1e-9);
633
-
634
- setZoom(next ?? from);
635
- }
636
-
637
-
638
- function flashBand(type) {
639
- clearTimeout(flashBand.timer);
640
- markTarget(type);
641
-
642
- flashBand.timer = setTimeout(() => markTarget(null), 1200);
643
- }
644
-
645
-
646
- /* ---------------- the right-click pill ---------------- */
647
-
648
- /** the open menu, or null */
649
- let menu = null;
650
-
651
-
652
- function closeMenu() {
653
- menu?.remove();
654
- menu = null;
655
- }
656
-
657
-
658
- /**
659
- * Opens the pill at a point on screen.
660
- *
661
- * Drawn first and measured second: what it offers decides how wide it is,
662
- * and it cannot be kept inside the page area without knowing that.
663
- *
664
- * @param {number} clientX
665
- * @param {number} clientY
666
- */
667
- function openMenu(clientX, clientY) {
668
- closeMenu();
669
-
670
- main.insertAdjacentHTML('beforeend', drawMenu(menuActions({
671
- count: state.selection.length,
672
- canPaste: state.clipboard.length > 0,
673
- /** a copy of a table would be the second one this report cannot hold */
674
- canDuplicate: !selectedItems().some(item => item.type === 'table')
675
- })));
676
-
677
- menu = main.querySelector('[data-role="menu"]');
678
-
679
- /**
680
- * Bound to the pill, not to the page area: a delegated listener out
681
- * there answers for the tool strip as well, and every add would run
682
- * twice.
683
- */
684
- menu.addEventListener('click', onMenuClick);
685
-
686
- const bounds = main.getBoundingClientRect();
687
- const box = menu.getBoundingClientRect();
688
-
689
- const at = menuPosition(
690
- { x: clientX - bounds.left, y: clientY - bounds.top },
691
- { width: box.width, height: box.height },
692
- { width: bounds.width, height: bounds.height }
693
- );
694
-
695
- menu.style.left = `${at.left}px`;
696
- menu.style.top = `${at.top}px`;
697
-
698
- /** so escape and the arrow keys have somewhere to be aimed */
699
- menu.querySelector('button:not([disabled])')?.focus();
700
- }
701
-
702
-
703
- /**
704
- * A right click acts on what is under it. An item that is not selected
705
- * becomes the selection first - otherwise Delete would take whatever
706
- * happened to be selected elsewhere, which is how a layout gets lost.
707
- */
708
- function onContextMenu(event) {
709
- if (state.mode !== 'design') return;
710
-
711
- event.preventDefault();
712
-
713
- const node = event.target.closest?.('[data-item-id]');
714
- const bandType = node?.closest('[data-band-type]')?.dataset.bandType ?? null;
715
-
716
- if (node && bandType) {
717
- const where = { band: bandType, id: node.dataset.itemId };
718
- const already = state.selection
719
- .some(one => one.band === where.band && one.id === where.id);
720
-
721
- if (!already) setSelection(where);
722
- } else {
723
- setSelection(null);
724
- }
725
-
726
- openMenu(event.clientX, event.clientY);
727
- }
728
-
729
-
730
- function onMenuClick(event) {
731
- const node = event.target.closest?.('[data-action]');
732
- if (!node || node.disabled) return;
733
-
734
- event.preventDefault();
735
-
736
- /** closed first: what follows redraws, and a stale pill would outlive it */
737
- closeMenu();
738
- act(node.dataset.action, node.dataset);
739
- }
740
-
741
-
742
- /** anything that is not the pill closes it */
743
- function onDocumentDown(event) {
744
- if (menu && !menu.contains(event.target)) closeMenu();
745
- }
746
-
747
-
748
- function onMenuKey(event) {
749
- if (menu && event.key === 'Escape') closeMenu();
750
- }
751
-
752
-
753
- function act(action, data) {
754
- const item = selected();
755
-
756
- switch (action) {
757
- case 'add-text': {
758
- const type = targetBand(state.layout, primary());
759
- if (!type) return;
760
-
761
- place(type, createText(state.layout, findBand(state.layout, type)));
762
- return;
763
- }
764
-
765
- case 'add-box': {
766
- const type = targetBand(state.layout, primary());
767
- if (!type) return;
768
-
769
- place(type, createBox(state.layout, findBand(state.layout, type)));
770
- return;
771
- }
772
-
773
- case 'add-line': {
774
- const type = targetBand(state.layout, primary());
775
- if (!type) return;
776
-
777
- place(type, createLine(
778
- state.layout, findBand(state.layout, type), data?.orientation));
779
- return;
780
- }
781
-
782
- case 'add-field': {
783
- /**
784
- * Unlike text and table, this chooses its own band - a total
785
- * belongs in a footer, and the alternative is inserting it into
786
- * the detail band and asking the user to drag it somewhere it
787
- * will actually resolve.
788
- */
789
- askToken(root, state.layout, primary()?.band ?? null).then(chosen => {
790
- if (!chosen) return;
791
-
792
- const band = findBand(state.layout, chosen.band);
793
- if (!band) return;
794
-
795
- const made = createText(state.layout, band);
796
-
797
- made.value = chosen.value;
798
- made.w = chosen.w;
799
- made.style.align = chosen.align;
800
-
801
- place(chosen.band, made);
802
- });
803
- return;
804
- }
805
-
806
- case 'add-table': {
807
- const type = targetBand(state.layout, primary());
808
- if (!type) return;
809
-
810
- /**
811
- * The engine binds the dataset to one table (validate.js says
812
- * so). Refused here as well as there, so the answer arrives
813
- * when the tool is pressed rather than as a problem in the
814
- * corner after the table has been drawn.
815
- */
816
- if (!canAddTable(state.layout)) {
817
- flashStatus(
818
- 'This report already has a table - a report binds one',
819
- { ms: 3000 }
820
- );
821
- return;
822
- }
823
-
824
- /**
825
- * A table is asked about first: how many columns it starts with
826
- * is the one thing that cannot be dragged into place afterwards
827
- * without a trip through the rail for each of them.
828
- */
829
- askColumns(root).then(columns => {
830
- if (columns == null) return;
831
-
832
- place(type, createTable(
833
- state.layout, findBand(state.layout, type), columns));
834
- });
835
- return;
836
- }
837
-
838
- case 'duplicate-item': {
839
- if (!state.selection.length) return;
840
-
841
- /**
842
- * Read the selection before adding anything: duplicateItem
843
- * appends to the same band, and a copy made from a copy would
844
- * cascade down the page for as long as the loop ran.
845
- */
846
- const sources = [...state.selection];
847
- const copies = [];
848
-
849
- for (const one of sources) {
850
- const made = duplicateItem(state.layout, one.band, one.id);
851
- if (made) copies.push({ band: one.band, id: made.id });
852
- }
853
-
854
- if (!copies.length) {
855
- if (sources.some(one => itemAt(one)?.type === 'table')) {
856
- flashStatus(
857
- 'A report binds one table, so it cannot be copied',
858
- { ms: 3000 }
859
- );
860
- }
861
- return;
862
- }
863
-
864
- /**
865
- * The copies are what is selected afterwards, not the originals:
866
- * the next thing anyone does to a duplicate is move it, and
867
- * leaving the original selected would move the wrong one.
868
- */
869
- state.selection = copies;
870
- restructured(`duplicate:${copies.map(c => c.id).join(',')}`);
871
-
872
- flashBand([...new Set(copies.map(c => c.band))]);
873
- return;
874
- }
875
-
876
- case 'dismiss-problems': {
877
- state.dismissed = validateLayout(state.layout);
878
- toasts.innerHTML = '';
879
- return;
880
- }
881
-
882
- case 'copy-items': {
883
- if (!state.selection.length) return;
884
-
885
- const taken = state.selection
886
- .map(one => ({ band: one.band, item: itemAt(one) }))
887
- .filter(entry => entry.item)
888
- .map(entry => ({
889
- band: entry.band,
890
- item: structuredClone(entry.item)
891
- }));
892
-
893
- if (!taken.length) return;
894
-
895
- state.clipboard = taken;
896
-
897
- /**
898
- * Nothing on screen changes when a copy is taken, so the bar
899
- * says it did - otherwise ctrl+C is a keystroke with no answer.
900
- */
901
- flashStatus(
902
- taken.length > 1 ? `Copied ${taken.length} items` : 'Copied',
903
- { ms: 2000 }
904
- );
905
- return;
906
- }
907
-
908
- case 'paste-items': {
909
- if (!state.clipboard.length) return;
910
-
911
- /** onto the band being worked in, which is where a paste is expected */
912
- const type = targetBand(state.layout, primary());
913
- if (!type) return;
914
-
915
- const made = pasteItems(state.layout, type, state.clipboard);
916
- if (!made.length) return;
917
-
918
- /**
919
- * The clipboard now holds where these landed, so pressing paste
920
- * again steps down from the last copy rather than putting a
921
- * second one exactly on top of it.
922
- */
923
- state.clipboard = made.map(item => ({
924
- band: type,
925
- item: structuredClone(item)
926
- }));
927
-
928
- state.selection = made.map(item => ({ band: type, id: item.id }));
929
- restructured(`paste:${made.map(i => i.id).join(',')}`);
930
-
931
- flashBand(type);
932
- return;
933
- }
934
-
935
- case 'delete-item': {
936
- if (!state.selection.length) return;
937
-
938
- const gone = state.selection.map(one => one.id).join(',');
939
-
940
- for (const one of state.selection) {
941
- removeItem(state.layout, one.band, one.id);
942
- }
943
-
944
- state.selection = [];
945
- restructured(`delete:${gone}`);
946
- return;
947
- }
948
-
949
- case 'add-column':
950
- if (item?.type !== 'table') return;
951
- addColumn(item);
952
- restructured(`column:add:${item.id}`);
953
- return;
954
-
955
- case 'remove-column':
956
- if (item?.type !== 'table') return;
957
- if (removeColumn(item, Number(data.index))) {
958
- restructured(`column:remove:${item.id}`);
959
- }
960
- return;
961
-
962
- case 'undo': {
963
- const previous = history.undo();
964
- if (previous) replaceLayout(previous, { dirty: true });
965
- return;
966
- }
967
-
968
- case 'redo': {
969
- const next = history.redo();
970
- if (next) replaceLayout(next, { dirty: true });
971
- return;
972
- }
973
-
974
- case 'open': return openReport();
975
- case 'save': return saveReport();
976
- case 'data': return editData();
977
- case 'open-window': return openInWindow();
978
-
979
- case 'zoom-in': return stepZoom(1);
980
- case 'zoom-out': return stepZoom(-1);
981
-
982
- case 'toggle-rulers': {
983
- state.rulers = !state.rulers;
984
- draw();
985
- refreshBar();
986
- return;
987
- }
988
- case 'toggle-preview': return togglePreview();
989
- }
990
- }
991
-
992
-
993
- /**
994
- * Whether the report being edited may be closed.
995
- *
996
- * A report with no unsaved changes closes without a word - a question
997
- * nobody needs to answer is one they stop reading, and then they stop
998
- * reading the one that mattered too.
999
- *
1000
- * @returns {Promise<boolean>}
1001
- */
1002
- async function mayClose() {
1003
- if (!state.dirty) return true;
1004
-
1005
- return askDiscard(root, state.layout?.name ?? '');
1006
- }
1007
-
1008
-
1009
- /**
1010
- * Opens another report.
1011
- *
1012
- * Asked before the list is fetched rather than after one is chosen: what
1013
- * the user is deciding is whether to leave this report, and that is settled
1014
- * at the click, not three steps into a flow they would then have to unwind.
1015
- *
1016
- * The list comes from the server, so this is also where the designer finds
1017
- * out there is no server - and says so in terms of what to do about it,
1018
- * rather than letting a failed fetch surface as nothing happening.
1019
- */
1020
- async function openReport() {
1021
- if (!await mayClose()) return;
1022
-
1023
- let reports;
1024
-
1025
- try {
1026
- reports = await files.list();
1027
- } catch (error) {
1028
- return complain(error);
1029
- }
1030
-
1031
- const chosen = await askReport(root, reports);
1032
- if (!chosen) return;
1033
-
1034
- if (chosen.blank) {
1035
- replaceLayout(blankLayout(), { id: null, dirty: false });
1036
- history.reset(state.layout);
1037
- refreshBar();
1038
- return;
1039
- }
1040
-
1041
- try {
1042
- const loaded = await files.load(chosen.id);
1043
-
1044
- replaceLayout(loaded, { id: chosen.id, dirty: false });
1045
- history.reset(state.layout);
1046
- refreshBar();
1047
- } catch (error) {
1048
- complain(error);
1049
- }
1050
- }
1051
-
1052
-
1053
- /**
1054
- * Saves the report, asking what to call it the first time.
1055
- *
1056
- * An invalid layout is saved anyway - a report half-designed is legitimately
1057
- * invalid, and refusing to keep somebody's work in progress is not a safety
1058
- * feature. The problems banner is already saying what is wrong.
1059
- */
1060
- async function saveReport() {
1061
- let saveId = state.id;
1062
-
1063
- if (!saveId) {
1064
- const named = await askName(root, state.layout.name ?? '');
1065
- if (!named) return;
1066
-
1067
- saveId = named.id;
1068
- state.layout.name = named.name;
1069
- }
1070
-
1071
- try {
1072
- await files.save(saveId, state.layout);
1073
-
1074
- state.id = saveId;
1075
- state.dirty = false;
1076
- refreshBar();
1077
-
1078
- await seedData(saveId);
1079
- } catch (error) {
1080
- complain(error);
1081
- }
1082
- }
1083
-
1084
-
1085
- /**
1086
- * Writes a sample data file for a report that has none.
1087
- *
1088
- * Only when there is none. Once someone has put real figures in that file,
1089
- * every later save must leave it exactly alone - a designer that quietly
1090
- * replaced the host application's data with "Customer 1" would be worse
1091
- * than one that never offered to help.
1092
- */
1093
- async function seedData(saveId) {
1094
- if (!files.loadData || !files.saveData) return;
1095
-
1096
- try {
1097
- const existing = await files.loadData(saveId);
1098
- if (existing) return;
1099
-
1100
- await files.saveData(saveId, sampleData(state.layout));
1101
- } catch {
1102
- /**
1103
- * A report that saved but whose sample data did not is a working
1104
- * report. Complaining about the convenience would bury the fact
1105
- * that the thing being asked for succeeded.
1106
- */
1107
- }
1108
- }
1109
-
1110
-
1111
- /**
1112
- * Shows what data the report is asking for.
1113
- *
1114
- * Loaded from disk if it is there, and otherwise derived from the layout -
1115
- * so a report that has never been saved can still answer "what do I have to
1116
- * supply?", which is the question this exists for.
1117
- */
1118
- async function editData() {
1119
- let current = null;
1120
-
1121
- if (state.id && files.loadData) {
1122
- try {
1123
- current = await files.loadData(state.id);
1124
- } catch (error) {
1125
- return complain(error);
1126
- }
1127
- }
1128
-
1129
- const generated = current == null;
1130
- const edited = await askData(root, current ?? sampleData(state.layout), {
1131
- id: state.id, generated
1132
- });
1133
-
1134
- if (!edited) return;
1135
-
1136
- if (!state.id) {
1137
- return complain(new Error(
1138
- 'Save the report first - its data file is named after it.'));
1139
- }
1140
-
1141
- try {
1142
- await files.saveData(state.id, edited);
1143
- } catch (error) {
1144
- complain(error);
1145
- }
1146
- }
1147
-
1148
-
1149
- /**
1150
- * Runs the report, or goes back to arranging it.
1151
- *
1152
- * The data is fetched each time rather than cached, so a report previewed
1153
- * after its data file was edited shows the edit. It is the report's real
1154
- * data when there is some and the derived sample when there is not, which
1155
- * makes the preview work for a report nobody has supplied data for yet -
1156
- * the case it is most needed in.
1157
- */
1158
- /**
1159
- * Runs the report and opens it in a window of its own.
1160
- *
1161
- * This used to be a link to the preview screen, which reads the report off
1162
- * the disk - so it did nothing until the report had been saved, which is
1163
- * the wrong answer to "show me this". The window is built here from the
1164
- * design as it currently stands, so it works on the first keystroke of a
1165
- * report that has never been named.
1166
- */
1167
- function openInWindow() {
1168
- let paginated;
1169
-
1170
- try {
1171
- paginated = buildPages(state.layout, state.data ?? sampleData(state.layout));
1172
- } catch (error) {
1173
- complain(error);
1174
- return;
1175
- }
1176
-
1177
- const opened = openViewerWindow({
1178
- paginated,
1179
- title: state.layout?.name || 'Report'
1180
- });
1181
-
1182
- /** a browser that refused the window says nothing itself, so this does */
1183
- if (!opened) {
1184
- flashStatus(
1185
- 'The browser blocked the report window - allow pop-ups for this page',
1186
- { problem: true, ms: 6000 }
1187
- );
1188
- return;
1189
- }
1190
-
1191
- windows.add(opened);
1192
- }
1193
-
1194
-
1195
- /** the report windows this designer opened, so they go when it does */
1196
- const windows = new Set();
1197
-
1198
- /** the zoom menu, built once the bar exists */
1199
- let zoomPicker = null;
1200
-
1201
-
1202
- async function togglePreview() {
1203
- if (state.mode === 'preview') {
1204
- state.mode = 'design';
1205
- state.data = null;
1206
- drawMode();
1207
- return;
1208
- }
1209
-
1210
- let data = null;
1211
-
1212
- if (state.id && files.loadData) {
1213
- try {
1214
- data = await files.loadData(state.id);
1215
- } catch {
1216
- /** a preview on sample data beats no preview at all */
1217
- }
1218
- }
1219
-
1220
- state.data = data ?? sampleData(state.layout);
1221
- state.mode = 'preview';
1222
-
1223
- /** an outline over a paginated page points at nothing */
1224
- state.selection = [];
1225
- drawMode();
1226
- }
1227
-
1228
-
1229
- /** everything that differs between arranging a report and running it */
1230
- function drawMode() {
1231
- root.dataset.mode = state.mode;
1232
-
1233
- const button = bar.querySelector('[data-action="toggle-preview"]');
1234
- const running = state.mode === 'preview';
1235
-
1236
- button.innerHTML = icon(running ? 'design' : 'preview');
1237
- button.title = running ? 'Back to the design (ctrl+E)' : 'Run the report (ctrl+E)';
1238
- button.setAttribute('aria-label', button.title);
1239
- button.setAttribute('aria-pressed', String(running));
1240
-
1241
- draw();
1242
- drawRail();
1243
- refreshBar();
1244
- }
1245
-
1246
-
1247
- /** the server's own words, where the user is looking */
1248
- /**
1249
- * Says something in the bar for a moment, then puts the saved state back.
1250
- *
1251
- * Shared with complain() so there is one place that owns the status line -
1252
- * two timers writing to it independently is how a message ends up cleared
1253
- * by an error that arrived before it.
1254
- *
1255
- * @param {string} message
1256
- * @param {object} [options]
1257
- * @param {boolean} [options.problem] draws it as a failure
1258
- * @param {number} [options.ms] how long it stands
1259
- */
1260
- function flashStatus(message, { problem = false, ms = 6000 } = {}) {
1261
- const note = bar.querySelector('[data-role="status"]');
1262
-
1263
- note.textContent = message;
1264
- if (problem) note.dataset.problem = 'true';
1265
- else delete note.dataset.problem;
1266
-
1267
- clearTimeout(complain.timer);
1268
- complain.timer = setTimeout(() => {
1269
- delete note.dataset.problem;
1270
- refreshBar();
1271
- }, ms);
1272
- }
1273
-
1274
-
1275
- function complain(error) {
1276
- const message = error instanceof StoreError
1277
- ? error.message
1278
- : `Something went wrong: ${error?.message ?? error}`;
1279
-
1280
- flashStatus(message, { problem: true });
1281
- }
1282
-
1283
-
1284
- function toggleBand(type, on) {
1285
- if (on) addBand(state.layout, type);
1286
- else {
1287
- removeBand(state.layout, type);
1288
- /** the selection may have been standing on it */
1289
- state.selection = state.selection.filter(one => one.band !== type);
1290
- }
1291
-
1292
- restructured(`band:${type}`);
1293
- }
1294
-
1295
-
1296
- function setBandHeight(type, raw) {
1297
- const band = findBand(state.layout, type);
1298
- if (!band) return;
1299
-
1300
- const trimmed = String(raw).trim();
1301
-
1302
- if (trimmed === '') delete band.height;
1303
- else if (/^-?[\d.]+\s*%$/.test(trimmed)) band.height = trimmed;
1304
- else if (Number.isFinite(Number(trimmed))) band.height = Number(trimmed);
1305
- else return;
1306
-
1307
- /** the rail is not rebuilt - the box being typed into is in it */
1308
- draw();
1309
- record(`band-height:${type}`);
1310
- }
1311
-
1312
-
1313
- root.dataset.mode = state.mode;
1314
-
1315
- zoomPicker = createDropdown(bar.querySelector('[data-role="zoom-dropdown"]'));
1316
-
1317
- zoomPicker.addEventListener('change', () => {
1318
- if (zoomPicker.value === 'fit') setFitWidth();
1319
- else setZoom(Number(zoomPicker.value));
1320
- });
1321
-
1322
- /** fit width is a reading of the viewport, so it is taken again when it changes */
1323
- const onViewportResize = () => { if (state.fitWidth) setFitWidth(); };
1324
- const view = doc.defaultView ?? globalThis;
1325
-
1326
- view.addEventListener('resize', onViewportResize);
1327
-
1328
- /**
1329
- * The tab or the window closing, which is the other way to close a report.
1330
- *
1331
- * Nothing of ours can be shown here. A page may only ask the browser to put
1332
- * its own question - "leave site?" - and browsers stopped letting the page
1333
- * word it years ago, because a page that could write that text could write
1334
- * anything into a box the user reads as the browser's. So askDiscard cannot
1335
- * be reached from here, and the choice is this prompt or no prompt at all.
1336
- *
1337
- * preventDefault is the modern spelling and returnValue the old one; both
1338
- * are set because which one a browser honours still varies. Neither shows
1339
- * anything unless the user has interacted with the page - a rule against
1340
- * pages that trap people who only glanced at them, and no obstacle to
1341
- * somebody who has been dragging text boxes around.
1342
- *
1343
- * Registered by default and turned off with `guardUnload: false`: a host
1344
- * embedding the designer in a larger application may have its own unsaved
1345
- * state and its own prompt, and two prompts for one close is worse than the
1346
- * one it already had.
1347
- */
1348
- const onBeforeUnload = (event) => {
1349
- if (!state.dirty) return;
1350
-
1351
- event.preventDefault();
1352
- event.returnValue = '';
1353
- };
1354
-
1355
- if (guardUnload) view.addEventListener('beforeunload', onBeforeUnload);
1356
-
1357
- draw();
1358
- drawRail();
1359
- refreshBar();
1360
-
1361
- const detach = attachEditing({
1362
- canvas,
1363
- getLayout: () => state.layout,
1364
- getSelection: () => state.selection,
1365
- select: setSelection,
1366
- remove: () => act('delete-item'),
1367
-
1368
- /**
1369
- * Alt-drag. The copies become the selection, so the drag that follows
1370
- * carries them and leaves the originals where they were put.
1371
- */
1372
- duplicate: () => {
1373
- const before = state.selection.map(one => one.id).join(',');
1374
- act('duplicate-item');
1375
-
1376
- return state.selection.map(one => one.id).join(',') !== before;
1377
- },
1378
- /**
1379
- * render.js emits the same data-item-id attributes items.js gives the
1380
- * canvas - which is the point of one drawing path, and also means a
1381
- * click on a rendered page would otherwise select and drag the item
1382
- * behind it.
1383
- */
1384
- enabled: () => state.mode === 'design',
1385
-
1386
- /**
1387
- * Screen pixels are page pixels divided by this. Without it a drag at
1388
- * 200% moves an item twice as far as the pointer went.
1389
- */
1390
- getZoom: () => state.zoom,
1391
-
1392
- /** no rulers, no guides to drag off them and nothing to snap to */
1393
- rulers: () => state.rulers,
1394
- /**
1395
- * A drag moves x and y, which the rail is showing - so the controls are
1396
- * refreshed rather than rebuilt. Rebuilding them under a cursor takes
1397
- * the focus and the caret with it.
1398
- */
1399
- onTarget: markTarget,
1400
-
1401
- /**
1402
- * What the drag has lined up with. Drawn straight rather than through
1403
- * draw(), because it changes sixty times a second and rebuilding the
1404
- * sheet that often is what patch() exists to avoid.
1405
- */
1406
- onGuides: drawAlignment,
1407
-
1408
- commit: ({ live, band, key = null }) => {
1409
- /**
1410
- * A drag that ended over another band moves the item into it. Until
1411
- * now the item followed the pointer across the boundary and stayed
1412
- * in the band it started in, which is the sort of thing that is only
1413
- * noticed once the report prints in the wrong place.
1414
- */
1415
- /**
1416
- * Each selected item goes to the band it actually landed in, rather
1417
- * than to one band chosen for the whole group - what you see on the
1418
- * page is where they end up.
1419
- */
1420
- if (!live && band?.length) {
1421
- let moved = false;
1422
-
1423
- state.selection = state.selection.map(one => {
1424
- const item = itemAt(one);
1425
- const to = item ? bandUnder(state.layout, one.band, item) : null;
1426
-
1427
- if (to && to !== one.band
1428
- && moveItemToBand(state.layout, one.band, to, one.id)) {
1429
- moved = true;
1430
- return { band: to, id: one.id };
1431
- }
1432
-
1433
- return one;
1434
- });
1435
-
1436
- if (moved) drawRail();
1437
- }
1438
-
1439
- live ? patch() : draw();
1440
- syncPanel(panel, selected(), state.layout);
1441
-
1442
- /**
1443
- * Only the finished gesture is a step. A drag reports sixty times a
1444
- * second, and each of those as an undo step would bury the edit
1445
- * before it.
1446
- */
1447
- if (!live) {
1448
- record(key ?? `move:${state.selection.map(o => o.id).join(',')}`);
1449
- }
1450
- }
1451
- });
1452
-
1453
- const detachPanel = attachPanel({
1454
- panel,
1455
- getTarget: () => {
1456
- const item = selected();
1457
- return item
1458
- ? { target: item, fields: allFields(item) }
1459
- : { target: state.layout, fields: allReportFields(state.layout) };
1460
- },
1461
- getItem: selected,
1462
- /**
1463
- * A typed edit redraws the page but never the rail: the control being
1464
- * typed into is in it.
1465
- *
1466
- * Unless the edit changed which controls there are - picking a named
1467
- * paper size puts the width and height boxes away - in which case the
1468
- * rail is rebuilt. Safe here because the control that asked for it is a
1469
- * dropdown, not something anyone is mid-word in.
1470
- */
1471
- changed: (key, { rebuild = false } = {}) => {
1472
- draw();
1473
- if (rebuild) drawRail();
1474
- record(key);
1475
- },
1476
- act,
1477
- toggleBand,
1478
- setBandHeight
1479
- });
1480
-
1481
- /** the bar and the footer both carry actions; the rail wires its own */
1482
- function onChromeClick(event) {
1483
- const node = event.target.closest?.('[data-action]');
1484
- if (!node) return;
1485
-
1486
- event.preventDefault();
1487
- act(node.dataset.action, node.dataset);
1488
- }
1489
-
1490
- /**
1491
- * Whether a keystroke belongs to this designer.
1492
- *
1493
- * Anything aimed inside it, plainly. And anything aimed at nothing at all -
1494
- * the page has just loaded, or a click landed on the canvas, and the body
1495
- * has the focus by default. Without that second case the shortcuts were
1496
- * dead until somebody happened to click a button, because a click on the
1497
- * design itself focuses nothing and the keystroke never reached this
1498
- * element to begin with.
1499
- *
1500
- * @param {KeyboardEvent} event
1501
- * @returns {boolean}
1502
- */
1503
- function ours(event) {
1504
- if (root.contains(event.target)) return true;
1505
-
1506
- return event.target === doc.body || event.target === doc.documentElement;
1507
- }
1508
-
1509
-
1510
- /**
1511
- * Takes the focus when a click lands on something that cannot hold it.
1512
- *
1513
- * The canvas is a div, so clicking the design leaves the caret wherever it
1514
- * was - which, after a trip to the properties rail, is a text box. Then `z`
1515
- * types a z instead of zooming, which is correct of the shortcut and
1516
- * surprising to everyone.
1517
- *
1518
- * @param {PointerEvent} event
1519
- */
1520
- function takeFocus(event) {
1521
- const holder = event.target.closest?.(
1522
- 'input, textarea, select, button, a, label, [tabindex]');
1523
-
1524
- /**
1525
- * Root itself carries a tabindex now, so it matches that selector - and
1526
- * it is the thing being focused, not a reason not to. A browser does
1527
- * this walk on its own for a container that can hold focus; this is
1528
- * here so the behaviour is the designer's rather than the browser's.
1529
- */
1530
- if (holder && holder !== root) return;
1531
-
1532
- root.focus({ preventScroll: true });
1533
- }
1534
-
1535
-
1536
- /**
1537
- * The shortcuts everyone tries first. Bound on the document so they are
1538
- * heard wherever the focus is, and answered only for this designer - see
1539
- * `ours` - so a second one on the same page keeps its own.
1540
- */
1541
- function onShortcut(event) {
1542
- if (!ours(event)) return;
1543
-
1544
- const key = event.key.toLowerCase();
1545
-
1546
- /**
1547
- * Zoom is one key: z in, alt+z out.
1548
- *
1549
- * Before the ctrl guard because it is not a ctrl shortcut - and it must
1550
- * stay out of ctrl's way, or it would take undo. Held back while a
1551
- * field has the caret, for the same reason copy is: the rail is full of
1552
- * boxes people type the letter z into.
1553
- */
1554
- if (key === 'z' && !event.ctrlKey && !event.metaKey) {
1555
- if (event.target.closest?.('input, textarea, select')) return;
1556
-
1557
- event.preventDefault();
1558
- stepZoom(event.altKey ? -1 : 1);
1559
- return;
1560
- }
1561
-
1562
- if (!(event.ctrlKey || event.metaKey)) return;
1563
-
1564
- /**
1565
- * Copy and paste stay the browser's while a field has the caret, or
1566
- * while there is text selected. Taking them would break copying a value
1567
- * out of the rail, which people do far more often than they copy an
1568
- * item - and a shortcut that works everywhere except where you need it
1569
- * is worse than one that was never bound.
1570
- */
1571
- if (key === 'c' || key === 'v') {
1572
- if (event.target.closest?.('input, textarea, select')) return;
1573
- if (key === 'c' && String(globalThis.getSelection?.() ?? '')) return;
1574
-
1575
- event.preventDefault();
1576
- act(key === 'c' ? 'copy-items' : 'paste-items');
1577
- return;
1578
- }
1579
-
1580
- if (key === 's') {
1581
- event.preventDefault();
1582
- act('save');
1583
- return;
1584
- }
1585
-
1586
- if (key === 'o') {
1587
- event.preventDefault();
1588
- act('open');
1589
- return;
1590
- }
1591
-
1592
- if (key === 'e') {
1593
- event.preventDefault();
1594
- act('toggle-preview');
1595
- return;
1596
- }
1597
-
1598
- /**
1599
- * ctrl+0 is the way back to 100% from wherever the z key has got to.
1600
- * The stepping itself is z's; ctrl +/- is left to the browser here,
1601
- * which is not something the viewer next door does - a report being
1602
- * arranged is scrolled and dragged far more than one being read, and a
1603
- * modifier on every zoom is one modifier too many for that.
1604
- */
1605
- if (key === '0') {
1606
- event.preventDefault();
1607
- setZoom(1);
1608
- return;
1609
- }
1610
-
1611
- if (key === 'z') {
1612
- event.preventDefault();
1613
-
1614
- /**
1615
- * ctrl+alt+z redoes, as well as the ctrl+shift+z every editor has.
1616
- * Two spellings of one thing rather than a choice between them:
1617
- * shift+z is the one people arrive with, and alt+z is the one that
1618
- * matches the zoom pair next door - z in, alt+z out, so alt is
1619
- * already the "and back again" key on this keyboard.
1620
- *
1621
- * Plain alt+z is the zoom, and cannot be reached from here: the
1622
- * branch at the top of this function takes it while ctrl is up, and
1623
- * nothing gets this far without ctrl or meta down.
1624
- */
1625
- act(event.shiftKey || event.altKey ? 'redo' : 'undo');
1626
- return;
1627
- }
1628
-
1629
- if (key === 'y') {
1630
- event.preventDefault();
1631
- act('redo');
1632
- return;
1633
- }
1634
-
1635
- if (key === 'd') {
1636
- event.preventDefault();
1637
- act('duplicate-item');
1638
- }
1639
- }
1640
-
1641
- bar.addEventListener('click', onChromeClick);
1642
- foot.addEventListener('click', onChromeClick);
1643
- toasts.addEventListener('click', onChromeClick);
1644
- root.addEventListener('pointerdown', takeFocus);
1645
- doc.addEventListener('keydown', onShortcut);
1646
-
1647
- canvas.addEventListener('contextmenu', onContextMenu);
1648
- /** the pill is pinned to the page area, so a scroll leaves it behind */
1649
- canvas.addEventListener('scroll', closeMenu);
1650
- doc.addEventListener('pointerdown', onDocumentDown);
1651
- doc.addEventListener('keydown', onMenuKey);
1652
-
1653
- return {
1654
- /** the layout as it currently stands - the thing onSave will be given */
1655
- get layout() { return state.layout; },
1656
-
1657
- /** 'design' or 'preview' */
1658
- get mode() { return state.mode; },
1659
-
1660
- /** run the report, or go back to arranging it */
1661
- togglePreview,
1662
-
1663
- /** the data the report is asking for, derived from the layout */
1664
- get sampleData() { return sampleData(state.layout); },
1665
-
1666
- /** the item being edited, as `{ band, id }`, or null */
1667
- /** the item the rail describes - the most recently selected */
1668
- get selection() { return primary(); },
1669
-
1670
- /** every selected item, oldest first */
1671
- get selections() { return [...state.selection]; },
1672
-
1673
- select: setSelection,
1674
-
1675
- /** the filename stem this report is saved under, or null */
1676
- get id() { return state.id; },
1677
-
1678
- /** whether there are changes the disk has not seen */
1679
- get dirty() { return state.dirty; },
1680
-
1681
- /** swap the report being edited */
1682
- open(next, openId = null) {
1683
- replaceLayout(
1684
- isEmptyLayout(next) ? blankLayout() : next,
1685
- { id: openId, dirty: false });
1686
-
1687
- history.reset(state.layout);
1688
- refreshBar();
1689
-
1690
- return validateLayout(state.layout);
1691
- },
1692
-
1693
- /** save it where it came from, asking for a name the first time */
1694
- save: saveReport,
1695
-
1696
- redraw: draw,
1697
-
1698
- destroy() {
1699
- detach();
1700
- detachPanel();
1701
- bar.removeEventListener('click', onChromeClick);
1702
- foot.removeEventListener('click', onChromeClick);
1703
- toasts.removeEventListener('click', onChromeClick);
1704
- root.removeEventListener('pointerdown', takeFocus);
1705
- doc.removeEventListener('keydown', onShortcut);
1706
- canvas.removeEventListener('contextmenu', onContextMenu);
1707
- canvas.removeEventListener('scroll', closeMenu);
1708
- doc.removeEventListener('pointerdown', onDocumentDown);
1709
- doc.removeEventListener('keydown', onMenuKey);
1710
- (doc.defaultView ?? globalThis)
1711
- .removeEventListener('resize', onViewportResize);
1712
- view.removeEventListener('beforeunload', onBeforeUnload);
1713
- zoomPicker?.destroy();
1714
- closeMenu();
1715
- clearTimeout(complain.timer);
1716
- clearTimeout(flashBand.timer);
1717
- /** a report window shows what was passed to it; it cannot outlive this */
1718
- for (const opened of windows) opened.destroy();
1719
- windows.clear();
1720
-
1721
- root.innerHTML = '';
1722
- root.classList.remove('report-designer');
1723
- }
1724
- };
1725
- }
1726
-
1727
-
1728
- function chrome(layout) {
1729
- const size = layout.page
1730
- ? `${layout.page.width} &times; ${layout.page.height}`
1731
- : '';
1732
-
1733
- return `
1734
- <header class="dz-bar" data-role="bar">
1735
- <span class="dz-brand">Report Studio</span>
1736
-
1737
- <span class="dz-title">
1738
- <span class="dz-name" data-role="name">${escapeText(layout.name ?? '')}</span>
1739
- <span class="dz-status" data-role="status">Not saved yet</span>
1740
- </span>
1741
-
1742
- <div class="dz-bar-group">
1743
- <button type="button" class="dz-tool" data-role="undo" data-action="undo"
1744
- title="Undo (ctrl+Z)" aria-label="Undo" disabled
1745
- >${icon('undo')}</button>
1746
- <button type="button" class="dz-tool" data-role="redo" data-action="redo"
1747
- title="Redo (ctrl+alt+Z or ctrl+shift+Z)" aria-label="Redo" disabled
1748
- >${icon('redo')}</button>
1749
- </div>
1750
-
1751
- <div class="dz-bar-group">
1752
- <button type="button" class="dz-tool" data-action="open"
1753
- title="Open a report (ctrl+O)" aria-label="Open a report"
1754
- >${icon('open')}</button>
1755
- <button type="button" class="dz-tool" data-action="save"
1756
- title="Save (ctrl+S)" aria-label="Save"
1757
- >${icon('save')}</button>
1758
- <button type="button" class="dz-tool" data-action="data"
1759
- title="The data this report needs" aria-label="Report data"
1760
- >${icon('data')}</button>
1761
- </div>
1762
-
1763
- <div class="dz-bar-group">
1764
- <button type="button" class="dz-tool" data-role="rulers"
1765
- data-action="toggle-rulers"
1766
- title="Rulers and guides - drag off a ruler to place one"
1767
- aria-label="Rulers and guides" aria-pressed="false"
1768
- >${icon('ruler')}</button>
1769
- <button type="button" class="dz-tool" data-action="toggle-preview"
1770
- title="Run the report (ctrl+E)" aria-label="Run the report"
1771
- aria-pressed="false"
1772
- >${icon('preview')}</button>
1773
-
1774
- <!--
1775
- A button, not a link: the window is built from the design as it
1776
- stands rather than fetched from a URL, so it works on a report
1777
- that has never been saved - which a link to the preview screen
1778
- could not, because that screen reads the report off the disk.
1779
- -->
1780
- <button type="button" class="dz-tool" data-role="open-preview"
1781
- data-action="open-window"
1782
- title="Open the report in its own window"
1783
- aria-label="Open the report in its own window"
1784
- >${icon('external')}</button>
1785
- </div>
1786
-
1787
- <span class="dz-pages" data-role="pages"></span>
1788
- <span class="dz-size" data-role="size">${size}</span>
1789
-
1790
- <!--
1791
- The same three controls the viewer has, in the same order and with
1792
- the same shortcuts. A designer and a preview of the same report
1793
- should not zoom differently.
1794
- -->
1795
- <div class="dz-bar-group dz-zoom-group">
1796
- <button type="button" class="dz-tool" data-role="zoom-out"
1797
- data-action="zoom-out"
1798
- title="Zoom out (alt+Z)" aria-label="Zoom out">&#8722;</button>
1799
-
1800
- <div class="dropdown" data-role="zoom-dropdown">
1801
- <button type="button" class="dropdown-trigger" data-role="zoom"
1802
- aria-haspopup="listbox" aria-expanded="false"
1803
- aria-label="Zoom level">
1804
- <span class="dropdown-value">100%</span>
1805
- <span class="dropdown-caret" aria-hidden="true"></span>
1806
- </button>
1807
-
1808
- <ul class="dropdown-menu" data-role="zoom-menu" role="listbox"
1809
- aria-label="Zoom level" hidden>
1810
- <li class="dropdown-item" role="option" tabindex="-1"
1811
- data-value="fit">Fit width</li>
1812
- ${ZOOM_STEPS.map(step => `
1813
- <li class="dropdown-item" role="option" tabindex="-1"
1814
- data-value="${step}"${step === 1 ? ' data-selected="true"' : ''}
1815
- >${Math.round(step * 100)}%</li>`).join('')}
1816
- </ul>
1817
- </div>
1818
-
1819
- <button type="button" class="dz-tool" data-role="zoom-in"
1820
- data-action="zoom-in"
1821
- title="Zoom in (Z)" aria-label="Zoom in">&#43;</button>
1822
- </div>
1823
- </header>
1824
-
1825
- <div class="dz-body">
1826
- <div class="dz-main">
1827
- <div class="dz-canvas" data-role="canvas">
1828
- <!--
1829
- Two boxes for one job. The inner one is scaled, and a
1830
- transform changes nothing about layout - so at 200% there
1831
- would be nothing to scroll. The outer one is given the
1832
- scaled size in px, and is what the canvas scrolls.
1833
- -->
1834
- <div class="dz-stage" data-role="stage">
1835
- <div class="dz-zoom-layer" data-role="zoom-layer"></div>
1836
- </div>
1837
- </div>
1838
-
1839
- <!--
1840
- The tools sit under the page rather than in the bar: the bar is
1841
- about the report as a whole, and these act on the band you are
1842
- looking at. Icon-only, so the strip stays out of the way of the
1843
- thing being designed - the label lives on the button for a
1844
- screen reader and in the tooltip for everyone else.
1845
- -->
1846
- <footer class="dz-foot" data-role="foot">
1847
- <button type="button" class="dz-tool" data-action="add-text"
1848
- title="Add a text box" aria-label="Add a text box"
1849
- >${icon('text')}</button>
1850
- <button type="button" class="dz-tool" data-role="add-table"
1851
- data-action="add-table"
1852
- title="Add a table" aria-label="Add a table"
1853
- >${icon('table')}</button>
1854
- <button type="button" class="dz-tool" data-action="add-line"
1855
- title="Add a line" aria-label="Add a line"
1856
- >${icon('line')}</button>
1857
- <button type="button" class="dz-tool" data-action="add-box"
1858
- title="Add a box" aria-label="Add a box"
1859
- >${icon('box')}</button>
1860
- <button type="button" class="dz-tool" data-action="add-field"
1861
- title="Insert a page number, date or total"
1862
- aria-label="Insert a field"
1863
- >${icon('field')}</button>
1864
- </footer>
1865
-
1866
- <!--
1867
- The corner messages, in the page area rather than the window.
1868
- Pinned to the window they would hang over the properties rail -
1869
- which is where the band switches are, and so where most of what
1870
- the validator complains about is actually fixed.
1871
- -->
1872
- <div class="dz-toasts" data-role="toasts"></div>
1873
- </div>
1874
-
1875
- <aside class="dz-panel" data-role="panel" aria-label="Properties"></aside>
1876
- </div>`;
1877
- }
1878
-
1879
-
1880
- /**
1881
- * The validator already writes in the user's terms - "bands[2].items[0].value
1882
- * must be a string" - so this only has to show the list rather than translate it.
1883
- */
1884
- /**
1885
- * An item id comes from a hand-written layout file, so it can hold anything.
1886
- * CSS.escape is absent in some test environments, hence the fallback.
1887
- */
1888
- function cssEscape(value) {
1889
- const text = String(value);
1890
- return globalThis.CSS?.escape ? CSS.escape(text) : JSON.stringify(text).slice(1, -1);
1891
- }
1892
-
1893
-
1894
- function escapeText(value) {
1895
- if (value == null) return '';
1896
- return String(value)
1897
- .replace(/&/g, '&amp;')
1898
- .replace(/</g, '&lt;')
1899
- .replace(/>/g, '&gt;');
1900
- }
1
+ /**
2
+ * designer.js is the package's designer entry point.
3
+ *
4
+ * createDesigner({ mount: '#report-designer', layout })
5
+ *
6
+ * The host supplies one empty element and nothing else - the designer builds
7
+ * its own chrome inside it. Asking a consumer to copy a screenful of toolbar
8
+ * markup is how the preview playground works, and it is not an API.
9
+ *
10
+ * Nothing here imports React, and nothing here touches the filesystem: reading
11
+ * and writing report files is the dev server's job (phase 5), reached over
12
+ * fetch. This module knows about a layout object and a DOM node.
13
+ */
14
+
15
+ import { validateLayout } from '../engine/validate.js';
16
+ import { allFields, allReportFields, fieldsFor, reportFields } from './fields.js';
17
+ import { blankLayout, isEmptyLayout } from './blank.js';
18
+ import {
19
+ drawSheet, selectionBox, selectionBoxes, bandUnder, bandBox, drawGuides,
20
+ guideLines, guideNubs
21
+ } from './canvas.js';
22
+ import { attachEditing } from './select.js';
23
+ import {
24
+ drawPanel, drawReportPanel, drawManyPanel, attachPanel, syncPanel
25
+ } from './panel.js';
26
+ import { icon } from './icons.js';
27
+ import { createDropdown } from '../shared/dropdown.js';
28
+ import { menuActions, drawMenu, menuPosition } from './menu.js';
29
+ import { openWindow, closeWithOpener } from '../shared/window.js';
30
+ import {
31
+ openViewerWindow, ZOOM_STEPS, MIN_ZOOM, MAX_ZOOM
32
+ } from '../preview/viewer.js';
33
+ import { buildPages } from '../engine/index.js';
34
+ import { drawProblems, sameIssues } from './toast.js';
35
+ import { askColumns, askReport, askName, askData, askToken, askDiscard } from './dialog.js';
36
+ import { sampleData, completeData } from './sample-data.js';
37
+ import { drawPreview } from './preview.js';
38
+ import { createHistory } from './history.js';
39
+ import { createStore, StoreError, toId } from '../shared/store.js';
40
+ import {
41
+ addBand, removeBand, findBand, addItem, removeItem, duplicateItem, pasteItems,
42
+ moveItemToBand, createText, createTable, createLine, createBox, createImage, addColumn,
43
+ removeColumn, targetBand, canAddTable
44
+ } from './structure.js';
45
+
46
+
47
+ /** the raster formats the renderer will draw from a data: URI; see imageSrc */
48
+ const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
49
+
50
+ /**
51
+ * How large a picture may be before it is kept out of the layout, and before
52
+ * storing one earns a word. A data: URI is a third larger than the file, and
53
+ * the layout is fetched whole every time a report is shown.
54
+ */
55
+ const IMAGE_MAX_BYTES = 1024 * 1024;
56
+ const IMAGE_WARN_BYTES = 200 * 1024;
57
+
58
+ const kb = (bytes) => `${Math.round(bytes / 1024)} KB`;
59
+
60
+
61
+ /** what a store has to be able to do; the rest of its methods are optional */
62
+ const STORE_METHODS = ['list', 'load', 'save'];
63
+
64
+
65
+ /**
66
+ * Refuses a store that is not one, at mount rather than at the first click.
67
+ *
68
+ * A folder path is the natural thing to try - `store: './reports'` - and it
69
+ * used to get as far as the report picker, which called `store.list()` and
70
+ * failed with "l.list is not a function" from somewhere inside the bundle.
71
+ * Nothing in that says what a store is or how to get reports from a folder,
72
+ * so this does.
73
+ *
74
+ * @param {*} store the option as given; absent is fine and means the dev server
75
+ */
76
+ function assertStore(store) {
77
+ if (store == null) return;
78
+
79
+ if (typeof store === 'string') {
80
+ throw new TypeError(
81
+ `createDesigner: store must be an object with list, load and save ` +
82
+ `functions, not a path ("${store}"). To keep reports in a folder, ` +
83
+ `leave store out and serve the folder: \`npx report-studio design ` +
84
+ `--dir ${store}\`, or reportStudio({ dir: '${store}' }) from ` +
85
+ `'report-studio/vite' in your vite.config.`);
86
+ }
87
+
88
+ const missing = STORE_METHODS.filter(name => typeof store?.[name] !== 'function');
89
+
90
+ if (missing.length > 0) {
91
+ throw new TypeError(
92
+ `createDesigner: store is missing ${missing.join(', ')} - it must be ` +
93
+ `an object with list, load and save functions (see the store contract), ` +
94
+ `or left out to use the dev server's routes.`);
95
+ }
96
+ }
97
+
98
+
99
+ /**
100
+ * Mounts the designer.
101
+ *
102
+ * @param {object} options
103
+ * @param {Element|string} options.mount the element to take over, or a selector
104
+ * @param {object} [options.layout] the report to edit; empty or absent starts a new one
105
+ * @param {string} [options.id] the report's filename stem, when it has one
106
+ * @param {object} [options.store] where reports are read and written; the dev
107
+ * server's routes by default
108
+ * @param {boolean} [options.guardUnload=true] ask the browser to confirm before
109
+ * the tab or window closes on unsaved changes. The browser words that prompt
110
+ * itself and will not take ours; pass false in a host that has its own.
111
+ * @param {(layout: object) => void} [options.onChange] called after every edit
112
+ * that lands in the undo history, and after undo, redo or opening another
113
+ * report - with the layout as it now stands. The designer's own object, not
114
+ * a copy: clone it before keeping it anywhere that outlives the next edit.
115
+ * @returns {object} a handle: the current layout, redraw, and destroy
116
+ */
117
+ /**
118
+ * Opens the designer in a window of its own.
119
+ *
120
+ * The same designer, mounted in a window this opens rather than in an element
121
+ * the host supplies - a report is a page-shaped thing, and a page suits a
122
+ * window better than a panel in somebody's application. The host's stylesheets
123
+ * are carried across, so it looks the same either way.
124
+ *
125
+ * Call it from a click or a keystroke, or the browser blocks it; a blocked
126
+ * window is null rather than a throw, so a host can fall back to the page.
127
+ *
128
+ * @param {object} options what createDesigner takes, less `mount`
129
+ * @param {number} [options.width]
130
+ * @param {number} [options.height]
131
+ * @param {string} [options.features] passed to window.open as given
132
+ * @returns {object|null} the designer handle, with `window`; null if blocked
133
+ */
134
+ export function openDesignerWindow({
135
+ width, height, features, ...rest
136
+ } = {}) {
137
+ const opened = openWindow({
138
+ title: rest.layout?.name ? `${rest.layout.name} - Designer` : 'Report designer',
139
+ width, height, features
140
+ });
141
+
142
+ if (!opened) return null;
143
+
144
+ const designer = createDesigner({ ...rest, mount: opened.mount });
145
+
146
+ /** what is being edited is held in memory, so it goes when the opener does */
147
+ const unwatch = closeWithOpener(globalThis, opened.window, designer.destroy);
148
+
149
+ return {
150
+ ...designer,
151
+ window: opened.window,
152
+
153
+ destroy() {
154
+ unwatch();
155
+ designer.destroy();
156
+ opened.close();
157
+ }
158
+ };
159
+ }
160
+
161
+
162
+ export function createDesigner({
163
+ mount, layout, id = null, store, guardUnload = true, onChange = null
164
+ } = {}) {
165
+ const root = typeof mount === 'string'
166
+ ? document.querySelector(mount)
167
+ : mount;
168
+
169
+ if (!root) {
170
+ throw new Error(
171
+ `createDesigner: no element for mount ${JSON.stringify(mount)}. ` +
172
+ `Add <div id="report-designer"></div> to the page first.`
173
+ );
174
+ }
175
+
176
+ /**
177
+ * The document the screen is mounted in, which is not always this one: a
178
+ * designer or a viewer opened in its own window lives in that window's
179
+ * document, and a listener put on the opener's would never hear it.
180
+ */
181
+ const doc = root.ownerDocument;
182
+
183
+ assertStore(store);
184
+
185
+ const files = store ?? createStore();
186
+
187
+ const state = {
188
+ /** page pixels per screen pixel; 1 until somebody says otherwise */
189
+ zoom: 1,
190
+
191
+ /** whether the zoom is being recomputed from the viewport on resize */
192
+ fitWidth: false,
193
+
194
+ /**
195
+ * Whether the rulers are showing. A view preference, not part of the
196
+ * report - the guides dragged off them are saved with the file, but
197
+ * whether somebody has the rulers up while they work is theirs.
198
+ */
199
+ rulers: false,
200
+
201
+ layout: isEmptyLayout(layout) ? blankLayout() : layout,
202
+ /**
203
+ * The selected items, oldest first, as `{ band, id }` - the band type
204
+ * and the item id, because ids are only unique within a band
205
+ * (validate.js does not require more).
206
+ *
207
+ * A list rather than one, so several can be moved together. The last is
208
+ * the primary: it is the one the rail describes and the one whose
209
+ * handles are drawn, because resizing six things at once has no single
210
+ * answer.
211
+ */
212
+ selection: [],
213
+ /** the filename stem this report is saved under, or null if never saved */
214
+ id,
215
+ /** whether there are changes the disk has not seen */
216
+ dirty: false,
217
+ /**
218
+ * What ctrl+C took, as `{ band, item }` - the item deep-copied, so a
219
+ * later edit to the original does not reach back into the clipboard,
220
+ * and the band it came from, which a paste elsewhere needs to know to
221
+ * reposition it.
222
+ *
223
+ * The designer's own, not the system's: reading the platform clipboard
224
+ * needs a permission prompt, and nothing outside this screen can use a
225
+ * layout item anyway.
226
+ */
227
+ clipboard: [],
228
+ /** 'design' arranges the bands; 'preview' runs the report */
229
+ mode: 'design',
230
+ /**
231
+ * The problems the author has already been shown and closed, so the
232
+ * toast does not reopen on every keystroke. It comes back the moment
233
+ * what is wrong changes - see sameIssues in toast.js.
234
+ */
235
+ dismissed: null
236
+ };
237
+
238
+ const history = createHistory(state.layout);
239
+
240
+ root.classList.add('report-designer');
241
+
242
+ /**
243
+ * The designer has to be able to hold the focus.
244
+ *
245
+ * Its shortcuts are bound per designer rather than to the document, so a
246
+ * second one on the page does not answer for this one - which only works if
247
+ * the focus can get in here, and a div cannot take it without being told.
248
+ * -1 rather than 0: it is reachable by clicking, not by tabbing to it, so
249
+ * it never becomes a stop on the way to the controls inside it.
250
+ */
251
+ root.tabIndex = -1;
252
+ root.innerHTML = chrome(state.layout);
253
+
254
+ const canvas = root.querySelector('[data-role="canvas"]');
255
+ const stage = root.querySelector('[data-role="stage"]');
256
+ /** everything drawn lives in here, so the scale has one thing to act on */
257
+ const surface = root.querySelector('[data-role="zoom-layer"]');
258
+ const panel = root.querySelector('[data-role="panel"]');
259
+ const bar = root.querySelector('[data-role="bar"]');
260
+ const foot = root.querySelector('[data-role="foot"]');
261
+ /** the pill is drawn into the page area, which is the box it must stay inside */
262
+ const main = root.querySelector('.dz-main');
263
+ const toasts = root.querySelector('[data-role="toasts"]');
264
+ const pages = root.querySelector('[data-role="pages"]');
265
+
266
+
267
+ /** the most recently selected `{ band, id }`, or null */
268
+ function primary() {
269
+ return state.selection.at(-1) ?? null;
270
+ }
271
+
272
+
273
+ /** the layout item behind a `{ band, id }`, or null if it has since gone */
274
+ function itemAt(one) {
275
+ if (!one) return null;
276
+
277
+ const band = findBand(state.layout, one.band);
278
+ return (band?.items || []).find(i => i.id === one.id) ?? null;
279
+ }
280
+
281
+
282
+ /** the item the rail describes */
283
+ function selected() {
284
+ return itemAt(primary());
285
+ }
286
+
287
+
288
+ /** every selected item, skipping any that have since been removed */
289
+ function selectedItems() {
290
+ return state.selection.map(itemAt).filter(Boolean);
291
+ }
292
+
293
+
294
+ function draw() {
295
+ /**
296
+ * Spec 9.1: a layout is hand-written as often as it is designed, so a
297
+ * broken one is named field by field rather than drawn as a blank page
298
+ * and left to look like the library is broken.
299
+ *
300
+ * The issues are said in the corner rather than drawn over the
301
+ * design, because most of them are survivable - setting groupBy before
302
+ * adding a group band is one keystroke, and pushing the page down the
303
+ * canvas to say so is a punishment. Only a layout that cannot be drawn
304
+ * at all leaves nothing behind it.
305
+ */
306
+ const issues = validateLayout(state.layout);
307
+
308
+ if (state.mode === 'preview') {
309
+ const run = drawPreview(state.layout, state.data);
310
+
311
+ surface.innerHTML = run.markup;
312
+ pages.textContent = run.error
313
+ ? ''
314
+ : `${run.pageCount} page${run.pageCount === 1 ? '' : 's'}`;
315
+
316
+ /** the preview says what stopped it in the page itself */
317
+ showProblems(issues);
318
+ applyZoom();
319
+ return issues;
320
+ }
321
+
322
+ pages.textContent = '';
323
+
324
+ let sheet = '';
325
+
326
+ try {
327
+ sheet = drawSheet(state.layout, state.selection,
328
+ { rulers: state.rulers });
329
+ } catch {
330
+ sheet = '';
331
+ }
332
+
333
+ surface.innerHTML = sheet;
334
+ showProblems(issues);
335
+
336
+ /** what was drawn may be a different size; the stage has to match it */
337
+ applyZoom();
338
+
339
+ return issues;
340
+ }
341
+
342
+
343
+ /**
344
+ * Puts the validator's findings in the corner, or takes them away again.
345
+ *
346
+ * Never while the report is being previewed: the run says what stopped it in
347
+ * the page itself, and two accounts of one fault is one too many.
348
+ *
349
+ * @param {string[]} issues
350
+ */
351
+ function showProblems(issues) {
352
+ const hidden = state.mode !== 'design'
353
+ || issues.length === 0
354
+ || sameIssues(issues, state.dismissed);
355
+
356
+ toasts.innerHTML = hidden ? '' : drawProblems(issues);
357
+
358
+ /** a layout that validates forgets the dismissal, so the next fault is announced */
359
+ if (issues.length === 0) state.dismissed = null;
360
+ }
361
+
362
+
363
+ /**
364
+ * A drag redraws sixty times a second, and rebuilding the page's markup that
365
+ * often is how a hand-written drag ends up feeling worse than the library it
366
+ * replaced. While the pointer is down only the two boxes that moved are
367
+ * touched; the full redraw happens once, when it is let go.
368
+ */
369
+ function patch() {
370
+ patchRules();
371
+
372
+ const boxes = selectionBoxes(state.layout, state.selection);
373
+
374
+ for (const [index, { item, box }] of boxes.entries()) {
375
+ const where = state.selection[index];
376
+
377
+ const outline = canvas.querySelector(
378
+ `[data-role="select"][data-select-id="${cssEscape(item.id)}"]`);
379
+
380
+ if (outline) {
381
+ Object.assign(outline.style, {
382
+ top: `${box.y}px`, left: `${box.x}px`,
383
+ width: `${box.w}px`, height: `${box.h}px`
384
+ });
385
+ }
386
+
387
+ const drawn = canvas.querySelector(
388
+ `[data-band-type="${cssEscape(where.band)}"] ` +
389
+ `[data-item-id="${cssEscape(item.id)}"]`);
390
+
391
+ if (!drawn) continue;
392
+
393
+ Object.assign(drawn.style, {
394
+ top: `${item.y}px`, left: `${item.x}px`, width: `${item.w}px`
395
+ });
396
+ /** a table's height is its rows', so it is never written here */
397
+ if (item.type !== 'table') drawn.style.height = `${item.h}px`;
398
+ }
399
+ }
400
+
401
+
402
+ /**
403
+ * The ruler guides, redrawn without rebuilding the sheet.
404
+ *
405
+ * Two small containers rather than the whole page: the ticks never move and
406
+ * there are two hundred of them, and a guide being dragged is the same sixty
407
+ * frames a second an item drag is.
408
+ */
409
+ function patchRules() {
410
+ const rules = canvas.querySelector('[data-role="rules"]');
411
+ if (rules) rules.innerHTML = state.rulers ? guideLines(state.layout) : '';
412
+
413
+ for (const host of canvas.querySelectorAll('[data-role="ruler-guides"]')) {
414
+ host.innerHTML = guideNubs(state.layout, host.dataset.axis);
415
+ }
416
+ }
417
+
418
+
419
+ function drawRail() {
420
+ /** a rendered report has no item to describe and no report to restructure */
421
+ if (state.mode === 'preview') return;
422
+
423
+ const many = state.selection.length;
424
+
425
+ panel.innerHTML = many > 1
426
+ ? drawManyPanel(selectedItems())
427
+ : (selected() ? drawPanel(selected()) : drawReportPanel(state.layout));
428
+ }
429
+
430
+
431
+ const sameOne = (a, b) => a?.band === b?.band && a?.id === b?.id;
432
+
433
+
434
+ /**
435
+ * Sets or extends the selection.
436
+ *
437
+ * @param {object|object[]|null} next
438
+ * @param {object} [options]
439
+ * @param {boolean} [options.add] shift-click: add it, or take it out again
440
+ * if it was already in - toggling is what makes a mis-click recoverable
441
+ * without starting the whole selection over
442
+ */
443
+ function setSelection(next, { add = false } = {}) {
444
+ const wanted = next == null ? [] : [].concat(next);
445
+
446
+ let list;
447
+
448
+ if (!add) {
449
+ list = wanted;
450
+ } else {
451
+ list = [...state.selection];
452
+
453
+ for (const one of wanted) {
454
+ const at = list.findIndex(s => sameOne(s, one));
455
+
456
+ if (at === -1) list.push(one);
457
+ else list.splice(at, 1);
458
+ }
459
+ }
460
+
461
+ const unchanged = list.length === state.selection.length
462
+ && list.every((one, i) => sameOne(one, state.selection[i]));
463
+
464
+ if (unchanged) return;
465
+
466
+ state.selection = list;
467
+ draw();
468
+ drawRail();
469
+ }
470
+
471
+
472
+ /**
473
+ * Records a step and marks the report as unsaved.
474
+ *
475
+ * Edits sharing a key coalesce into one undo step - typing "250" into a
476
+ * width arrives as three edits, and three undo presses to get back past one
477
+ * number is not undo but punishment.
478
+ */
479
+ function record(key = null) {
480
+ if (history.push(state.layout, key)) {
481
+ state.dirty = true;
482
+ refreshBar();
483
+ changed();
484
+ }
485
+ }
486
+
487
+
488
+ /**
489
+ * Tells the host the layout moved on.
490
+ *
491
+ * A host's callback that throws is the host's fault, but it must not leave
492
+ * the designer half-way through an edit - so it is caught and reported
493
+ * rather than let through the middle of a redraw.
494
+ */
495
+ function changed() {
496
+ if (typeof onChange !== 'function') return;
497
+
498
+ try {
499
+ onChange(state.layout);
500
+ } catch (error) {
501
+ console.error('createDesigner: onChange threw', error);
502
+ }
503
+ }
504
+
505
+
506
+ /** a change that alters the rail's own shape, not just its values */
507
+ function restructured(key = null) {
508
+ draw();
509
+ drawRail();
510
+ record(key);
511
+ }
512
+
513
+
514
+ function refreshBar() {
515
+ bar.querySelector('[data-role="name"]').textContent = state.layout.name ?? '';
516
+
517
+ /**
518
+ * The preview screen reads the report off disk, so it can only show one
519
+ * that has been saved. Rather than opening it to an error, the link is
520
+ * inert until there is a file for it to open, and says why.
521
+ */
522
+ bar.querySelector('[data-role="undo"]').disabled = !history.canUndo;
523
+ bar.querySelector('[data-role="redo"]').disabled = !history.canRedo;
524
+
525
+ /** a toggle, so it says which way it is set rather than what it does */
526
+ const size = bar.querySelector('[data-role="size"]');
527
+
528
+ if (size && state.layout.page) {
529
+ size.innerHTML =
530
+ `${state.layout.page.width} &times; ${state.layout.page.height}`;
531
+ }
532
+
533
+ const rulers = bar.querySelector('[data-role="rulers"]');
534
+
535
+ rulers.setAttribute('aria-pressed', String(state.rulers));
536
+ rulers.classList.toggle('is-on', state.rulers);
537
+
538
+ /** greyed rather than absent, should canAddTable ever say no */
539
+ const addTable = foot.querySelector('[data-role="add-table"]');
540
+
541
+ addTable.disabled = !canAddTable(state.layout);
542
+ bar.dataset.dirty = String(state.dirty);
543
+
544
+ const saved = bar.querySelector('[data-role="status"]');
545
+ saved.textContent = state.dirty
546
+ ? 'Unsaved changes'
547
+ : (state.id ? `Saved as ${state.id}.json` : 'Not saved yet');
548
+ }
549
+
550
+
551
+ /**
552
+ * Replaces the whole layout, as undo, redo and opening all do.
553
+ *
554
+ * The selection is dropped rather than carried over: the item it named may
555
+ * not exist in the layout being restored, and a selection pointing at
556
+ * nothing draws an outline round empty space.
557
+ */
558
+ function replaceLayout(next, { id: nextId, dirty }) {
559
+ state.layout = next;
560
+ state.selection = [];
561
+
562
+ /** another report is another design; its pages have not been run yet */
563
+ state.mode = 'design';
564
+ state.data = null;
565
+
566
+ if (nextId !== undefined) state.id = nextId;
567
+ if (dirty !== undefined) state.dirty = dirty;
568
+
569
+ drawMode();
570
+ changed();
571
+ }
572
+
573
+
574
+ /** puts a new item on a band and leaves it selected, rail and all */
575
+ function place(bandType, item) {
576
+ addItem(state.layout, bandType, item);
577
+
578
+ state.selection = [{ band: bandType, id: item.id }];
579
+ restructured(`add:${item.id}`);
580
+
581
+ /**
582
+ * The band is lit for a moment afterwards. Where an inserted item lands
583
+ * is a decision the designer made rather than the user, so it says
584
+ * where - a page number appearing somewhere unexpected is otherwise
585
+ * found by hunting for it.
586
+ */
587
+ flashBand(bandType);
588
+ }
589
+
590
+
591
+ /** which band is lit, and why - a drop target, or somewhere just inserted */
592
+ function markTarget(types) {
593
+ /** one band or several: a group can straddle a boundary */
594
+ const lit = new Set(types == null ? [] : [].concat(types));
595
+
596
+ for (const zone of canvas.querySelectorAll('[data-band-type]')) {
597
+ zone.classList.toggle('is-target', lit.has(zone.dataset.bandType));
598
+ }
599
+
600
+ /** the name in the gutter lights too, so the band is named not just lit */
601
+ for (const tag of canvas.querySelectorAll('[data-band-tag]')) {
602
+ tag.classList.toggle('is-target', lit.has(tag.dataset.bandTag));
603
+ }
604
+ }
605
+
606
+
607
+ /**
608
+ * Draws the alignment guides, or takes them away.
609
+ *
610
+ * Into a layer of its own rather than into the outlines, for the reason the
611
+ * outlines are a layer of their own: a guide belongs to the gesture, not to
612
+ * an item, and an item that is redrawn mid-drag would take its guides with
613
+ * it. The layer survives patch() because patch() only touches boxes.
614
+ *
615
+ * @param {{band: string, lines: object[], gaps: object[]}|null} found
616
+ */
617
+ function drawAlignment(found) {
618
+ const layer = canvas.querySelector('[data-role="guides"]');
619
+ if (!layer) return;
620
+
621
+ layer.innerHTML = found
622
+ ? drawGuides(bandBox(state.layout, found.band), found.lines, found.gaps)
623
+ : '';
624
+ }
625
+
626
+
627
+ /* ---------------- zoom ---------------- */
628
+
629
+ /**
630
+ * Scales the drawing rather than the numbers in it.
631
+ *
632
+ * The same choice the viewer makes, and for the same reason: re-computing
633
+ * type at 150% would re-wrap the text and stop matching what the engine
634
+ * paginated, so what is on screen would no longer be what would print.
635
+ *
636
+ * A transform does not affect layout, so the stage is given the scaled
637
+ * footprint explicitly - measured off the drawing rather than worked out
638
+ * from the page, because the gutter and the rulers are part of what has to
639
+ * fit and only the browser knows how wide they came out.
640
+ */
641
+ function applyZoom() {
642
+ surface.style.transformOrigin = 'top left';
643
+ surface.style.transform = `scale(${state.zoom})`;
644
+
645
+ const width = surface.offsetWidth;
646
+ const height = surface.offsetHeight;
647
+
648
+ /** jsdom lays nothing out, and neither does a canvas nobody has drawn yet */
649
+ if (width && height) {
650
+ stage.style.width = `${width * state.zoom}px`;
651
+ stage.style.height = `${height * state.zoom}px`;
652
+ }
653
+
654
+ refreshZoom();
655
+ }
656
+
657
+
658
+ function refreshZoom() {
659
+ /**
660
+ * Fit width has no step to light, and setFitWidth has already said so -
661
+ * writing a percentage over it here would take the label away from the
662
+ * mode that is actually on.
663
+ */
664
+ if (zoomPicker && !state.fitWidth) {
665
+ const exact = ZOOM_STEPS.find(
666
+ step => Math.abs(step - state.zoom) < 1e-9);
667
+
668
+ zoomPicker.value = exact !== undefined ? String(exact) : 'fit';
669
+ }
670
+
671
+ bar.querySelector('[data-role="zoom-out"]').disabled =
672
+ !state.fitWidth && state.zoom <= MIN_ZOOM;
673
+ bar.querySelector('[data-role="zoom-in"]').disabled =
674
+ !state.fitWidth && state.zoom >= MAX_ZOOM;
675
+ }
676
+
677
+
678
+ function setZoom(next) {
679
+ state.fitWidth = false;
680
+ state.zoom = Math.min(Math.max(next, MIN_ZOOM), MAX_ZOOM);
681
+ applyZoom();
682
+ }
683
+
684
+
685
+ /** the widest scale that still fits the canvas, less its own padding */
686
+ function setFitWidth() {
687
+ state.fitWidth = true;
688
+ if (zoomPicker) zoomPicker.value = 'fit';
689
+
690
+ const available = canvas.clientWidth - 48;
691
+ const natural = surface.offsetWidth;
692
+
693
+ if (available > 0 && natural > 0) {
694
+ state.zoom = Math.min(Math.max(available / natural, MIN_ZOOM), MAX_ZOOM);
695
+ }
696
+
697
+ applyZoom();
698
+ }
699
+
700
+
701
+ /** to the neighbouring preset rather than a blind multiply */
702
+ function stepZoom(direction) {
703
+ const from = state.zoom;
704
+
705
+ const next = direction > 0
706
+ ? ZOOM_STEPS.find(step => step > from + 1e-9)
707
+ : [...ZOOM_STEPS].reverse().find(step => step < from - 1e-9);
708
+
709
+ setZoom(next ?? from);
710
+ }
711
+
712
+
713
+ function flashBand(type) {
714
+ clearTimeout(flashBand.timer);
715
+ markTarget(type);
716
+
717
+ flashBand.timer = setTimeout(() => markTarget(null), 1200);
718
+ }
719
+
720
+
721
+ /* ---------------- the right-click pill ---------------- */
722
+
723
+ /** the open menu, or null */
724
+ let menu = null;
725
+
726
+
727
+ function closeMenu() {
728
+ menu?.remove();
729
+ menu = null;
730
+ }
731
+
732
+
733
+ /**
734
+ * Opens the pill at a point on screen.
735
+ *
736
+ * Drawn first and measured second: what it offers decides how wide it is,
737
+ * and it cannot be kept inside the page area without knowing that.
738
+ *
739
+ * @param {number} clientX
740
+ * @param {number} clientY
741
+ */
742
+ function openMenu(clientX, clientY) {
743
+ closeMenu();
744
+
745
+ main.insertAdjacentHTML('beforeend', drawMenu(menuActions({
746
+ count: state.selection.length,
747
+ canPaste: state.clipboard.length > 0,
748
+ /** should canAddTable ever say no, a copy of a table is what it refuses */
749
+ canDuplicate: canAddTable(state.layout)
750
+ || !selectedItems().some(item => item.type === 'table')
751
+ })));
752
+
753
+ menu = main.querySelector('[data-role="menu"]');
754
+
755
+ /**
756
+ * Bound to the pill, not to the page area: a delegated listener out
757
+ * there answers for the tool strip as well, and every add would run
758
+ * twice.
759
+ */
760
+ menu.addEventListener('click', onMenuClick);
761
+
762
+ const bounds = main.getBoundingClientRect();
763
+ const box = menu.getBoundingClientRect();
764
+
765
+ const at = menuPosition(
766
+ { x: clientX - bounds.left, y: clientY - bounds.top },
767
+ { width: box.width, height: box.height },
768
+ { width: bounds.width, height: bounds.height }
769
+ );
770
+
771
+ menu.style.left = `${at.left}px`;
772
+ menu.style.top = `${at.top}px`;
773
+
774
+ /** so escape and the arrow keys have somewhere to be aimed */
775
+ menu.querySelector('button:not([disabled])')?.focus();
776
+ }
777
+
778
+
779
+ /**
780
+ * A right click acts on what is under it. An item that is not selected
781
+ * becomes the selection first - otherwise Delete would take whatever
782
+ * happened to be selected elsewhere, which is how a layout gets lost.
783
+ */
784
+ function onContextMenu(event) {
785
+ if (state.mode !== 'design') return;
786
+
787
+ event.preventDefault();
788
+
789
+ const node = event.target.closest?.('[data-item-id]');
790
+ const bandType = node?.closest('[data-band-type]')?.dataset.bandType ?? null;
791
+
792
+ if (node && bandType) {
793
+ const where = { band: bandType, id: node.dataset.itemId };
794
+ const already = state.selection
795
+ .some(one => one.band === where.band && one.id === where.id);
796
+
797
+ if (!already) setSelection(where);
798
+ } else {
799
+ setSelection(null);
800
+ }
801
+
802
+ openMenu(event.clientX, event.clientY);
803
+ }
804
+
805
+
806
+ function onMenuClick(event) {
807
+ const node = event.target.closest?.('[data-action]');
808
+ if (!node || node.disabled) return;
809
+
810
+ event.preventDefault();
811
+
812
+ /** closed first: what follows redraws, and a stale pill would outlive it */
813
+ closeMenu();
814
+ act(node.dataset.action, node.dataset);
815
+ }
816
+
817
+
818
+ /** anything that is not the pill closes it */
819
+ function onDocumentDown(event) {
820
+ if (menu && !menu.contains(event.target)) closeMenu();
821
+ }
822
+
823
+
824
+ function onMenuKey(event) {
825
+ if (menu && event.key === 'Escape') closeMenu();
826
+ }
827
+
828
+
829
+ function act(action, data) {
830
+ const item = selected();
831
+
832
+ switch (action) {
833
+ case 'add-text': {
834
+ const type = targetBand(state.layout, primary());
835
+ if (!type) return;
836
+
837
+ place(type, createText(state.layout, findBand(state.layout, type)));
838
+ return;
839
+ }
840
+
841
+ case 'add-box': {
842
+ const type = targetBand(state.layout, primary());
843
+ if (!type) return;
844
+
845
+ place(type, createBox(state.layout, findBand(state.layout, type)));
846
+ return;
847
+ }
848
+
849
+ case 'add-image': {
850
+ const type = targetBand(state.layout, primary());
851
+ if (!type) return;
852
+
853
+ place(type, createImage(state.layout, findBand(state.layout, type)));
854
+ return;
855
+ }
856
+
857
+ case 'upload-image':
858
+ if (item?.type !== 'image') return;
859
+ chooseImage(item);
860
+ return;
861
+
862
+ case 'clear-image':
863
+ if (item?.type !== 'image' || !item.src) return;
864
+ item.src = null;
865
+ restructured(`image:${item.id}`);
866
+ return;
867
+
868
+ case 'add-line': {
869
+ const type = targetBand(state.layout, primary());
870
+ if (!type) return;
871
+
872
+ place(type, createLine(
873
+ state.layout, findBand(state.layout, type), data?.orientation));
874
+ return;
875
+ }
876
+
877
+ case 'add-field': {
878
+ /**
879
+ * Unlike text and table, this chooses its own band - a total
880
+ * belongs in a footer, and the alternative is inserting it into
881
+ * the detail band and asking the user to drag it somewhere it
882
+ * will actually resolve.
883
+ */
884
+ askToken(root, state.layout, primary()?.band ?? null).then(chosen => {
885
+ if (!chosen) return;
886
+
887
+ const band = findBand(state.layout, chosen.band);
888
+ if (!band) return;
889
+
890
+ const made = createText(state.layout, band);
891
+
892
+ made.value = chosen.value;
893
+ made.w = chosen.w;
894
+ made.style.align = chosen.align;
895
+
896
+ place(chosen.band, made);
897
+ });
898
+ return;
899
+ }
900
+
901
+ case 'add-table': {
902
+ const type = targetBand(state.layout, primary());
903
+ if (!type) return;
904
+
905
+ if (!canAddTable(state.layout)) return;
906
+
907
+ /**
908
+ * A table is asked about first: how many columns it starts with
909
+ * is the one thing that cannot be dragged into place afterwards
910
+ * without a trip through the rail for each of them.
911
+ */
912
+ askColumns(root).then(columns => {
913
+ if (columns == null) return;
914
+
915
+ place(type, createTable(
916
+ state.layout, findBand(state.layout, type), columns));
917
+ });
918
+ return;
919
+ }
920
+
921
+ case 'duplicate-item': {
922
+ if (!state.selection.length) return;
923
+
924
+ /**
925
+ * Read the selection before adding anything: duplicateItem
926
+ * appends to the same band, and a copy made from a copy would
927
+ * cascade down the page for as long as the loop ran.
928
+ */
929
+ const sources = [...state.selection];
930
+ const copies = [];
931
+
932
+ for (const one of sources) {
933
+ const made = duplicateItem(state.layout, one.band, one.id);
934
+ if (made) copies.push({ band: one.band, id: made.id });
935
+ }
936
+
937
+ if (!copies.length) return;
938
+
939
+ /**
940
+ * The copies are what is selected afterwards, not the originals:
941
+ * the next thing anyone does to a duplicate is move it, and
942
+ * leaving the original selected would move the wrong one.
943
+ */
944
+ state.selection = copies;
945
+ restructured(`duplicate:${copies.map(c => c.id).join(',')}`);
946
+
947
+ flashBand([...new Set(copies.map(c => c.band))]);
948
+ return;
949
+ }
950
+
951
+ case 'dismiss-problems': {
952
+ state.dismissed = validateLayout(state.layout);
953
+ toasts.innerHTML = '';
954
+ return;
955
+ }
956
+
957
+ case 'copy-items': {
958
+ if (!state.selection.length) return;
959
+
960
+ const taken = state.selection
961
+ .map(one => ({ band: one.band, item: itemAt(one) }))
962
+ .filter(entry => entry.item)
963
+ .map(entry => ({
964
+ band: entry.band,
965
+ item: structuredClone(entry.item)
966
+ }));
967
+
968
+ if (!taken.length) return;
969
+
970
+ state.clipboard = taken;
971
+
972
+ /**
973
+ * Nothing on screen changes when a copy is taken, so the bar
974
+ * says it did - otherwise ctrl+C is a keystroke with no answer.
975
+ */
976
+ flashStatus(
977
+ taken.length > 1 ? `Copied ${taken.length} items` : 'Copied',
978
+ { ms: 2000 }
979
+ );
980
+ return;
981
+ }
982
+
983
+ case 'paste-items': {
984
+ if (!state.clipboard.length) return;
985
+
986
+ /** onto the band being worked in, which is where a paste is expected */
987
+ const type = targetBand(state.layout, primary());
988
+ if (!type) return;
989
+
990
+ const made = pasteItems(state.layout, type, state.clipboard);
991
+ if (!made.length) return;
992
+
993
+ /**
994
+ * The clipboard now holds where these landed, so pressing paste
995
+ * again steps down from the last copy rather than putting a
996
+ * second one exactly on top of it.
997
+ */
998
+ state.clipboard = made.map(item => ({
999
+ band: type,
1000
+ item: structuredClone(item)
1001
+ }));
1002
+
1003
+ state.selection = made.map(item => ({ band: type, id: item.id }));
1004
+ restructured(`paste:${made.map(i => i.id).join(',')}`);
1005
+
1006
+ flashBand(type);
1007
+ return;
1008
+ }
1009
+
1010
+ case 'delete-item': {
1011
+ if (!state.selection.length) return;
1012
+
1013
+ const gone = state.selection.map(one => one.id).join(',');
1014
+
1015
+ for (const one of state.selection) {
1016
+ removeItem(state.layout, one.band, one.id);
1017
+ }
1018
+
1019
+ state.selection = [];
1020
+ restructured(`delete:${gone}`);
1021
+ return;
1022
+ }
1023
+
1024
+ case 'add-column':
1025
+ if (item?.type !== 'table') return;
1026
+ addColumn(item);
1027
+ restructured(`column:add:${item.id}`);
1028
+ return;
1029
+
1030
+ case 'remove-column':
1031
+ if (item?.type !== 'table') return;
1032
+ if (removeColumn(item, Number(data.index))) {
1033
+ restructured(`column:remove:${item.id}`);
1034
+ }
1035
+ return;
1036
+
1037
+ case 'undo': {
1038
+ const previous = history.undo();
1039
+ if (previous) replaceLayout(previous, { dirty: true });
1040
+ return;
1041
+ }
1042
+
1043
+ case 'redo': {
1044
+ const next = history.redo();
1045
+ if (next) replaceLayout(next, { dirty: true });
1046
+ return;
1047
+ }
1048
+
1049
+ case 'open': return openReport();
1050
+ case 'save': return saveReport();
1051
+ case 'data': return editData();
1052
+ case 'open-window': return openInWindow();
1053
+
1054
+ case 'zoom-in': return stepZoom(1);
1055
+ case 'zoom-out': return stepZoom(-1);
1056
+
1057
+ case 'toggle-rulers': {
1058
+ state.rulers = !state.rulers;
1059
+ draw();
1060
+ refreshBar();
1061
+ return;
1062
+ }
1063
+ case 'toggle-preview': return togglePreview();
1064
+ }
1065
+ }
1066
+
1067
+
1068
+ /**
1069
+ * Whether the report being edited may be closed.
1070
+ *
1071
+ * A report with no unsaved changes closes without a word - a question
1072
+ * nobody needs to answer is one they stop reading, and then they stop
1073
+ * reading the one that mattered too.
1074
+ *
1075
+ * @returns {Promise<boolean>}
1076
+ */
1077
+ async function mayClose() {
1078
+ if (!state.dirty) return true;
1079
+
1080
+ return askDiscard(root, state.layout?.name ?? '');
1081
+ }
1082
+
1083
+
1084
+ /**
1085
+ * Opens another report.
1086
+ *
1087
+ * Asked before the list is fetched rather than after one is chosen: what
1088
+ * the user is deciding is whether to leave this report, and that is settled
1089
+ * at the click, not three steps into a flow they would then have to unwind.
1090
+ *
1091
+ * The list comes from the server, so this is also where the designer finds
1092
+ * out there is no server - and says so in terms of what to do about it,
1093
+ * rather than letting a failed fetch surface as nothing happening.
1094
+ */
1095
+ async function openReport() {
1096
+ if (!await mayClose()) return;
1097
+
1098
+ let reports;
1099
+
1100
+ try {
1101
+ reports = await files.list();
1102
+ } catch (error) {
1103
+ return complain(error);
1104
+ }
1105
+
1106
+ const chosen = await askReport(root, reports);
1107
+ if (!chosen) return;
1108
+
1109
+ if (chosen.blank) {
1110
+ replaceLayout(blankLayout(), { id: null, dirty: false });
1111
+ history.reset(state.layout);
1112
+ refreshBar();
1113
+ return;
1114
+ }
1115
+
1116
+ try {
1117
+ const loaded = await files.load(chosen.id);
1118
+
1119
+ replaceLayout(loaded, { id: chosen.id, dirty: false });
1120
+ history.reset(state.layout);
1121
+ refreshBar();
1122
+ } catch (error) {
1123
+ complain(error);
1124
+ }
1125
+ }
1126
+
1127
+
1128
+ /**
1129
+ * Saves the report, asking what to call it the first time.
1130
+ *
1131
+ * An invalid layout is saved anyway - a report half-designed is legitimately
1132
+ * invalid, and refusing to keep somebody's work in progress is not a safety
1133
+ * feature. The problems banner is already saying what is wrong.
1134
+ */
1135
+ async function saveReport() {
1136
+ let saveId = state.id;
1137
+
1138
+ if (!saveId) {
1139
+ const named = await askName(root, state.layout.name ?? '');
1140
+ if (!named) return;
1141
+
1142
+ saveId = named.id;
1143
+ state.layout.name = named.name;
1144
+ }
1145
+
1146
+ try {
1147
+ await files.save(saveId, state.layout);
1148
+
1149
+ state.id = saveId;
1150
+ state.dirty = false;
1151
+ refreshBar();
1152
+
1153
+ await seedData(saveId);
1154
+ } catch (error) {
1155
+ complain(error);
1156
+ }
1157
+ }
1158
+
1159
+
1160
+ /**
1161
+ * Writes a sample data file for a report that has none, and brings one that
1162
+ * exists up to date with the layout.
1163
+ *
1164
+ * Up to date means *added to*, never changed. Once someone has put real
1165
+ * figures in that file, a later save must not touch them - a designer that
1166
+ * quietly replaced the host application's data with "Customer 1" would be
1167
+ * worse than one that never offered to help. But a table added since the
1168
+ * file was written needs rows, or the preview has nothing to bind it to, so
1169
+ * what the layout asks for and the file lacks is filled in from the sample.
1170
+ * A file with nothing missing is not written at all.
1171
+ */
1172
+ async function seedData(saveId) {
1173
+ if (!files.loadData || !files.saveData) return;
1174
+
1175
+ try {
1176
+ const existing = await files.loadData(saveId);
1177
+ const { data, added } = completeData(existing, state.layout);
1178
+
1179
+ if (added) await files.saveData(saveId, data);
1180
+ } catch {
1181
+ /**
1182
+ * A report that saved but whose sample data did not is a working
1183
+ * report. Complaining about the convenience would bury the fact
1184
+ * that the thing being asked for succeeded.
1185
+ */
1186
+ }
1187
+ }
1188
+
1189
+
1190
+ /**
1191
+ * Shows what data the report is asking for.
1192
+ *
1193
+ * Loaded from disk if it is there, and otherwise derived from the layout -
1194
+ * so a report that has never been saved can still answer "what do I have to
1195
+ * supply?", which is the question this exists for.
1196
+ */
1197
+ async function editData() {
1198
+ let current = null;
1199
+
1200
+ if (state.id && files.loadData) {
1201
+ try {
1202
+ current = await files.loadData(state.id);
1203
+ } catch (error) {
1204
+ return complain(error);
1205
+ }
1206
+ }
1207
+
1208
+ const generated = current == null;
1209
+
1210
+ /** a table added since the file was written shows up with its rows */
1211
+ const edited = await askData(root, completeData(current, state.layout).data, {
1212
+ id: state.id, generated
1213
+ });
1214
+
1215
+ if (!edited) return;
1216
+
1217
+ if (!state.id) {
1218
+ return complain(new Error(
1219
+ 'Save the report first - its data file is named after it.'));
1220
+ }
1221
+
1222
+ try {
1223
+ await files.saveData(state.id, edited);
1224
+ } catch (error) {
1225
+ complain(error);
1226
+ }
1227
+ }
1228
+
1229
+
1230
+ /**
1231
+ * Runs the report, or goes back to arranging it.
1232
+ *
1233
+ * The data is fetched each time rather than cached, so a report previewed
1234
+ * after its data file was edited shows the edit. It is the report's real
1235
+ * data when there is some and the derived sample when there is not, which
1236
+ * makes the preview work for a report nobody has supplied data for yet -
1237
+ * the case it is most needed in.
1238
+ */
1239
+ /**
1240
+ * Runs the report and opens it in a window of its own.
1241
+ *
1242
+ * This used to be a link to the preview screen, which reads the report off
1243
+ * the disk - so it did nothing until the report had been saved, which is
1244
+ * the wrong answer to "show me this". The window is built here from the
1245
+ * design as it currently stands, so it works on the first keystroke of a
1246
+ * report that has never been named.
1247
+ */
1248
+ function openInWindow() {
1249
+ let paginated;
1250
+
1251
+ try {
1252
+ paginated = buildPages(state.layout, state.data ?? sampleData(state.layout));
1253
+ } catch (error) {
1254
+ complain(error);
1255
+ return;
1256
+ }
1257
+
1258
+ const opened = openViewerWindow({
1259
+ paginated,
1260
+ title: state.layout?.name || 'Report'
1261
+ });
1262
+
1263
+ /** a browser that refused the window says nothing itself, so this does */
1264
+ if (!opened) {
1265
+ flashStatus(
1266
+ 'The browser blocked the report window - allow pop-ups for this page',
1267
+ { problem: true, ms: 6000 }
1268
+ );
1269
+ return;
1270
+ }
1271
+
1272
+ windows.add(opened);
1273
+ }
1274
+
1275
+
1276
+ /** the report windows this designer opened, so they go when it does */
1277
+ const windows = new Set();
1278
+
1279
+ /** the zoom menu, built once the bar exists */
1280
+ let zoomPicker = null;
1281
+
1282
+
1283
+ async function togglePreview() {
1284
+ if (state.mode === 'preview') {
1285
+ state.mode = 'design';
1286
+ state.data = null;
1287
+ drawMode();
1288
+ return;
1289
+ }
1290
+
1291
+ let data = null;
1292
+
1293
+ if (state.id && files.loadData) {
1294
+ try {
1295
+ data = await files.loadData(state.id);
1296
+ } catch {
1297
+ /** a preview on sample data beats no preview at all */
1298
+ }
1299
+ }
1300
+
1301
+ /**
1302
+ * Completed rather than taken as it is: a data file written before the
1303
+ * newest table or placeholder existed would otherwise fail the preview
1304
+ * on a dataset "which is not present in the data".
1305
+ */
1306
+ state.data = completeData(data, state.layout).data;
1307
+ state.mode = 'preview';
1308
+
1309
+ /** an outline over a paginated page points at nothing */
1310
+ state.selection = [];
1311
+ drawMode();
1312
+ }
1313
+
1314
+
1315
+ /** everything that differs between arranging a report and running it */
1316
+ function drawMode() {
1317
+ root.dataset.mode = state.mode;
1318
+
1319
+ const button = bar.querySelector('[data-action="toggle-preview"]');
1320
+ const running = state.mode === 'preview';
1321
+
1322
+ button.innerHTML = icon(running ? 'design' : 'preview');
1323
+ button.title = running ? 'Back to the design (ctrl+E)' : 'Run the report (ctrl+E)';
1324
+ button.setAttribute('aria-label', button.title);
1325
+ button.setAttribute('aria-pressed', String(running));
1326
+
1327
+ draw();
1328
+ drawRail();
1329
+ refreshBar();
1330
+ }
1331
+
1332
+
1333
+ /** the server's own words, where the user is looking */
1334
+ /**
1335
+ * Says something in the bar for a moment, then puts the saved state back.
1336
+ *
1337
+ * Shared with complain() so there is one place that owns the status line -
1338
+ * two timers writing to it independently is how a message ends up cleared
1339
+ * by an error that arrived before it.
1340
+ *
1341
+ * @param {string} message
1342
+ * @param {object} [options]
1343
+ * @param {boolean} [options.problem] draws it as a failure
1344
+ * @param {number} [options.ms] how long it stands
1345
+ */
1346
+ function flashStatus(message, { problem = false, ms = 6000 } = {}) {
1347
+ const note = bar.querySelector('[data-role="status"]');
1348
+
1349
+ note.textContent = message;
1350
+ if (problem) note.dataset.problem = 'true';
1351
+ else delete note.dataset.problem;
1352
+
1353
+ clearTimeout(complain.timer);
1354
+ complain.timer = setTimeout(() => {
1355
+ delete note.dataset.problem;
1356
+ refreshBar();
1357
+ }, ms);
1358
+ }
1359
+
1360
+
1361
+ /**
1362
+ * Asks for a picture and stores it on the item as a data: URI.
1363
+ *
1364
+ * Into the layout rather than beside it: a layout is one JSON file that the
1365
+ * host fetches and hands to buildPages, and a picture stored anywhere else
1366
+ * is a second thing to deploy and a broken image when somebody forgets to.
1367
+ * The cost is size, so a large file is refused outright and a middling one
1368
+ * stored with a word about it - a picture that big wants to be a URL in
1369
+ * the data instead.
1370
+ *
1371
+ * @param {object} item the image item; still checked when the file arrives,
1372
+ * because the selection may have moved on while the dialog was open
1373
+ */
1374
+ function chooseImage(item) {
1375
+ const input = doc.createElement('input');
1376
+
1377
+ input.type = 'file';
1378
+ input.accept = IMAGE_TYPES.join(',');
1379
+
1380
+ input.addEventListener('change', () => {
1381
+ const file = input.files?.[0];
1382
+ if (!file) return;
1383
+
1384
+ if (!IMAGE_TYPES.includes(file.type)) {
1385
+ flashStatus(`${file.name} is not a PNG, JPEG, GIF or WebP image`,
1386
+ { problem: true });
1387
+ return;
1388
+ }
1389
+
1390
+ if (file.size > IMAGE_MAX_BYTES) {
1391
+ flashStatus(
1392
+ `${file.name} is ${kb(file.size)} - too large to store in a layout. ` +
1393
+ `Bind the image to a data field and supply its URL instead`,
1394
+ { problem: true });
1395
+ return;
1396
+ }
1397
+
1398
+ const reader = new (doc.defaultView ?? globalThis).FileReader();
1399
+
1400
+ reader.addEventListener('load', () => {
1401
+ if (!itemStillThere(item)) return;
1402
+
1403
+ item.src = String(reader.result);
1404
+ restructured(`image:${item.id}`);
1405
+
1406
+ if (file.size > IMAGE_WARN_BYTES) {
1407
+ flashStatus(`Stored ${file.name} (${kb(file.size)}) in the layout - ` +
1408
+ `every copy of the report carries it`);
1409
+ }
1410
+ });
1411
+
1412
+ reader.addEventListener('error', () => complain(reader.error));
1413
+ reader.readAsDataURL(file);
1414
+ });
1415
+
1416
+ input.click();
1417
+ }
1418
+
1419
+
1420
+ /** whether an item is still in the layout - undo can take it while a dialog is open */
1421
+ function itemStillThere(item) {
1422
+ return (state.layout.bands ?? []).some(band => (band.items ?? []).includes(item));
1423
+ }
1424
+
1425
+
1426
+ function complain(error) {
1427
+ const message = error instanceof StoreError
1428
+ ? error.message
1429
+ : `Something went wrong: ${error?.message ?? error}`;
1430
+
1431
+ flashStatus(message, { problem: true });
1432
+ }
1433
+
1434
+
1435
+ function toggleBand(type, on) {
1436
+ if (on) addBand(state.layout, type);
1437
+ else {
1438
+ removeBand(state.layout, type);
1439
+ /** the selection may have been standing on it */
1440
+ state.selection = state.selection.filter(one => one.band !== type);
1441
+ }
1442
+
1443
+ restructured(`band:${type}`);
1444
+ }
1445
+
1446
+
1447
+ function setBandHeight(type, raw) {
1448
+ const band = findBand(state.layout, type);
1449
+ if (!band) return;
1450
+
1451
+ const trimmed = String(raw).trim();
1452
+
1453
+ if (trimmed === '') delete band.height;
1454
+ else if (/^-?[\d.]+\s*%$/.test(trimmed)) band.height = trimmed;
1455
+ else if (Number.isFinite(Number(trimmed))) band.height = Number(trimmed);
1456
+ else return;
1457
+
1458
+ /** the rail is not rebuilt - the box being typed into is in it */
1459
+ draw();
1460
+ record(`band-height:${type}`);
1461
+ }
1462
+
1463
+
1464
+ root.dataset.mode = state.mode;
1465
+
1466
+ zoomPicker = createDropdown(bar.querySelector('[data-role="zoom-dropdown"]'));
1467
+
1468
+ zoomPicker.addEventListener('change', () => {
1469
+ if (zoomPicker.value === 'fit') setFitWidth();
1470
+ else setZoom(Number(zoomPicker.value));
1471
+ });
1472
+
1473
+ /** fit width is a reading of the viewport, so it is taken again when it changes */
1474
+ const onViewportResize = () => { if (state.fitWidth) setFitWidth(); };
1475
+ const view = doc.defaultView ?? globalThis;
1476
+
1477
+ view.addEventListener('resize', onViewportResize);
1478
+
1479
+ /**
1480
+ * The tab or the window closing, which is the other way to close a report.
1481
+ *
1482
+ * Nothing of ours can be shown here. A page may only ask the browser to put
1483
+ * its own question - "leave site?" - and browsers stopped letting the page
1484
+ * word it years ago, because a page that could write that text could write
1485
+ * anything into a box the user reads as the browser's. So askDiscard cannot
1486
+ * be reached from here, and the choice is this prompt or no prompt at all.
1487
+ *
1488
+ * preventDefault is the modern spelling and returnValue the old one; both
1489
+ * are set because which one a browser honours still varies. Neither shows
1490
+ * anything unless the user has interacted with the page - a rule against
1491
+ * pages that trap people who only glanced at them, and no obstacle to
1492
+ * somebody who has been dragging text boxes around.
1493
+ *
1494
+ * Registered by default and turned off with `guardUnload: false`: a host
1495
+ * embedding the designer in a larger application may have its own unsaved
1496
+ * state and its own prompt, and two prompts for one close is worse than the
1497
+ * one it already had.
1498
+ */
1499
+ const onBeforeUnload = (event) => {
1500
+ if (!state.dirty) return;
1501
+
1502
+ event.preventDefault();
1503
+ event.returnValue = '';
1504
+ };
1505
+
1506
+ if (guardUnload) view.addEventListener('beforeunload', onBeforeUnload);
1507
+
1508
+ draw();
1509
+ drawRail();
1510
+ refreshBar();
1511
+
1512
+ const detach = attachEditing({
1513
+ canvas,
1514
+ getLayout: () => state.layout,
1515
+ getSelection: () => state.selection,
1516
+ select: setSelection,
1517
+ remove: () => act('delete-item'),
1518
+
1519
+ /**
1520
+ * Alt-drag. The copies become the selection, so the drag that follows
1521
+ * carries them and leaves the originals where they were put.
1522
+ */
1523
+ duplicate: () => {
1524
+ const before = state.selection.map(one => one.id).join(',');
1525
+ act('duplicate-item');
1526
+
1527
+ return state.selection.map(one => one.id).join(',') !== before;
1528
+ },
1529
+ /**
1530
+ * render.js emits the same data-item-id attributes items.js gives the
1531
+ * canvas - which is the point of one drawing path, and also means a
1532
+ * click on a rendered page would otherwise select and drag the item
1533
+ * behind it.
1534
+ */
1535
+ enabled: () => state.mode === 'design',
1536
+
1537
+ /**
1538
+ * Screen pixels are page pixels divided by this. Without it a drag at
1539
+ * 200% moves an item twice as far as the pointer went.
1540
+ */
1541
+ getZoom: () => state.zoom,
1542
+
1543
+ /** no rulers, no guides to drag off them and nothing to snap to */
1544
+ rulers: () => state.rulers,
1545
+ /**
1546
+ * A drag moves x and y, which the rail is showing - so the controls are
1547
+ * refreshed rather than rebuilt. Rebuilding them under a cursor takes
1548
+ * the focus and the caret with it.
1549
+ */
1550
+ onTarget: markTarget,
1551
+
1552
+ /**
1553
+ * What the drag has lined up with. Drawn straight rather than through
1554
+ * draw(), because it changes sixty times a second and rebuilding the
1555
+ * sheet that often is what patch() exists to avoid.
1556
+ */
1557
+ onGuides: drawAlignment,
1558
+
1559
+ commit: ({ live, band, key = null }) => {
1560
+ /**
1561
+ * A drag that ended over another band moves the item into it. Until
1562
+ * now the item followed the pointer across the boundary and stayed
1563
+ * in the band it started in, which is the sort of thing that is only
1564
+ * noticed once the report prints in the wrong place.
1565
+ */
1566
+ /**
1567
+ * Each selected item goes to the band it actually landed in, rather
1568
+ * than to one band chosen for the whole group - what you see on the
1569
+ * page is where they end up.
1570
+ */
1571
+ if (!live && band?.length) {
1572
+ let moved = false;
1573
+
1574
+ state.selection = state.selection.map(one => {
1575
+ const item = itemAt(one);
1576
+ const to = item ? bandUnder(state.layout, one.band, item) : null;
1577
+
1578
+ if (to && to !== one.band
1579
+ && moveItemToBand(state.layout, one.band, to, one.id)) {
1580
+ moved = true;
1581
+ return { band: to, id: one.id };
1582
+ }
1583
+
1584
+ return one;
1585
+ });
1586
+
1587
+ if (moved) drawRail();
1588
+ }
1589
+
1590
+ live ? patch() : draw();
1591
+ syncPanel(panel, selected(), state.layout);
1592
+
1593
+ /**
1594
+ * Only the finished gesture is a step. A drag reports sixty times a
1595
+ * second, and each of those as an undo step would bury the edit
1596
+ * before it.
1597
+ */
1598
+ if (!live) {
1599
+ record(key ?? `move:${state.selection.map(o => o.id).join(',')}`);
1600
+ }
1601
+ }
1602
+ });
1603
+
1604
+ const detachPanel = attachPanel({
1605
+ panel,
1606
+ getTarget: () => {
1607
+ const item = selected();
1608
+ return item
1609
+ ? { target: item, fields: allFields(item) }
1610
+ : { target: state.layout, fields: allReportFields(state.layout) };
1611
+ },
1612
+ getItem: selected,
1613
+ /**
1614
+ * A typed edit redraws the page but never the rail: the control being
1615
+ * typed into is in it.
1616
+ *
1617
+ * Unless the edit changed which controls there are - picking a named
1618
+ * paper size puts the width and height boxes away - in which case the
1619
+ * rail is rebuilt. Safe here because the control that asked for it is a
1620
+ * dropdown, not something anyone is mid-word in.
1621
+ */
1622
+ changed: (key, { rebuild = false } = {}) => {
1623
+ draw();
1624
+ if (rebuild) drawRail();
1625
+ record(key);
1626
+ },
1627
+ act,
1628
+ toggleBand,
1629
+ setBandHeight
1630
+ });
1631
+
1632
+ /** the bar and the footer both carry actions; the rail wires its own */
1633
+ function onChromeClick(event) {
1634
+ const node = event.target.closest?.('[data-action]');
1635
+ if (!node) return;
1636
+
1637
+ event.preventDefault();
1638
+ act(node.dataset.action, node.dataset);
1639
+ }
1640
+
1641
+ /**
1642
+ * Whether a keystroke belongs to this designer.
1643
+ *
1644
+ * Anything aimed inside it, plainly. And anything aimed at nothing at all -
1645
+ * the page has just loaded, or a click landed on the canvas, and the body
1646
+ * has the focus by default. Without that second case the shortcuts were
1647
+ * dead until somebody happened to click a button, because a click on the
1648
+ * design itself focuses nothing and the keystroke never reached this
1649
+ * element to begin with.
1650
+ *
1651
+ * @param {KeyboardEvent} event
1652
+ * @returns {boolean}
1653
+ */
1654
+ function ours(event) {
1655
+ if (root.contains(event.target)) return true;
1656
+
1657
+ return event.target === doc.body || event.target === doc.documentElement;
1658
+ }
1659
+
1660
+
1661
+ /**
1662
+ * Takes the focus when a click lands on something that cannot hold it.
1663
+ *
1664
+ * The canvas is a div, so clicking the design leaves the caret wherever it
1665
+ * was - which, after a trip to the properties rail, is a text box. Then `z`
1666
+ * types a z instead of zooming, which is correct of the shortcut and
1667
+ * surprising to everyone.
1668
+ *
1669
+ * @param {PointerEvent} event
1670
+ */
1671
+ function takeFocus(event) {
1672
+ const holder = event.target.closest?.(
1673
+ 'input, textarea, select, button, a, label, [tabindex]');
1674
+
1675
+ /**
1676
+ * Root itself carries a tabindex now, so it matches that selector - and
1677
+ * it is the thing being focused, not a reason not to. A browser does
1678
+ * this walk on its own for a container that can hold focus; this is
1679
+ * here so the behaviour is the designer's rather than the browser's.
1680
+ */
1681
+ if (holder && holder !== root) return;
1682
+
1683
+ root.focus({ preventScroll: true });
1684
+ }
1685
+
1686
+
1687
+ /**
1688
+ * The shortcuts everyone tries first. Bound on the document so they are
1689
+ * heard wherever the focus is, and answered only for this designer - see
1690
+ * `ours` - so a second one on the same page keeps its own.
1691
+ */
1692
+ function onShortcut(event) {
1693
+ if (!ours(event)) return;
1694
+
1695
+ const key = event.key.toLowerCase();
1696
+
1697
+ /**
1698
+ * Zoom is one key: z in, alt+z out.
1699
+ *
1700
+ * Before the ctrl guard because it is not a ctrl shortcut - and it must
1701
+ * stay out of ctrl's way, or it would take undo. Held back while a
1702
+ * field has the caret, for the same reason copy is: the rail is full of
1703
+ * boxes people type the letter z into.
1704
+ */
1705
+ if (key === 'z' && !event.ctrlKey && !event.metaKey) {
1706
+ if (event.target.closest?.('input, textarea, select')) return;
1707
+
1708
+ event.preventDefault();
1709
+ stepZoom(event.altKey ? -1 : 1);
1710
+ return;
1711
+ }
1712
+
1713
+ if (!(event.ctrlKey || event.metaKey)) return;
1714
+
1715
+ /**
1716
+ * Copy and paste stay the browser's while a field has the caret, or
1717
+ * while there is text selected. Taking them would break copying a value
1718
+ * out of the rail, which people do far more often than they copy an
1719
+ * item - and a shortcut that works everywhere except where you need it
1720
+ * is worse than one that was never bound.
1721
+ */
1722
+ if (key === 'c' || key === 'v') {
1723
+ if (event.target.closest?.('input, textarea, select')) return;
1724
+ if (key === 'c' && String(globalThis.getSelection?.() ?? '')) return;
1725
+
1726
+ event.preventDefault();
1727
+ act(key === 'c' ? 'copy-items' : 'paste-items');
1728
+ return;
1729
+ }
1730
+
1731
+ if (key === 's') {
1732
+ event.preventDefault();
1733
+ act('save');
1734
+ return;
1735
+ }
1736
+
1737
+ if (key === 'o') {
1738
+ event.preventDefault();
1739
+ act('open');
1740
+ return;
1741
+ }
1742
+
1743
+ if (key === 'e') {
1744
+ event.preventDefault();
1745
+ act('toggle-preview');
1746
+ return;
1747
+ }
1748
+
1749
+ /**
1750
+ * ctrl+0 is the way back to 100% from wherever the z key has got to.
1751
+ * The stepping itself is z's; ctrl +/- is left to the browser here,
1752
+ * which is not something the viewer next door does - a report being
1753
+ * arranged is scrolled and dragged far more than one being read, and a
1754
+ * modifier on every zoom is one modifier too many for that.
1755
+ */
1756
+ if (key === '0') {
1757
+ event.preventDefault();
1758
+ setZoom(1);
1759
+ return;
1760
+ }
1761
+
1762
+ if (key === 'z') {
1763
+ event.preventDefault();
1764
+
1765
+ /**
1766
+ * ctrl+alt+z redoes, as well as the ctrl+shift+z every editor has.
1767
+ * Two spellings of one thing rather than a choice between them:
1768
+ * shift+z is the one people arrive with, and alt+z is the one that
1769
+ * matches the zoom pair next door - z in, alt+z out, so alt is
1770
+ * already the "and back again" key on this keyboard.
1771
+ *
1772
+ * Plain alt+z is the zoom, and cannot be reached from here: the
1773
+ * branch at the top of this function takes it while ctrl is up, and
1774
+ * nothing gets this far without ctrl or meta down.
1775
+ */
1776
+ act(event.shiftKey || event.altKey ? 'redo' : 'undo');
1777
+ return;
1778
+ }
1779
+
1780
+ if (key === 'y') {
1781
+ event.preventDefault();
1782
+ act('redo');
1783
+ return;
1784
+ }
1785
+
1786
+ if (key === 'd') {
1787
+ event.preventDefault();
1788
+ act('duplicate-item');
1789
+ }
1790
+ }
1791
+
1792
+ bar.addEventListener('click', onChromeClick);
1793
+ foot.addEventListener('click', onChromeClick);
1794
+ toasts.addEventListener('click', onChromeClick);
1795
+ root.addEventListener('pointerdown', takeFocus);
1796
+ doc.addEventListener('keydown', onShortcut);
1797
+
1798
+ canvas.addEventListener('contextmenu', onContextMenu);
1799
+ /** the pill is pinned to the page area, so a scroll leaves it behind */
1800
+ canvas.addEventListener('scroll', closeMenu);
1801
+ doc.addEventListener('pointerdown', onDocumentDown);
1802
+ doc.addEventListener('keydown', onMenuKey);
1803
+
1804
+ return {
1805
+ /** the layout as it currently stands - the thing onSave will be given */
1806
+ get layout() { return state.layout; },
1807
+
1808
+ /** 'design' or 'preview' */
1809
+ get mode() { return state.mode; },
1810
+
1811
+ /** run the report, or go back to arranging it */
1812
+ togglePreview,
1813
+
1814
+ /** the data the report is asking for, derived from the layout */
1815
+ get sampleData() { return sampleData(state.layout); },
1816
+
1817
+ /** the item being edited, as `{ band, id }`, or null */
1818
+ /** the item the rail describes - the most recently selected */
1819
+ get selection() { return primary(); },
1820
+
1821
+ /** every selected item, oldest first */
1822
+ get selections() { return [...state.selection]; },
1823
+
1824
+ select: setSelection,
1825
+
1826
+ /** the filename stem this report is saved under, or null */
1827
+ get id() { return state.id; },
1828
+
1829
+ /** whether there are changes the disk has not seen */
1830
+ get dirty() { return state.dirty; },
1831
+
1832
+ /** swap the report being edited */
1833
+ open(next, openId = null) {
1834
+ replaceLayout(
1835
+ isEmptyLayout(next) ? blankLayout() : next,
1836
+ { id: openId, dirty: false });
1837
+
1838
+ history.reset(state.layout);
1839
+ refreshBar();
1840
+
1841
+ return validateLayout(state.layout);
1842
+ },
1843
+
1844
+ /** save it where it came from, asking for a name the first time */
1845
+ save: saveReport,
1846
+
1847
+ redraw: draw,
1848
+
1849
+ destroy() {
1850
+ detach();
1851
+ detachPanel();
1852
+ bar.removeEventListener('click', onChromeClick);
1853
+ foot.removeEventListener('click', onChromeClick);
1854
+ toasts.removeEventListener('click', onChromeClick);
1855
+ root.removeEventListener('pointerdown', takeFocus);
1856
+ doc.removeEventListener('keydown', onShortcut);
1857
+ canvas.removeEventListener('contextmenu', onContextMenu);
1858
+ canvas.removeEventListener('scroll', closeMenu);
1859
+ doc.removeEventListener('pointerdown', onDocumentDown);
1860
+ doc.removeEventListener('keydown', onMenuKey);
1861
+ (doc.defaultView ?? globalThis)
1862
+ .removeEventListener('resize', onViewportResize);
1863
+ view.removeEventListener('beforeunload', onBeforeUnload);
1864
+ zoomPicker?.destroy();
1865
+ closeMenu();
1866
+ clearTimeout(complain.timer);
1867
+ clearTimeout(flashBand.timer);
1868
+ /** a report window shows what was passed to it; it cannot outlive this */
1869
+ for (const opened of windows) opened.destroy();
1870
+ windows.clear();
1871
+
1872
+ root.innerHTML = '';
1873
+ root.classList.remove('report-designer');
1874
+ }
1875
+ };
1876
+ }
1877
+
1878
+
1879
+ function chrome(layout) {
1880
+ const size = layout.page
1881
+ ? `${layout.page.width} &times; ${layout.page.height}`
1882
+ : '';
1883
+
1884
+ return `
1885
+ <header class="dz-bar" data-role="bar">
1886
+ <span class="dz-brand">Report Studio</span>
1887
+
1888
+ <span class="dz-title">
1889
+ <span class="dz-name" data-role="name">${escapeText(layout.name ?? '')}</span>
1890
+ <span class="dz-status" data-role="status">Not saved yet</span>
1891
+ </span>
1892
+
1893
+ <div class="dz-bar-group">
1894
+ <button type="button" class="dz-tool" data-role="undo" data-action="undo"
1895
+ title="Undo (ctrl+Z)" aria-label="Undo" disabled
1896
+ >${icon('undo')}</button>
1897
+ <button type="button" class="dz-tool" data-role="redo" data-action="redo"
1898
+ title="Redo (ctrl+alt+Z or ctrl+shift+Z)" aria-label="Redo" disabled
1899
+ >${icon('redo')}</button>
1900
+ </div>
1901
+
1902
+ <div class="dz-bar-group">
1903
+ <button type="button" class="dz-tool" data-action="open"
1904
+ title="Open a report (ctrl+O)" aria-label="Open a report"
1905
+ >${icon('open')}</button>
1906
+ <button type="button" class="dz-tool" data-action="save"
1907
+ title="Save (ctrl+S)" aria-label="Save"
1908
+ >${icon('save')}</button>
1909
+ <button type="button" class="dz-tool" data-action="data"
1910
+ title="The data this report needs" aria-label="Report data"
1911
+ >${icon('data')}</button>
1912
+ </div>
1913
+
1914
+ <div class="dz-bar-group">
1915
+ <button type="button" class="dz-tool" data-role="rulers"
1916
+ data-action="toggle-rulers"
1917
+ title="Rulers and guides - drag off a ruler to place one"
1918
+ aria-label="Rulers and guides" aria-pressed="false"
1919
+ >${icon('ruler')}</button>
1920
+ <button type="button" class="dz-tool" data-action="toggle-preview"
1921
+ title="Run the report (ctrl+E)" aria-label="Run the report"
1922
+ aria-pressed="false"
1923
+ >${icon('preview')}</button>
1924
+
1925
+ <!--
1926
+ A button, not a link: the window is built from the design as it
1927
+ stands rather than fetched from a URL, so it works on a report
1928
+ that has never been saved - which a link to the preview screen
1929
+ could not, because that screen reads the report off the disk.
1930
+ -->
1931
+ <button type="button" class="dz-tool" data-role="open-preview"
1932
+ data-action="open-window"
1933
+ title="Open the report in its own window"
1934
+ aria-label="Open the report in its own window"
1935
+ >${icon('external')}</button>
1936
+ </div>
1937
+
1938
+ <span class="dz-pages" data-role="pages"></span>
1939
+ <span class="dz-size" data-role="size">${size}</span>
1940
+
1941
+ <!--
1942
+ The same three controls the viewer has, in the same order and with
1943
+ the same shortcuts. A designer and a preview of the same report
1944
+ should not zoom differently.
1945
+ -->
1946
+ <div class="dz-bar-group dz-zoom-group">
1947
+ <button type="button" class="dz-tool" data-role="zoom-out"
1948
+ data-action="zoom-out"
1949
+ title="Zoom out (alt+Z)" aria-label="Zoom out">&#8722;</button>
1950
+
1951
+ <div class="dropdown" data-role="zoom-dropdown">
1952
+ <button type="button" class="dropdown-trigger" data-role="zoom"
1953
+ aria-haspopup="listbox" aria-expanded="false"
1954
+ aria-label="Zoom level">
1955
+ <span class="dropdown-value">100%</span>
1956
+ <span class="dropdown-caret" aria-hidden="true"></span>
1957
+ </button>
1958
+
1959
+ <ul class="dropdown-menu" data-role="zoom-menu" role="listbox"
1960
+ aria-label="Zoom level" hidden>
1961
+ <li class="dropdown-item" role="option" tabindex="-1"
1962
+ data-value="fit">Fit width</li>
1963
+ ${ZOOM_STEPS.map(step => `
1964
+ <li class="dropdown-item" role="option" tabindex="-1"
1965
+ data-value="${step}"${step === 1 ? ' data-selected="true"' : ''}
1966
+ >${Math.round(step * 100)}%</li>`).join('')}
1967
+ </ul>
1968
+ </div>
1969
+
1970
+ <button type="button" class="dz-tool" data-role="zoom-in"
1971
+ data-action="zoom-in"
1972
+ title="Zoom in (Z)" aria-label="Zoom in">&#43;</button>
1973
+ </div>
1974
+ </header>
1975
+
1976
+ <div class="dz-body">
1977
+ <div class="dz-main">
1978
+ <div class="dz-canvas" data-role="canvas">
1979
+ <!--
1980
+ Two boxes for one job. The inner one is scaled, and a
1981
+ transform changes nothing about layout - so at 200% there
1982
+ would be nothing to scroll. The outer one is given the
1983
+ scaled size in px, and is what the canvas scrolls.
1984
+ -->
1985
+ <div class="dz-stage" data-role="stage">
1986
+ <div class="dz-zoom-layer" data-role="zoom-layer"></div>
1987
+ </div>
1988
+ </div>
1989
+
1990
+ <!--
1991
+ The tools sit under the page rather than in the bar: the bar is
1992
+ about the report as a whole, and these act on the band you are
1993
+ looking at. Icon-only, so the strip stays out of the way of the
1994
+ thing being designed - the label lives on the button for a
1995
+ screen reader and in the tooltip for everyone else.
1996
+ -->
1997
+ <footer class="dz-foot" data-role="foot">
1998
+ <button type="button" class="dz-tool" data-action="add-text"
1999
+ title="Add a text box" aria-label="Add a text box"
2000
+ >${icon('text')}</button>
2001
+ <button type="button" class="dz-tool" data-role="add-table"
2002
+ data-action="add-table"
2003
+ title="Add a table" aria-label="Add a table"
2004
+ >${icon('table')}</button>
2005
+ <button type="button" class="dz-tool" data-action="add-line"
2006
+ title="Add a line" aria-label="Add a line"
2007
+ >${icon('line')}</button>
2008
+ <button type="button" class="dz-tool" data-action="add-box"
2009
+ title="Add a box" aria-label="Add a box"
2010
+ >${icon('box')}</button>
2011
+ <button type="button" class="dz-tool" data-action="add-image"
2012
+ title="Add an image" aria-label="Add an image"
2013
+ >${icon('image')}</button>
2014
+ <button type="button" class="dz-tool" data-action="add-field"
2015
+ title="Insert a page number, date or total"
2016
+ aria-label="Insert a field"
2017
+ >${icon('field')}</button>
2018
+ </footer>
2019
+
2020
+ <!--
2021
+ The corner messages, in the page area rather than the window.
2022
+ Pinned to the window they would hang over the properties rail -
2023
+ which is where the band switches are, and so where most of what
2024
+ the validator complains about is actually fixed.
2025
+ -->
2026
+ <div class="dz-toasts" data-role="toasts"></div>
2027
+ </div>
2028
+
2029
+ <aside class="dz-panel" data-role="panel" aria-label="Properties"></aside>
2030
+ </div>`;
2031
+ }
2032
+
2033
+
2034
+ /**
2035
+ * The validator already writes in the user's terms - "bands[2].items[0].value
2036
+ * must be a string" - so this only has to show the list rather than translate it.
2037
+ */
2038
+ /**
2039
+ * An item id comes from a hand-written layout file, so it can hold anything.
2040
+ * CSS.escape is absent in some test environments, hence the fallback.
2041
+ */
2042
+ function cssEscape(value) {
2043
+ const text = String(value);
2044
+ return globalThis.CSS?.escape ? CSS.escape(text) : JSON.stringify(text).slice(1, -1);
2045
+ }
2046
+
2047
+
2048
+ function escapeText(value) {
2049
+ if (value == null) return '';
2050
+ return String(value)
2051
+ .replace(/&/g, '&amp;')
2052
+ .replace(/</g, '&lt;')
2053
+ .replace(/>/g, '&gt;');
2054
+ }