report-studio 1.2.3 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +254 -3
  2. package/dist/designer-_sWqzOj8.js +5052 -0
  3. package/dist/designer.js +1 -1
  4. package/dist/index.js +2 -2
  5. package/dist/react-designer.js +1 -1
  6. package/dist/react.js +1 -1
  7. package/dist/viewer-4I7C1Rnd.js +4083 -0
  8. package/package.json +2 -2
  9. package/src/designer/blank.js +0 -1
  10. package/src/designer/canvas.js +172 -54
  11. package/src/designer/choice.js +368 -0
  12. package/src/designer/designer.js +342 -12
  13. package/src/designer/dialog.js +634 -6
  14. package/src/designer/fields.js +345 -36
  15. package/src/designer/geometry.js +77 -4
  16. package/src/designer/grouping.js +556 -0
  17. package/src/designer/icons.js +22 -0
  18. package/src/designer/menu.js +50 -6
  19. package/src/designer/panel.js +872 -69
  20. package/src/designer/rulers.js +14 -6
  21. package/src/designer/sample-data.js +112 -31
  22. package/src/designer/select.js +24 -3
  23. package/src/designer/structure.js +126 -12
  24. package/src/designer/styles.css +2017 -732
  25. package/src/designer/tokens.js +38 -11
  26. package/src/engine/calculate.js +487 -0
  27. package/src/engine/csv.js +17 -9
  28. package/src/engine/format.js +483 -0
  29. package/src/engine/group.js +350 -70
  30. package/src/engine/highlight.js +224 -0
  31. package/src/engine/index.js +8 -1
  32. package/src/engine/measure.js +53 -26
  33. package/src/engine/paginate.js +189 -92
  34. package/src/engine/resolve.js +117 -10
  35. package/src/engine/rows.js +71 -8
  36. package/src/engine/search.js +12 -4
  37. package/src/engine/tables.js +309 -11
  38. package/src/engine/validate.js +304 -8
  39. package/src/engine/xlsx-style.js +50 -4
  40. package/src/engine/xlsx.js +91 -21
  41. package/src/index.js +18 -0
  42. package/src/preview/chrome.css +302 -84
  43. package/src/preview/chrome.js +70 -58
  44. package/src/preview/viewer.js +137 -85
  45. package/src/render/items.js +61 -10
  46. package/src/render/report.css +0 -5
  47. package/src/shared/dropdown.css +78 -45
  48. package/src/shared/dropdown.js +105 -5
  49. package/src/shared/modal.css +78 -13
  50. package/types/index.d.ts +104 -9
  51. package/types/layout.d.ts +164 -2
  52. package/dist/designer-DQlfKnTr.js +0 -3416
  53. package/dist/viewer-BSPNCNRU.js +0 -2912
@@ -13,9 +13,16 @@
13
13
  */
14
14
 
15
15
  import { DEFAULT_COLUMNS } from './structure.js';
16
+ import { bandLabel } from './grouping.js';
16
17
  import { toId } from '../shared/store.js';
17
18
  import { esc } from '../render/items.js';
18
19
  import { createDropdown } from '../shared/dropdown.js';
