report-studio 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +238 -4
  3. package/dist/designer.js +3209 -0
  4. package/dist/index.js +2 -4
  5. package/dist/viewer-D-c0lKzQ.js +1576 -0
  6. package/package.json +66 -33
  7. package/src/asset/images/icon.png +0 -0
  8. package/src/asset/images/logo.png +0 -0
  9. package/src/cli/index.js +282 -0
  10. package/src/cli/serve.js +135 -0
  11. package/src/designer/blank.js +53 -0
  12. package/src/designer/canvas.js +518 -0
  13. package/src/designer/designer.js +1900 -0
  14. package/src/designer/dialog.js +708 -0
  15. package/src/designer/fields.js +584 -0
  16. package/src/designer/geometry.js +154 -0
  17. package/src/designer/guides.js +370 -0
  18. package/src/designer/history.js +113 -0
  19. package/src/designer/icons.js +118 -0
  20. package/src/designer/index.html +28 -0
  21. package/src/designer/main.js +39 -0
  22. package/src/designer/menu.js +126 -0
  23. package/src/designer/panel.js +478 -0
  24. package/src/designer/preview.js +95 -0
  25. package/src/designer/rulers.js +231 -0
  26. package/src/designer/sample-data.js +240 -0
  27. package/src/designer/select.js +699 -0
  28. package/src/designer/structure.js +604 -0
  29. package/src/designer/styles.css +1616 -0
  30. package/src/designer/toast.js +62 -0
  31. package/src/designer/tokens.js +284 -0
  32. package/src/engine/csv.js +315 -0
  33. package/src/engine/group.js +304 -0
  34. package/src/engine/index.js +34 -0
  35. package/src/engine/measure.js +390 -0
  36. package/src/engine/paginate.js +861 -0
  37. package/src/engine/regions.js +175 -0
  38. package/src/engine/resolve.js +171 -0
  39. package/src/engine/search.js +129 -0
  40. package/src/engine/text-metrics.js +206 -0
  41. package/src/engine/validate.js +328 -0
  42. package/src/index.html +79 -0
  43. package/src/index.js +50 -0
  44. package/src/preview/chrome.css +505 -0
  45. package/src/preview/chrome.js +147 -0
  46. package/src/preview/index.html +28 -0
  47. package/src/preview/main.js +66 -0
  48. package/src/preview/styles.css +16 -0
  49. package/src/preview/viewer.js +745 -0
  50. package/src/render/items.js +425 -0
  51. package/src/render/render.js +98 -0
  52. package/src/render/report.css +202 -0
  53. package/src/server/routes.js +331 -0
  54. package/src/shared/brand.css +29 -0
  55. package/src/shared/dropdown.css +136 -0
  56. package/src/shared/dropdown.js +166 -0
  57. package/src/shared/modal.css +125 -0
  58. package/src/shared/prefix.js +13 -0
  59. package/src/shared/store.js +145 -0
  60. package/src/shared/theme.css +72 -0
  61. package/src/shared/window.js +138 -0
  62. package/src/vite/index.js +53 -0
  63. package/dist/react.js +0 -4
