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