20
+ import { choiceBox, refreshChoices, attachChoices } from './choice.js';
21
+ import {
22
+ effectiveFormat, formatValue, toNumber, DATE_PATTERNS, DATETIME_PATTERNS, MAX_DECIMALS,
23
+ CURRENCY_SYMBOLS
24
+ } from '../engine/format.js';
25
+ import { UNARY_OPS } from '../engine/highlight.js';
19
26
  import {
20
27
  TOKENS, findToken, needsField, resolvesIn, tokenItem, aggregateScope,
21
28
  availableFields, bandChoices, defaultBand
@@ -184,6 +191,12 @@ export function askDiscard(root, name = '') {
184
191
  * @param {(host: Element, done: (value: any) => void) => void} wire
185
192
  * @returns {Promise<any>} whatever `done` was given, or null if cancelled
186
193
  */
194
+ /** the close button's ×, drawn so it sits on the same grid as the other glyphs */
195
+ const CLOSE_GLYPH = `<svg viewBox="0 0 16 16" width="14" height="14" fill="none"
196
+ stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
197
+ aria-hidden="true" focusable="false"><path d="M4 4l8 8M12 4l-8 8"/></svg>`;
198
+
199
+
187
200
  function open(root, role, body, wire) {
188
201
  return new Promise(resolve => {
189
202
  /** created in the document the designer is mounted in, not always this one */
@@ -192,14 +205,28 @@ function open(root, role, body, wire) {
192
205
  host.dataset.role = role;
193
206
  host.innerHTML = body;
194
207
 
208
+ /**
209
+ * Every dialog gets the × a design tool's dialog has, in its title
210
+ * bar. Added here rather than in each dialog's markup, and given a
211
+ * role of its own: [data-role="cancel"] is a button some dialogs
212
+ * label and style as something else ("Keep editing").
213
+ */
214
+ host.querySelector('.modal-card')?.insertAdjacentHTML('afterbegin', `
215
+ <button type="button" class="modal-close" data-role="close"
216
+ title="Close" aria-label="Close">${CLOSE_GLYPH}</button>`);
217
+
195
218
  root.appendChild(host);
196
219
 
220
+ /** a dialog's choices open the same list the rail's do */
221
+ const detachChoices = attachChoices(host);
222
+
197
223
  let settled = false;
198
224
 
199
225
  function close(value) {
200
226
  if (settled) return;
201
227
 
202
228
  settled = true;
229
+ detachChoices();
203
230
  /** so a dropdown inside can drop its document listener */
204
231
  host.dispatchEvent(new CustomEvent('dz-closing'));
205
232
  host.remove();
@@ -225,7 +252,8 @@ function open(root, role, body, wire) {
225
252
  close(null);
226
253
  }
227
254
 
228
- for (const node of host.querySelectorAll('[data-role="cancel"], [data-role="backdrop"]')) {
255
+ for (const node of host.querySelectorAll(
256
+ '[data-role="cancel"], [data-role="backdrop"], [data-role="close"]')) {
229
257
  node.addEventListener('click', () => close(null));
230
258
  }
231
259
 
@@ -536,7 +564,7 @@ export function askToken(root, layout, current = null) {
536
564
  const wanted = defaultBand(layout, token, current);
537
565
 
538
566
  bandWrapper.innerHTML = listbox('band',
539
- choices.map(b => ({ value: b, label: b })), wanted);
567
+ choices.map(b => ({ value: b, label: bandLabel(b) })), wanted);
540
568
 
541
569
  bandPicker = createDropdown(bandWrapper);
542
570
  bandPicker.addEventListener('change', () => refresh());
@@ -595,7 +623,7 @@ export function askToken(root, layout, current = null) {
595
623
 
596
624
 
597
625
  function aggregateNote(token, band) {
598
- return `${token.label} prints nothing in a ${band}.`;
626
+ return `${token.label} prints nothing in a ${bandLabel(band)}.`;
599
627
  }
600
628
 
601
629
 
@@ -612,12 +640,12 @@ function scopeNote(token, band) {
612
640
  const scope = aggregateScope(token, band);
613
641
 
614
642
  if (scope === 'group') {
615
- return `In a ${band}, ${token.label.toLowerCase()} is worked out over ` +
643
+ return `In a ${bandLabel(band)}, ${token.label.toLowerCase()} is worked out over ` +
616
644
  `each group's own rows, once per group.`;
617
645
  }
618
646
 
619
647
  if (scope === 'report') {
620
- return `In a ${band}, ${token.label.toLowerCase()} is worked out over ` +
648
+ return `In a ${bandLabel(band)}, ${token.label.toLowerCase()} is worked out over ` +
621
649
  `every row in the report.`;
622
650
  }
623
651
 
@@ -654,7 +682,7 @@ function tokenMarkup(layout, fields, current) {
654
682
  fields[0], { hidden: !needsField(first), empty: 'No fields yet - add a table first' })}
655
683
 
656
684
  ${picker('band', 'Band',
657
- bandChoices(layout, first).map(b => ({ value: b, label: b })),
685
+ bandChoices(layout, first).map(b => ({ value: b, label: bandLabel(b) })),
658
686
  defaultBand(layout, first, current))}
659
687
 
660
688
  <p class="dz-token-warning" data-role="token-warning" aria-live="polite" hidden></p>
@@ -706,3 +734,603 @@ function listbox(role, options, selected) {
706
734
  >${esc(o.label)}</li>`).join('')}
707
735
  </ul>`;
708
736
  }
737
+
738
+
739
+ /* ---------------- the format editor ---------------- */
740
+
741
+
742
+ /** the types the editor offers, in the order a person thinks of them */
743
+ const FORMAT_CHOICES = [
744
+ { value: 'text', label: 'As it comes' },
745
+ { value: 'number', label: 'Number' },
746
+ { value: 'currency', label: 'Currency' },
747
+ { value: 'percent', label: 'Percent' },
748
+ { value: 'date', label: 'Date' },
749
+ { value: 'datetime', label: 'Date & time' }
750
+ ];
751
+
752
+ /** the values the sample line shows, per type: a big one, a negative, a zero */
753
+ const SAMPLES = {
754
+ number: [1234567.891, -1500, 0],
755
+ currency: [1234567.891, -1500, 0],
756
+ percent: [0.1234, -0.05, 0],
757
+ date: ['2026-06-17'],
758
+ datetime: ['2026-06-17T15:04:00']
759
+ };
760
+
761
+ const CUSTOM = '__custom__';
762
+
763
+
764
+ /**
765
+ * Asks how a text item's or a column's values should print - Crystal's Format
766
+ * Editor, cut to what the engine does: the type, and for a number its places,
767
+ * digit groups, negatives and zero, and for money its symbol; for a date its
768
+ * layout. A sample line shows the result as it is chosen.
769
+ *
770
+ * What comes back says only what differs from the report's own defaults, so a
771
+ * report switched to Indian digit groups later takes every format with it that
772
+ * never asked for anything else.
773
+ *
774
+ * @param {Element} root
775
+ * @param {object|null} current the format as it stands
776
+ * @param {object|null} defaults the report's `layout.format`
777
+ * @param {{title?: string}} [options]
778
+ * @returns {Promise<{format: object|null}|null>} the new format - null for
779
+ * "as it comes" - or null when cancelled
780
+ */
781
+ export function askFormat(root, current, defaults, { title = 'Format' } = {}) {
782
+ const start = effectiveFormat(current, defaults)
783
+ ?? { ...effectiveFormat({ type: 'number' }, defaults), type: 'text' };
784
+
785
+ return open(root, 'format-dialog', formatMarkup(start, title), (host, done) => {
786
+ const form = host.querySelector('form');
787
+ const value = (role) => host.querySelector(`[data-role="${role}"]`)?.value;
788
+
789
+ /** the format the controls describe, every key filled in */
790
+ const read = () => {
791
+ const type = host.querySelector('[name="format-type"]:checked')?.value ?? 'text';
792
+ const chosen = value('pattern');
793
+
794
+ return {
795
+ type,
796
+ decimals: decimalsFrom(value('decimals'), start.decimals),
797
+ grouping: value('grouping'),
798
+ negative: value('negative'),
799
+ zero: value('zero'),
800
+ symbol: value('symbolChoice') === CUSTOM ? (value('symbol') ?? '').trim() : (value('symbolChoice') ?? ''),
801
+ symbolPosition: value('symbolPosition'),
802
+ pattern: chosen === CUSTOM ? (value('customPattern') || start.pattern) : chosen
803
+ };
804
+ };
805
+
806
+ const refresh = () => {
807
+ const f = read();
808
+ const isNumber = ['number', 'currency', 'percent'].includes(f.type);
809
+ const isDate = f.type === 'date' || f.type === 'datetime';
810
+
811
+ /** a date & time pattern list for a date & time, a date one for a date */
812
+ if (isDate) syncPatterns(host, f.type, f.pattern);
813
+
814
+ host.querySelector('[data-role="number-options"]').hidden = !isNumber;
815
+ host.querySelector('[data-role="currency-options"]').hidden = f.type !== 'currency';
816
+ host.querySelector('[data-role="date-options"]').hidden = !isDate;
817
+ host.querySelector('[data-role="custom-row"]').hidden = value('pattern') !== CUSTOM;
818
+ host.querySelector('[data-role="symbol-row"]').hidden = value('symbolChoice') !== CUSTOM;
819
+
820
+ const shown = read();
821
+
822
+ /** a number past the ends shows as the end it was held to; an empty box is left to be typed in */
823
+ const places = host.querySelector('[data-role="decimals"]');
824
+ if (places.value !== '' && Number(places.value) !== shown.decimals) {
825
+ places.value = String(shown.decimals);
826
+ }
827
+
828
+ /** zero prints with the places chosen: 0, 0.00, 0.000 */
829
+ const zero = host.querySelector('[data-role="zero"] option[value="zero"]');
830
+ if (zero) zero.textContent = zeroLabel(shown.decimals);
831
+
832
+ /** a relabelled zero, a new list of layouts: the buttons say so too */
833
+ refreshChoices(host);
834
+ host.querySelector('[data-role="sample"]').innerHTML = shown.type === 'text'
835
+ ? '<span>Printed as the data has it</span>'
836
+ : (SAMPLES[shown.type] ?? []).map(v =>
837
+ `<span>${esc(formatValue(v, shown) || '(blank)')}</span>`).join('');
838
+ };
839
+
840
+ form.addEventListener('input', refresh);
841
+ form.addEventListener('change', refresh);
842
+
843
+ host.querySelector('[data-role="reset"]').addEventListener('click', () => {
844
+ const type = read().type;
845
+ done({ format: type === 'text' ? null : { type } });
846
+ });
847
+
848
+ form.addEventListener('submit', event => {
849
+ event.preventDefault();
850
+ done({ format: overrides(read(), defaults) });
851
+ });
852
+
853
+ refresh();
854
+ host.querySelector('[name="format-type"]:checked')?.focus();
855
+ });
856
+ }
857
+
858
+
859
+ /**
860
+ * The places typed into the Decimals box, kept to what a format can hold - a
861
+ * box cleared on the way to typing a new number keeps the last good one.
862
+ * @param {string|undefined} raw
863
+ * @param {number} fallback
864
+ * @returns {number}
865
+ */
866
+ function decimalsFrom(raw, fallback) {
867
+ const n = Math.round(Number(raw));
868
+ if (raw === '' || raw == null || !Number.isFinite(n)) return fallback;
869
+ return Math.min(MAX_DECIMALS, Math.max(0, n));
870
+ }
871
+
872
+
873
+ /** what "zero as zero" prints with this many places */
874
+ function zeroLabel(decimals) {
875
+ return (0).toFixed(decimals);
876
+ }
877
+
878
+
879
+ /**
880
+ * A format as the layout should keep it: its type, and only the choices that
881
+ * differ from what the report would give it anyway - the keys that belong to
882
+ * its type, nothing a date has no use for.
883
+ */
884
+ function overrides(chosen, defaults) {
885
+ if (chosen.type === 'text') return null;
886
+
887
+ const inherited = effectiveFormat({ type: chosen.type }, defaults);
888
+ const keys = chosen.type === 'date' || chosen.type === 'datetime'
889
+ ? ['pattern']
890
+ : ['decimals', 'grouping', 'negative', 'zero',
891
+ ...(chosen.type === 'currency' ? ['symbol', 'symbolPosition'] : [])];
892
+
893
+ const format = { type: chosen.type };
894
+ for (const key of keys) {
895
+ if (chosen[key] !== inherited[key]) format[key] = chosen[key];
896
+ }
897
+
898
+ return format;
899
+ }
900
+
901
+
902
+ /** the pattern list for the type chosen, keeping what is selected if it can */
903
+ function syncPatterns(host, type, pattern) {
904
+ const select = host.querySelector('[data-role="pattern"]');
905
+ if (select.dataset.for === type) return;
906
+
907
+ const list = type === 'datetime' ? DATETIME_PATTERNS : DATE_PATTERNS;
908
+ const selected = list.includes(pattern) ? pattern : list[0];
909
+
910
+ select.innerHTML = patternOptions(list, type, selected);
911
+ select.dataset.for = type;
912
+ }
913
+
914
+
915
+ /** a type's date layouts, each shown as the sample it prints, then Custom… */
916
+ function patternList(list, type) {
917
+ const sample = SAMPLES[type][0];
918
+
919
+ return [
920
+ ...list.map(p => ({ value: p, label: `${formatValue(sample, { type, pattern: p })} (${p})` })),
921
+ { value: CUSTOM, label: 'Custom…' }
922
+ ];
923
+ }
924
+
925
+
926
+ function patternOptions(list, type, selected) {
927
+ const chosen = list.includes(selected) ? selected : CUSTOM;
928
+
929
+ return patternList(list, type).map(o => `<option value="${esc(o.value)}"
930
+ ${o.value === chosen ? ' selected' : ''}>${esc(o.label)}</option>`).join('');
931
+ }
932
+
933
+
934
+ function formatMarkup(f, title) {
935
+ const select = (role, label, options, current) => `
936
+ <div class="dz-field">
937
+ <label for="dz-format-${role}" id="dz-format-${role}-label">${esc(label)}</label>
938
+ ${choiceBox(`dz-format-${role}`, `data-role="${role}"`, options, current)}
939
+ </div>`;
940
+
941
+ const dateType = f.type === 'datetime' ? 'datetime' : 'date';
942
+ const patterns = dateType === 'datetime' ? DATETIME_PATTERNS : DATE_PATTERNS;
943
+ const isCustom = !patterns.includes(f.pattern);
944
+ const knownSymbol = CURRENCY_SYMBOLS.some(o => o.value === f.symbol);
945
+
946
+ return `
947
+ <div class="modal-backdrop" data-role="backdrop"></div>
948
+
949
+ <div class="modal-card dz-format-card" role="dialog" aria-modal="true"
950
+ aria-labelledby="dz-format-title">
951
+ <h2 id="dz-format-title">${esc(title)}</h2>
952
+
953
+ <form>
954
+ <fieldset class="dz-format-types">
955
+ <legend>Type</legend>
956
+ <div class="dz-format-track">
957
+ ${FORMAT_CHOICES.map(o => `
958
+ <label class="dz-format-type">
959
+ <input type="radio" name="format-type" value="${o.value}"
960
+ ${o.value === f.type ? 'checked' : ''}>
961
+ <span>${esc(o.label)}</span>
962
+ </label>`).join('')}
963
+ </div>
964
+ </fieldset>
965
+
966
+ <div class="dz-format-group" data-role="number-options">
967
+ <div class="dz-field">
968
+ <label for="dz-format-decimals">Decimals</label>
969
+ <input type="number" id="dz-format-decimals" data-role="decimals"
970
+ value="${f.decimals}" min="0" max="${MAX_DECIMALS}" step="1">
971
+ </div>
972
+ ${select('grouping', 'Digit groups', [
973
+ { value: 'international', label: '1,234,567' },
974
+ { value: 'indian', label: '12,34,567 (Indian)' },
975
+ { value: 'none', label: '1234567' }
976
+ ], f.grouping)}
977
+ ${select('negative', 'Negative', [
978
+ { value: 'minus', label: '-1,234' },
979
+ { value: 'brackets', label: '(1,234)' },
980
+ { value: 'trailing', label: '1,234-' }
981
+ ], f.negative)}
982
+ ${select('zero', 'Zero shows as', [
983
+ { value: 'zero', label: zeroLabel(f.decimals) },
984
+ { value: 'dash', label: '-' },
985
+ { value: 'blank', label: 'Nothing' }
986
+ ], f.zero)}
987
+ </div>
988
+
989
+ <div class="dz-format-group" data-role="currency-options">
990
+ ${select('symbolChoice', 'Symbol', [
991
+ ...CURRENCY_SYMBOLS,
992
+ { value: CUSTOM, label: 'Custom…' }
993
+ ], knownSymbol ? f.symbol : CUSTOM)}
994
+ ${select('symbolPosition', 'Symbol goes', [
995
+ { value: 'before', label: 'Before ₹100' },
996
+ { value: 'after', label: 'After 100 ₹' }
997
+ ], f.symbolPosition)}
998
+ <div class="dz-field" data-role="symbol-row"${knownSymbol ? ' hidden' : ''}>
999
+ <label for="dz-format-symbol">Custom symbol</label>
1000
+ <input type="text" id="dz-format-symbol" data-role="symbol"
1001
+ value="${esc(knownSymbol ? '' : f.symbol)}" maxlength="6"
1002
+ spellcheck="false" placeholder="such as CHF">
1003
+ </div>
1004
+ </div>
1005
+
1006
+ <div class="dz-format-group" data-role="date-options">
1007
+ <div class="dz-field">
1008
+ <label for="dz-format-pattern" id="dz-format-pattern-label">Layout</label>
1009
+ ${choiceBox('dz-format-pattern', `data-role="pattern" data-for="${dateType}"`,
1010
+ patternList(patterns, dateType), isCustom ? CUSTOM : f.pattern)}
1011
+ </div>
1012
+ <div class="dz-field" data-role="custom-row"${isCustom ? '' : ' hidden'}>
1013
+ <label for="dz-format-custom">Pattern</label>
1014
+ <input type="text" id="dz-format-custom" data-role="customPattern"
1015
+ value="${esc(isCustom ? f.pattern : '')}" spellcheck="false"
1016
+ placeholder="dd/MM/yyyy">
1017
+ </div>
1018
+ <p class="modal-summary">
1019
+ yyyy year · MM month · MMM Jun · dd day · HH hour · hh 12-hour ·
1020
+ mm minute · a AM/PM
1021
+ </p>
1022
+ </div>
1023
+
1024
+ <div class="dz-format-sample">
1025
+ <span class="dz-format-sample-label">Sample</span>
1026
+ <span class="dz-format-sample-values" data-role="sample"></span>
1027
+ </div>
1028
+
1029
+ <div class="modal-actions">
1030
+ <button type="button" data-role="reset"
1031
+ title="Keep the type, and take everything else from the report's own settings">
1032
+ Report defaults</button>
1033
+ <button type="button" data-role="cancel">Cancel</button>
1034
+ <button type="submit" class="is-primary" data-role="confirm">Apply</button>
1035
+ </div>
1036
+ </form>
1037
+ </div>`;
1038
+ }
1039
+
1040
+
1041
+ /* ---------------- the highlight editor ---------------- */
1042
+
1043
+
1044
+ /** a rule's tests, as the editor offers them */
1045
+ const OP_CHOICES = [
1046
+ { value: '=', label: 'equals' },
1047
+ { value: '!=', label: 'is not' },
1048
+ { value: '<', label: 'is less than' },
1049
+ { value: '<=', label: 'is at most' },
1050
+ { value: '>', label: 'is more than' },
1051
+ { value: '>=', label: 'is at least' },
1052
+ { value: 'between', label: 'is between' },
1053
+ { value: 'contains', label: 'contains' },
1054
+ { value: 'startsWith', label: 'starts with' },
1055
+ { value: 'empty', label: 'is empty' },
1056
+ { value: 'notEmpty', label: 'is not empty' }
1057
+ ];
1058
+
1059
+ /** what "the value being drawn" is called in the subject choice */
1060
+ const THIS_VALUE = '';
1061
+
1062
+ /** a rule's colour when it is first added: the report's own red */
1063
+ const NEW_RULE_COLOR = '#b3261e';
1064
+
1065
+
1066
+ /**
1067
+ * Asks for the highlight rules of a column, a table's rows or a text item -
1068
+ * Crystal's Highlighting Expert: a list of conditions, each with the style it
1069
+ * gives, the first that holds being the one used.
1070
+ *
1071
+ * Each rule reads as a sentence - "When this value is less than 0" - with its
1072
+ * style beside it: text colour, fill, bold, italic, and a sample drawn in it.
1073
+ *
1074
+ * @param {Element} root
1075
+ * @param {object[]|null} current the rules as they stand
1076
+ * @param {object} options
1077
+ * @param {string} [options.title]
1078
+ * @param {string[]} [options.fields] the fields a rule may test besides the value
1079
+ * @param {boolean} [options.rows] a table's row rules, which have no value of
1080
+ * their own - every rule tests a field
1081
+ * @param {object|null} [options.format] how the value prints, for the sample
1082
+ * @returns {Promise<{rules: object[]|null}|null>} the rules - null for none -
1083
+ * or null when cancelled
1084
+ */
1085
+ export function askHighlight(root, current, { title = 'Highlight', fields = [], rows = false, format = null } = {}) {
1086
+ const rules = structuredClone(Array.isArray(current) ? current : []);
1087
+
1088
+ /** a field a rule already tests is offered even if the report no longer names it */
1089
+ const subjects = [...new Set([...fields, ...rules.map(r => r.when?.field).filter(Boolean)])];
1090
+
1091
+ const fresh = () => ({
1092
+ when: rows
1093
+ ? { field: subjects[0] ?? '', op: '=', value: '' }
1094
+ : { op: '<', value: 0 },
1095
+ style: { color: NEW_RULE_COLOR }
1096
+ });
1097
+
1098
+ if (rules.length === 0) rules.push(fresh());
1099
+
1100
+ return open(root, 'highlight-dialog', highlightMarkup(title), (host, done) => {
1101
+ const list = host.querySelector('[data-role="rules"]');
1102
+
1103
+ const draw = () => {
1104
+ list.innerHTML = rules.map((rule, n) =>
1105
+ ruleMarkup(rule, n, rules.length, subjects, rows, format)).join('');
1106
+ };
1107
+
1108
+ /** a typed value as the rule keeps it: a number when it is plainly one */
1109
+ const operand = (raw) => {
1110
+ const number = toNumber(raw);
1111
+ return number === null ? raw : number;
1112
+ };
1113
+
1114
+ host.addEventListener('input', event => {
1115
+ const node = event.target.closest('[data-key]');
1116
+ const n = Number(node?.closest('[data-n]')?.dataset.n);
1117
+ const rule = rules[n];
1118
+ if (!rule) return;
1119
+
1120
+ const key = node.dataset.key;
1121
+
1122
+ if (key === 'field') {
1123
+ if (node.value === THIS_VALUE) delete rule.when.field;
1124
+ else rule.when.field = node.value;
1125
+ } else if (key === 'op') {
1126
+ rule.when.op = node.value;
1127
+ if (UNARY_OPS.includes(node.value)) {
1128
+ delete rule.when.value;
1129
+ delete rule.when.to;
1130
+ }
1131
+ /** which value boxes there are has changed */
1132
+ draw();
1133
+ list.querySelector(`[data-n="${n}"] [data-key="op"]`)?.focus();
1134
+ return;
1135
+ } else if (key === 'value' || key === 'to') {
1136
+ rule.when[key] = operand(node.value);
1137
+ } else if (key === 'color' || key === 'background') {
1138
+ rule.style[key] = node.value;
1139
+ node.closest('.dz-swatch')?.classList.remove('is-none');
1140
+ }
1141
+
1142
+ refreshPreview(list, n, rule, format);
1143
+ });
1144
+
1145
+ /** a <select> reports on change only in some browsers */
1146
+ host.addEventListener('change', event => {
1147
+ if (event.target.tagName === 'SELECT') {
1148
+ event.target.dispatchEvent(new Event('input', { bubbles: true }));
1149
+ }
1150
+ });
1151
+
1152
+ host.addEventListener('click', event => {
1153
+ const button = event.target.closest('[data-rule-action]');
1154
+ if (!button) return;
1155
+
1156
+ event.preventDefault();
1157
+
1158
+ const n = Number(button.closest('[data-n]')?.dataset.n);
1159
+ const action = button.dataset.ruleAction;
1160
+
1161
+ if (action === 'add') {
1162
+ rules.push(fresh());
1163
+ draw();
1164
+ list.querySelector(`[data-n="${rules.length - 1}"] select, [data-n="${rules.length - 1}"] input`)?.focus();
1165
+ return;
1166
+ }
1167
+
1168
+ const rule = rules[n];
1169
+ if (!rule) return;
1170
+
1171
+ if (action === 'remove') rules.splice(n, 1);
1172
+ if (action === 'up' && n > 0) rules.splice(n - 1, 0, ...rules.splice(n, 1));
1173
+ if (action === 'clear') delete rule.style[button.dataset.key];
1174
+ if (action === 'bold') toggle(rule.style, 'fontWeight', 'bold');
1175
+ if (action === 'italic') toggle(rule.style, 'fontStyle', 'italic');
1176
+
1177
+ draw();
1178
+ });
1179
+
1180
+ host.querySelector('form').addEventListener('submit', event => {
1181
+ event.preventDefault();
1182
+ const kept = rules.filter(complete);
1183
+ done({ rules: kept.length ? kept : null });
1184
+ });
1185
+
1186
+ draw();
1187
+ list.querySelector('select, input')?.focus();
1188
+ });
1189
+ }
1190
+
1191
+
1192
+ /** a style key set to `on`, or taken off when it already is */
1193
+ function toggle(style, key, on) {
1194
+ if (style[key] === on) delete style[key];
1195
+ else style[key] = on;
1196
+ }
1197
+
1198
+
1199
+ /**
1200
+ * Whether a rule can ever hold: a test that compares has something to compare
1201
+ * with, and a row rule names its field. One left half-made is dropped on the
1202
+ * way out rather than saved as a layout validate.js would complain about.
1203
+ */
1204
+ function complete(rule) {
1205
+ const { when } = rule;
1206
+ if (!when || !OP_CHOICES.some(o => o.value === when.op)) return false;
1207
+ if (UNARY_OPS.includes(when.op)) return true;
1208
+
1209
+ const has = (v) => v !== undefined && v !== null && String(v).trim() !== '';
1210
+ return when.op === 'between' ? has(when.value) && has(when.to) : has(when.value);
1211
+ }
1212
+
1213
+
1214
+ /** the sample a rule shows: its own value in the column's format, drawn in its style */
1215
+ function preview(rule, format) {
1216
+ const value = rule.when?.value;
1217
+ const shown = value === undefined || value === '' ? 'Sample' : formatValue(value, format) || 'Sample';
1218
+ const style = rule.style ?? {};
1219
+
1220
+ const css = [
1221
+ style.color ? `color:${style.color}` : '',
1222
+ style.background ? `background:${style.background}` : '',
1223
+ style.fontWeight ? `font-weight:${style.fontWeight}` : '',
1224
+ style.fontStyle ? `font-style:${style.fontStyle}` : ''
1225
+ ].filter(Boolean).join(';');
1226
+
1227
+ return `<span class="dz-hl-preview" data-role="preview" style="${esc(css)}">${esc(shown)}</span>`;
1228
+ }
1229
+
1230
+
1231
+ function refreshPreview(list, n, rule, format) {
1232
+ const old = list.querySelector(`[data-n="${n}"] [data-role="preview"]`);
1233
+ if (old) old.outerHTML = preview(rule, format);
1234
+ }
1235
+
1236
+
1237
+ function ruleMarkup(rule, n, count, subjects, rows, format) {
1238
+ const when = rule.when ?? {};
1239
+ const style = rule.style ?? {};
1240
+ const unary = UNARY_OPS.includes(when.op);
1241
+
1242
+ const subjectChoices = [
1243
+ ...(rows ? [] : [{ value: THIS_VALUE, label: 'this value' }]),
1244
+ ...subjects.map(f => ({ value: f, label: f }))
1245
+ ];
1246
+
1247
+ const swatch = (key, label) => {
1248
+ const none = !style[key];
1249
+ return `
1250
+ <span class="dz-hl-color">
1251
+ <span class="dz-hl-color-label">${esc(label)}</span>
1252
+ <span class="dz-swatch${none ? ' is-none' : ''}">
1253
+ <span class="dz-swatch-well">
1254
+ <input type="color" data-key="${key}" value="${esc(none ? '#000000' : style[key])}"
1255
+ aria-label="${esc(label)} colour">
1256
+ </span>
1257
+ <button type="button" class="dz-icon dz-swatch-clear" data-rule-action="clear"
1258
+ data-key="${key}" title="No ${esc(label.toLowerCase())} colour"
1259
+ aria-label="Remove ${esc(label.toLowerCase())} colour">&times;</button>
1260
+ </span>
1261
+ </span>`;
1262
+ };
1263
+
1264
+ /**
1265
+ * Laid out on one grid for every rule - a label column, the controls, and
1266
+ * the rule's own buttons - so the dropdowns of one rule sit exactly under
1267
+ * those of the one above, whatever its label says or its test needs.
1268
+ */
1269
+ return `
1270
+ <div class="dz-hl-rule" data-n="${n}">
1271
+ <span class="dz-hl-label">${n === 0 ? 'When' : 'Else when'}</span>
1272
+ <div class="dz-hl-when">
1273
+ ${choiceBox(null, 'data-key="field"', subjectChoices, when.field ?? THIS_VALUE,
1274
+ { label: 'What to test' })}
1275
+ ${choiceBox(null, 'data-key="op"', OP_CHOICES, when.op, { label: 'Test' })}
1276
+ <span class="dz-hl-values">
1277
+ ${unary ? '<span class="dz-hl-novalue">no value needed</span>' : `
1278
+ <input type="text" data-key="value" value="${esc(when.value ?? '')}"
1279
+ spellcheck="false" aria-label="Value" placeholder="value">`}
1280
+ ${when.op === 'between' ? `
1281
+ <span class="dz-hl-and">and</span>
1282
+ <input type="text" data-key="to" value="${esc(when.to ?? '')}"
1283
+ spellcheck="false" aria-label="Upper value" placeholder="value">` : ''}
1284
+ </span>
1285
+ </div>
1286
+ <span class="dz-hl-actions">
1287
+ ${n > 0 ? `<button type="button" class="dz-icon" data-rule-action="up"
1288
+ title="Check this rule before the one above"
1289
+ aria-label="Move rule ${n + 1} up">&uarr;</button>`
1290
+ : '<span class="dz-hl-slot" aria-hidden="true"></span>'}
1291
+ <button type="button" class="dz-icon" data-rule-action="remove"
1292
+ title="Remove this rule" aria-label="Remove rule ${n + 1}">&times;</button>
1293
+ </span>
1294
+
1295
+ <span class="dz-hl-label">Style</span>
1296
+ <div class="dz-hl-style">
1297
+ ${swatch('color', 'Text')}
1298
+ ${swatch('background', 'Fill')}
1299
+ <span class="dz-hl-toggles">
1300
+ <button type="button" class="dz-hl-toggle" data-rule-action="bold"
1301
+ aria-pressed="${style.fontWeight === 'bold'}" title="Bold"
1302
+ aria-label="Bold"><b>B</b></button>
1303
+ <button type="button" class="dz-hl-toggle" data-rule-action="italic"
1304
+ aria-pressed="${style.fontStyle === 'italic'}" title="Italic"
1305
+ aria-label="Italic"><i>I</i></button>
1306
+ </span>
1307
+ ${preview(rule, format)}
1308
+ </div>
1309
+ </div>`;
1310
+ }
1311
+
1312
+
1313
+ function highlightMarkup(title) {
1314
+ return `
1315
+ <div class="modal-backdrop" data-role="backdrop"></div>
1316
+
1317
+ <div class="modal-card dz-highlight-card" role="dialog" aria-modal="true"
1318
+ aria-labelledby="dz-highlight-title">
1319
+ <h2 id="dz-highlight-title">${esc(title)}</h2>
1320
+
1321
+ <form>
1322
+ <div class="dz-hl-rules" data-role="rules"></div>
1323
+
1324
+ <button type="button" class="dz-add-row" data-rule-action="add">Add rule</button>
1325
+
1326
+ <p class="modal-summary">
1327
+ Rules are checked in order, and the first one that holds is used.
1328
+ </p>
1329
+
1330
+ <div class="modal-actions">
1331
+ <button type="button" data-role="cancel">Cancel</button>
1332
+ <button type="submit" class="is-primary" data-role="confirm">Apply</button>
1333
+ </div>
1334
+ </form>
1335
+ </div>`;
1336
+ }