@@ -0,0 +1,708 @@
1
+ /**
2
+ * dialog.js is the designer's modal, and the one it currently needs: how many
3
+ * columns a new table starts with.
4
+ *
5
+ * Hand-written rather than <dialog>, matching the preview - that element is
6
+ * still unimplemented in the environment the specs run in, and a stubbed
7
+ * showModal would test the stub instead of the behaviour. The shell's
8
+ * appearance is shared/modal.css, so both screens' dialogs are the same object.
9
+ *
10
+ * It resolves a promise rather than taking a callback: `const n = await
11
+ * askColumns(root)` reads as the question it is, and cancelling is one `null`
12
+ * rather than a second branch to wire.
13
+ */
14
+
15
+ import { DEFAULT_COLUMNS } from './structure.js';
16
+ import { toId } from '../shared/store.js';
17
+ import { esc } from '../render/items.js';
18
+ import { createDropdown } from '../shared/dropdown.js';
19
+ import {
20
+ TOKENS, findToken, needsField, resolvesIn, tokenItem, aggregateScope,
21
+ availableFields, bandChoices, defaultBand
22
+ } from './tokens.js';
23
+
24
+
25
+ /** the same ceiling the rail can comfortably list back to you */
26
+ const MAX_COLUMNS = 20;
27
+
28
+
29
+ /**
30
+ * Asks how many columns a new table should have.
31
+ *
32
+ * @param {Element} root the designer's own element, so the dialog is torn down
33
+ * with it rather than left on document.body
34
+ * @returns {Promise<number|null>} the count, or null if it was cancelled
35
+ */
36
+ export function askColumns(root) {
37
+ return open(root, 'column-dialog', columnsMarkup(), (host, done) => {
38
+ const field = host.querySelector('[data-role="count"]');
39
+
40
+ /** focus and select, so typing a different number replaces it */
41
+ field.focus();
42
+ field.select();
43
+
44
+ host.querySelector('form').addEventListener('submit', event => {
45
+ event.preventDefault();
46
+
47
+ const count = Math.round(Number(field.value));
48
+ done(Number.isFinite(count) && count > 0
49
+ ? Math.min(count, MAX_COLUMNS)
50
+ : DEFAULT_COLUMNS);
51
+ });
52
+ });
53
+ }
54
+
55
+
56
+ /**
57
+ * Asks which report to open.
58
+ *
59
+ * The list is what the server found on disk, so a report that will not parse is
60
+ * still offered - it is the one most in need of opening. It is marked, and
61
+ * loading it will fail with the server's own words rather than silently.
62
+ *
63
+ * @param {Element} root
64
+ * @param {object[]} reports `{ id, name, updatedAt, readable }`
65
+ * @returns {Promise<{id: string}|{blank: true}|null>}
66
+ */
67
+ export function askReport(root, reports) {
68
+ const list = reports || [];
69
+
70
+ return open(root, 'open-dialog', reportsMarkup(list), (host, done) => {
71
+ host.querySelector('[data-role="new"]')
72
+ ?.addEventListener('click', () => done({ blank: true }));
73
+
74
+ const wrapper = host.querySelector('[data-role="report-dropdown"]');
75
+ const confirm = host.querySelector('[data-role="confirm"]');
76
+
77
+ if (!wrapper || !list.length) {
78
+ host.querySelector('[data-role="new"]')?.focus();
79
+ return;
80
+ }
81
+
82
+ const picker = createDropdown(wrapper);
83
+ const meta = host.querySelector('[data-role="report-meta"]');
84
+
85
+ /**
86
+ * The name is what someone is choosing by; the filename and the date
87
+ * are what they check they picked the right one with. A dropdown shows
88
+ * one line, so the rest goes underneath it rather than being lost.
89
+ */
90
+ const describe = () => {
91
+ const chosen = list.find(r => r.id === picker.value) ?? list[0];
92
+ if (!chosen) return;
93
+
94
+ meta.textContent = `${chosen.id}.json${
95
+ chosen.readable === false ? ' - will not parse' : ''
96
+ }${when(chosen.updatedAt)}`;
97
+
98
+ meta.toggleAttribute('data-unreadable', chosen.readable === false);
99
+ };
100
+
101
+ picker.addEventListener('change', describe);
102
+ describe();
103
+
104
+ confirm.addEventListener('click', () => done({ id: picker.value }));
105
+ confirm.focus();
106
+
107
+ /** the dropdown listens on document while it is open */
108
+ host.addEventListener('dz-closing', () => picker.destroy());
109
+ });
110
+ }
111
+
112
+
113
+ /**
114
+ * Asks what to call a report that has not been saved before.
115
+ *
116
+ * The id is shown as it is typed, because the id is the filename and someone
117
+ * naming a report "Sales / June" should see `sales-june` before it is written
118
+ * rather than wonder later where the file went.
119
+ *
120
+ * @param {Element} root
121
+ * @param {string} [suggested] the report's current name
122
+ * @returns {Promise<{id: string, name: string}|null>}
123
+ */
124
+ export function askName(root, suggested = '') {
125
+ return open(root, 'save-dialog', nameMarkup(suggested), (host, done) => {
126
+ const field = host.querySelector('[data-role="report-name"]');
127
+ const shown = host.querySelector('[data-role="filename"]');
128
+ const confirm = host.querySelector('[data-role="confirm"]');
129
+
130
+ const refresh = () => {
131
+ const id = toId(field.value);
132
+
133
+ shown.textContent = id ? `${id}.json` : 'needs a letter or a digit';
134
+ confirm.disabled = !id;
135
+ };
136
+
137
+ field.addEventListener('input', refresh);
138
+ refresh();
139
+
140
+ field.focus();
141
+ field.select();
142
+
143
+ host.querySelector('form').addEventListener('submit', event => {
144
+ event.preventDefault();
145
+
146
+ const id = toId(field.value);
147
+ if (id) done({ id, name: field.value.trim() || id });
148
+ });
149
+ });
150
+ }
151
+
152
+
153
+ /**
154
+ * Asks whether to leave a report with changes the disk has not seen.
155
+ *
156
+ * Answered `false` by everything except the discard button - escape, the
157
+ * backdrop, the close of the dialog. Somebody who dismisses a question about
158
+ * losing work has not agreed to lose it, and the safe answer is the one that
159
+ * costs a second click rather than an afternoon.
160
+ *
161
+ * Keeping is the primary button and takes the focus for the same reason: enter
162
+ * is what a dialog gets pressed at, and enter here means "not that".
163
+ *
164
+ * @param {Element} root
165
+ * @param {string} [name] the report's name, so the question says which
166
+ * @returns {Promise<boolean>} true only when discard was chosen
167
+ */
168
+ export function askDiscard(root, name = '') {
169
+ return open(root, 'discard-dialog', discardMarkup(name), (host, done) => {
170
+ host.querySelector('[data-role="discard"]')
171
+ .addEventListener('click', () => done(true));
172
+
173
+ host.querySelector('[data-role="cancel"]').focus();
174
+ }).then(answer => answer === true);
175
+ }
176
+
177
+
178
+ /**
179
+ * The shell every dialog shares: mount, focus, wire cancel, resolve once.
180
+ *
181
+ * @param {Element} root
182
+ * @param {string} role
183
+ * @param {string} body
184
+ * @param {(host: Element, done: (value: any) => void) => void} wire
185
+ * @returns {Promise<any>} whatever `done` was given, or null if cancelled
186
+ */
187
+ function open(root, role, body, wire) {
188
+ return new Promise(resolve => {
189
+ /** created in the document the designer is mounted in, not always this one */
190
+ const host = root.ownerDocument.createElement('div');
191
+ host.className = 'modal';
192
+ host.dataset.role = role;
193
+ host.innerHTML = body;
194
+
195
+ root.appendChild(host);
196
+
197
+ let settled = false;
198
+
199
+ function close(value) {
200
+ if (settled) return;
201
+
202
+ settled = true;
203
+ /** so a dropdown inside can drop its document listener */
204
+ host.dispatchEvent(new CustomEvent('dz-closing'));
205
+ host.remove();
206
+ resolve(value);
207
+ }
208
+
209
+ /**
210
+ * Listened for on the dialog itself, not on document.
211
+ *
212
+ * A document listener outlives the element: destroying the designer
213
+ * takes the dialog out of the DOM without ever calling close, and the
214
+ * listener stays behind swallowing every later escape. On the host it
215
+ * goes when the host goes, and there is nothing to remember to clean up.
216
+ *
217
+ * Captured, and stopped, because select.js listens for escape too and
218
+ * would drop the selection behind the dialog being cancelled.
219
+ */
220
+ function onKey(event) {
221
+ if (event.key !== 'Escape') return;
222
+
223
+ event.stopPropagation();
224
+ event.preventDefault();
225
+ close(null);
226
+ }
227
+
228
+ for (const node of host.querySelectorAll('[data-role="cancel"], [data-role="backdrop"]')) {
229
+ node.addEventListener('click', () => close(null));
230
+ }
231
+
232
+ host.addEventListener('keydown', onKey, true);
233
+
234
+ wire(host, close);
235
+ });
236
+ }
237
+
238
+
239
+ function columnsMarkup() {
240
+ return `
241
+ <div class="modal-backdrop" data-role="backdrop"></div>
242
+
243
+ <div class="modal-card" role="dialog" aria-modal="true"
244
+ aria-labelledby="dz-columns-title">
245
+ <h2 id="dz-columns-title">Add table</h2>
246
+
247
+ <form>
248
+ <div class="dz-field dz-field-count">
249
+ <label for="dz-columns">Columns</label>
250
+ <input type="number" id="dz-columns" data-role="count"
251
+ value="${DEFAULT_COLUMNS}" min="1" max="${MAX_COLUMNS}"
252
+ step="1" required>
253
+ </div>
254
+
255
+ <p class="modal-summary">
256
+ Each column starts 50px wide. Rows come from your data, so there
257
+ is no count to set here.
258
+ </p>
259
+
260
+ <div class="modal-actions">
261
+ <button type="button" data-role="cancel">Cancel</button>
262
+ <button type="submit" class="is-primary" data-role="confirm">Add</button>
263
+ </div>
264
+ </form>
265
+ </div>`;
266
+ }
267
+
268
+
269
+ /**
270
+ * The report list.
271
+ *
272
+ * Names, not filenames - "Sales summary" is how someone thinks of a report, and
273
+ * the id underneath it is only interesting when it is about to become a file.
274
+ */
275
+ function reportsMarkup(reports) {
276
+ const list = reports || [];
277
+
278
+ const options = list.map((report, index) => `
279
+ <li class="dropdown-item" role="option" tabindex="-1"
280
+ data-value="${esc(report.id)}"
281
+ ${index === 0 ? 'data-selected="true"' : ''}
282
+ >${esc(report.name || report.id)}</li>`).join('');
283
+
284
+ const picker = `
285
+ <div class="dz-field dz-field-picker">
286
+ <label id="dz-open-label">Report</label>
287
+
288
+ <div class="dropdown" data-role="report-dropdown">
289
+ <button type="button" class="dropdown-trigger"
290
+ aria-haspopup="listbox" aria-expanded="false"
291
+ aria-labelledby="dz-open-label">
292
+ <span class="dropdown-value"></span>
293
+ <span class="dropdown-caret" aria-hidden="true"></span>
294
+ </button>
295
+
296
+ <ul class="dropdown-menu" role="listbox"
297
+ aria-labelledby="dz-open-label" hidden>${options}</ul>
298
+ </div>
299
+ </div>
300
+
301
+ <p class="dz-report-meta" data-role="report-meta" aria-live="polite"></p>`;
302
+
303
+ return `
304
+ <div class="modal-backdrop" data-role="backdrop"></div>
305
+
306
+ <div class="modal-card is-roomy" role="dialog" aria-modal="true"
307
+ aria-labelledby="dz-open-title">
308
+ <h2 id="dz-open-title">Open report</h2>
309
+
310
+ ${list.length ? picker : `<p class="modal-summary">
311
+ No reports saved yet. Start a new one and save it.</p>`}
312
+
313
+ <div class="modal-actions">
314
+ <button type="button" data-role="cancel">Cancel</button>
315
+ <button type="button" data-role="new">New report</button>
316
+ ${list.length
317
+ ? `<button type="button" class="is-primary" data-role="confirm">Open</button>`
318
+ : ''}
319
+ </div>
320
+ </div>`;
321
+ }
322
+
323
+
324
+ /**
325
+ * A date, said the way a person would. Exact times are noise for a file that
326
+ * was touched this afternoon, and wrong for one touched last year.
327
+ */
328
+ function when(iso) {
329
+ if (!iso) return '';
330
+
331
+ const at = new Date(iso);
332
+ if (Number.isNaN(at.getTime())) return '';
333
+
334
+ return ` - ${at.toLocaleDateString(undefined, {
335
+ day: 'numeric', month: 'short', year: 'numeric'
336
+ })}`;
337
+ }
338
+
339
+
340
+ function nameMarkup(suggested) {
341
+ return `
342
+ <div class="modal-backdrop" data-role="backdrop"></div>
343
+
344
+ <div class="modal-card" role="dialog" aria-modal="true"
345
+ aria-labelledby="dz-save-title">
346
+ <h2 id="dz-save-title">Save report</h2>
347
+
348
+ <form>
349
+ <div class="dz-field dz-field-text">
350
+ <label for="dz-save-name">Name</label>
351
+ <input type="text" id="dz-save-name" data-role="report-name"
352
+ value="${esc(suggested)}" spellcheck="false" required>
353
+ </div>
354
+
355
+ <p class="modal-summary">
356
+ Saved as <code data-role="filename"></code>
357
+ </p>
358
+
359
+ <div class="modal-actions">
360
+ <button type="button" data-role="cancel">Cancel</button>
361
+ <button type="submit" class="is-primary" data-role="confirm">Save</button>
362
+ </div>
363
+ </form>
364
+ </div>`;
365
+ }
366
+
367
+
368
+ /**
369
+ * The unsaved-changes question.
370
+ *
371
+ * Discard sits on the left as the plain button and keeping takes the accent,
372
+ * because the accent is where the eye goes and the eye should not be led to the
373
+ * one that throws work away.
374
+ */
375
+ function discardMarkup(name) {
376
+ const subject = name ? `<strong>${esc(name)}</strong>` : 'This report';
377
+
378
+ return `
379
+ <div class="modal-backdrop" data-role="backdrop"></div>
380
+
381
+ <div class="modal-card" role="dialog" aria-modal="true"
382
+ aria-labelledby="dz-discard-title">
383
+ <h2 id="dz-discard-title">Unsaved changes</h2>
384
+
385
+ <p class="modal-summary">
386
+ ${subject} has changes that have not been saved. Opening another
387
+ report closes this one, and the changes go with it.
388
+ </p>
389
+
390
+ <div class="modal-actions">
391
+ <button type="button" class="is-danger" data-role="discard">Discard changes</button>
392
+ <button type="button" class="is-primary" data-role="cancel">Keep editing</button>
393
+ </div>
394
+ </div>`;
395
+ }
396
+
397
+
398
+ /**
399
+ * Shows the data the report is asking for, and lets it be replaced.
400
+ *
401
+ * This is the answer to a real question a layout does not otherwise answer:
402
+ * *what do I have to supply?* The keys are read off the layout - every
403
+ * placeholder, every column field, the dataset and the grouping field - so the
404
+ * payload shown is the exact shape the engine will look for. Filling in real
405
+ * values over the samples is then a matter of typing, not of guessing.
406
+ *
407
+ * @param {Element} root
408
+ * @param {object} data the payload to show
409
+ * @param {object} [options]
410
+ * @param {string|null} [options.id] the report's id, for naming the file
411
+ * @param {boolean} [options.generated] whether this was derived rather than loaded
412
+ * @returns {Promise<object|null>} the edited payload, or null if cancelled
413
+ */
414
+ export function askData(root, data, { id = null, generated = false } = {}) {
415
+ return open(root, 'data-dialog', dataMarkup(data, id, generated), (host, done) => {
416
+ const field = host.querySelector('[data-role="payload"]');
417
+ const problem = host.querySelector('[data-role="parse-error"]');
418
+ const confirm = host.querySelector('[data-role="confirm"]');
419
+
420
+ /**
421
+ * Checked as it is typed rather than on submit: a payload someone has
422
+ * pasted and broken should say so beside the box, not after the click
423
+ * that was meant to save it.
424
+ */
425
+ const check = () => {
426
+ try {
427
+ const parsed = JSON.parse(field.value);
428
+ const usable = parsed != null && typeof parsed === 'object'
429
+ && !Array.isArray(parsed);
430
+
431
+ problem.textContent = usable
432
+ ? ''
433
+ : 'The payload must be a JSON object keyed by dataset name.';
434
+ confirm.disabled = !usable;
435
+ } catch (error) {
436
+ problem.textContent = error.message;
437
+ confirm.disabled = true;
438
+ }
439
+ };
440
+
441
+ field.addEventListener('input', check);
442
+ check();
443
+
444
+ field.focus();
445
+
446
+ confirm.addEventListener('click', () => {
447
+ try {
448
+ done(JSON.parse(field.value));
449
+ } catch {
450
+ /* the box already says why; leave the dialog open */
451
+ }
452
+ });
453
+ });
454
+ }
455
+
456
+
457
+ function dataMarkup(data, id, generated) {
458
+ const file = id ? `${id}.data.json` : 'a .data.json beside the report';
459
+
460
+ return `
461
+ <div class="modal-backdrop" data-role="backdrop"></div>
462
+
463
+ <div class="modal-card is-wide" role="dialog" aria-modal="true"
464
+ aria-labelledby="dz-data-title">
465
+ <h2 id="dz-data-title">Report data</h2>
466
+
467
+ <p class="modal-summary">
468
+ ${generated
469
+ ? `These keys were read off the report - every placeholder, every
470
+ column, and the field it groups by. Replace the sample values
471
+ with real ones.`
472
+ : `The data this report is currently previewed with.`}
473
+ Saved as <code>${esc(file)}</code>.
474
+ </p>
475
+
476
+ <textarea class="dz-payload" data-role="payload" rows="16"
477
+ spellcheck="false" aria-label="Report data"
478
+ >${esc(JSON.stringify(data, null, 2))}</textarea>
479
+
480
+ <p class="dz-parse-error" data-role="parse-error" aria-live="polite"></p>
481
+
482
+ <div class="modal-actions">
483
+ <button type="button" data-role="cancel">Cancel</button>
484
+ <button type="button" class="is-primary" data-role="confirm">Save data</button>
485
+ </div>
486
+ </div>`;
487
+ }
488
+
489
+
490
+ /**
491
+ * Asks which field to insert, and where.
492
+ *
493
+ * The list is spec 3.4's placeholder table made clickable. Each row shows the
494
+ * text it will insert, so the syntax is learned by using it rather than looked
495
+ * up - and the two things that are easy to get wrong, the field name inside an
496
+ * aggregate and the band it has to sit in to resolve at all, are picked from
497
+ * what the report actually has rather than typed.
498
+ *
499
+ * @param {Element} root
500
+ * @param {object} layout
501
+ * @param {string|null} [current] the band the selection is on
502
+ * @returns {Promise<{value: string, band: string, align: string, w: number}|null>}
503
+ */
504
+ export function askToken(root, layout, current = null) {
505
+ const fields = availableFields(layout);
506
+
507
+ return open(root, 'token-dialog', tokenMarkup(layout, fields, current),
508
+ (host, done) => {
509
+ const fieldRow = host.querySelector('[data-role="field-row"]');
510
+ const warning = host.querySelector('[data-role="token-warning"]');
511
+ const confirm = host.querySelector('[data-role="confirm"]');
512
+
513
+ const fieldPicker = fields.length
514
+ ? createDropdown(host.querySelector('[data-role="field-dropdown"]'))
515
+ : null;
516
+
517
+ const bandWrapper = host.querySelector('[data-role="band-dropdown"]');
518
+ let bandPicker = null;
519
+
520
+ const chosen = () => findToken(
521
+ host.querySelector('[name="dz-token"]:checked')?.value);
522
+
523
+ /**
524
+ * The band list is rebuilt per token, not merely re-selected: an
525
+ * aggregate has fewer places it can go than a page number does, and
526
+ * leaving the others listed offers a choice that prints nothing.
527
+ *
528
+ * The whole wrapper is replaced rather than just the menu, because
529
+ * createDropdown binds to the trigger - reusing it would leave the
530
+ * old listeners attached and every click would toggle twice.
531
+ */
532
+ function rebuildBands(token) {
533
+ bandPicker?.destroy();
534
+
535
+ const choices = bandChoices(layout, token);
536
+ const wanted = defaultBand(layout, token, current);
537
+
538
+ bandWrapper.innerHTML = listbox('band',
539
+ choices.map(b => ({ value: b, label: b })), wanted);
540
+
541
+ bandPicker = createDropdown(bandWrapper);
542
+ bandPicker.addEventListener('change', () => refresh());
543
+ }
544
+
545
+ function refresh({ retarget = false } = {}) {
546
+ const token = chosen();
547
+ if (!token) return;
548
+
549
+ fieldRow.hidden = !needsField(token);
550
+
551
+ if (retarget) rebuildBands(token);
552
+
553
+ const band = bandPicker.value;
554
+ const ok = resolvesIn(token, band);
555
+ const note = ok ? scopeNote(token, band) : aggregateNote(token, band);
556
+
557
+ warning.textContent = note;
558
+ warning.hidden = !note;
559
+ warning.classList.toggle('is-note', ok);
560
+
561
+ /**
562
+ * Not disabled. It is the author's report, and an item placed
563
+ * somewhere it prints nothing today may be somewhere it prints
564
+ * tomorrow - the warning is what they need, not a refusal.
565
+ */
566
+ confirm.textContent = ok ? 'Insert' : 'Insert anyway';
567
+ }
568
+
569
+ for (const radio of host.querySelectorAll('[name="dz-token"]')) {
570
+ radio.addEventListener('change', () => refresh({ retarget: true }));
571
+ }
572
+
573
+ /** rebuildBands attaches the change listener each time it runs */
574
+ refresh({ retarget: true });
575
+
576
+ confirm.addEventListener('click', () => {
577
+ const token = chosen();
578
+ if (!token) return;
579
+
580
+ const field = needsField(token)
581
+ ? (fieldPicker?.value || 'field')
582
+ : undefined;
583
+
584
+ done({ ...tokenItem(token, field), band: bandPicker.value });
585
+ });
586
+
587
+ host.querySelector('[name="dz-token"]')?.focus();
588
+
589
+ host.addEventListener('dz-closing', () => {
590
+ fieldPicker?.destroy();
591
+ bandPicker?.destroy();
592
+ });
593
+ });
594
+ }
595
+
596
+
597
+ function aggregateNote(token, band) {
598
+ return `${token.label} prints nothing in a ${band}.`;
599
+ }
600
+
601
+
602
+ /**
603
+ * What the chosen band means for an aggregate.
604
+ *
605
+ * An aggregate resolves wherever it is put, so there is nothing left to warn
606
+ * about - but `{sum(price)}` is a different number in a group footer and in a
607
+ * report footer, and both of them are right. Which one is being asked for is
608
+ * the thing worth saying, and the dialog is the last moment anyone will be
609
+ * looking at the question.
610
+ */
611
+ function scopeNote(token, band) {
612
+ const scope = aggregateScope(token, band);
613
+
614
+ if (scope === 'group') {
615
+ return `In a ${band}, ${token.label.toLowerCase()} is worked out over ` +
616
+ `each group's own rows, once per group.`;
617
+ }
618
+
619
+ if (scope === 'report') {
620
+ return `In a ${band}, ${token.label.toLowerCase()} is worked out over ` +
621
+ `every row in the report.`;
622
+ }
623
+
624
+ return '';
625
+ }
626
+
627
+
628
+ function tokenMarkup(layout, fields, current) {
629
+ const first = TOKENS[0];
630
+
631
+ const rows = TOKENS.map((token, index) => `
632
+ <label class="dz-token">
633
+ <input type="radio" name="dz-token" value="${esc(token.id)}"
634
+ ${index === 0 ? 'checked' : ''}>
635
+ <span class="dz-token-body">
636
+ <span class="dz-token-name">${esc(token.label)}</span>
637
+ <code class="dz-token-syntax">${esc(token.value)}</code>
638
+ ${token.note ? `<span class="dz-token-note">${esc(token.note)}</span>` : ''}
639
+ </span>
640
+ </label>`).join('');
641
+
642
+ return `
643
+ <div class="modal-backdrop" data-role="backdrop"></div>
644
+
645
+ <div class="modal-card is-roomy" role="dialog" aria-modal="true"
646
+ aria-labelledby="dz-token-title">
647
+ <h2 id="dz-token-title">Insert field</h2>
648
+
649
+ <div class="dz-tokens" role="radiogroup" aria-labelledby="dz-token-title">
650
+ ${rows}
651
+ </div>
652
+
653
+ ${picker('field', 'Field', fields.map(f => ({ value: f, label: f })),
654
+ fields[0], { hidden: !needsField(first), empty: 'No fields yet - add a table first' })}
655
+
656
+ ${picker('band', 'Band',
657
+ bandChoices(layout, first).map(b => ({ value: b, label: b })),
658
+ defaultBand(layout, first, current))}
659
+
660
+ <p class="dz-token-warning" data-role="token-warning" aria-live="polite" hidden></p>
661
+
662
+ <div class="modal-actions">
663
+ <button type="button" data-role="cancel">Cancel</button>
664
+ <button type="button" class="is-primary" data-role="confirm">Insert</button>
665
+ </div>
666
+ </div>`;
667
+ }
668
+
669
+
670
+ /** one labelled listbox, the shape createDropdown expects */
671
+ function picker(role, label, options, selected, { hidden = false, empty = '' } = {}) {
672
+ if (!options.length) {
673
+ return `<p class="modal-summary">${esc(empty)}</p>`;
674
+ }
675
+
676
+ return `
677
+ <div class="dz-field dz-field-picker" data-role="${role}-row"${hidden ? ' hidden' : ''}>
678
+ <label id="dz-${role}-label">${esc(label)}</label>
679
+
680
+ <div class="dropdown" data-role="${role}-dropdown">
681
+ ${listbox(role, options, selected)}
682
+ </div>
683
+ </div>`;
684
+ }
685
+
686
+
687
+ /**
688
+ * The trigger and the menu, without the wrapper - so the contents can be
689
+ * replaced on their own when the options change.
690
+ */
691
+ function listbox(role, options, selected) {
692
+ return `
693
+ <button type="button" class="dropdown-trigger"
694
+ aria-haspopup="listbox" aria-expanded="false"
695
+ aria-labelledby="dz-${role}-label">
696
+ <span class="dropdown-value"></span>
697
+ <span class="dropdown-caret" aria-hidden="true"></span>
698
+ </button>
699
+
700
+ <ul class="dropdown-menu" role="listbox"
701
+ aria-labelledby="dz-${role}-label" hidden>
702
+ ${options.map(o => `
703
+ <li class="dropdown-item" role="option" tabindex="-1"
704
+ data-value="${esc(o.value)}"
705
+ ${o.value === selected ? 'data-selected="true"' : ''}
706
+ >${esc(o.label)}</li>`).join('')}
707
+ </ul>`;
708
+ }