pivotkit-react 0.7.0 → 0.8.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 (55) hide show
  1. package/CHANGELOG.md +167 -1
  2. package/README.md +33 -15
  3. package/dist/chunks/{chunk-JMRTIOX4.js → chunk-2N2UGSIG.js} +7 -0
  4. package/dist/chunks/{chunk-ZK5RVCHP.js → chunk-BHHIZHUE.js} +1 -1
  5. package/dist/chunks/{chunk-YXLANLGL.js → chunk-GUSQWPTH.js} +56 -3
  6. package/dist/chunks/{chunk-E6M57YLL.js → chunk-MU5BTKSY.js} +7 -0
  7. package/dist/chunks/{chunk-TR2HROIK.js → chunk-RNQ32FCN.js} +66 -5
  8. package/dist/chunks/{chunk-XN5HNKJ2.js → chunk-SJCG4I57.js} +98 -33
  9. package/dist/chunks/{chunk-4WZ5F2TJ.js → chunk-VMJMDP7C.js} +371 -32
  10. package/dist/chunks/{unused-texts-Y4R67XSN.js → unused-texts-LRYVWFFN.js} +1 -1
  11. package/dist/chunks/{unused-texts-de-6YVPTNVS.js → unused-texts-de-GB3IWWEM.js} +1 -1
  12. package/dist/echarts.js +426 -35
  13. package/dist/import-ui.js +2 -2
  14. package/dist/index.js +723 -392
  15. package/dist/labels.js +6 -6
  16. package/dist/menu-texts-de.js +1 -1
  17. package/dist/menus.js +1534 -1020
  18. package/dist/styles.css +268 -158
  19. package/package.json +3 -3
  20. package/types/PivotReport.d.ts +6 -0
  21. package/types/add-menu.d.ts +48 -0
  22. package/types/chart-colors.d.ts +8 -0
  23. package/types/chart-decorate.d.ts +66 -3
  24. package/types/chart-legend.d.ts +176 -0
  25. package/types/chart-summary.d.ts +8 -3
  26. package/types/chart-tooltip.d.ts +159 -17
  27. package/types/chart.d.ts +21 -3
  28. package/types/date-context.d.ts +30 -0
  29. package/types/drill-panel.d.ts +4 -2
  30. package/types/echarts.d.ts +7 -3
  31. package/types/export-run.d.ts +7 -14
  32. package/types/export-scope.d.ts +13 -2
  33. package/types/field-info.d.ts +12 -0
  34. package/types/files.d.ts +14 -0
  35. package/types/filter.d.ts +18 -0
  36. package/types/group-context.d.ts +20 -0
  37. package/types/index.d.ts +35 -6
  38. package/types/label-room.d.ts +13 -0
  39. package/types/labels.d.ts +85 -16
  40. package/types/lazy-menus.d.ts +2 -2
  41. package/types/levels.d.ts +16 -7
  42. package/types/menu-labels.d.ts +67 -1
  43. package/types/menu-ops.d.ts +10 -0
  44. package/types/menu-topics.d.ts +110 -21
  45. package/types/menus.d.ts +2 -1
  46. package/types/names.d.ts +32 -3
  47. package/types/overflow.d.ts +18 -30
  48. package/types/rove.d.ts +10 -0
  49. package/types/toolbar-panels.d.ts +34 -10
  50. package/types/unused-texts.d.ts +7 -0
  51. package/types/use-big-result.d.ts +24 -9
  52. package/types/use-export.d.ts +2 -2
  53. package/types/view-ops.d.ts +19 -8
  54. package/types/view-tabs.d.ts +12 -0
  55. package/types/zones.d.ts +41 -9
package/dist/menus.js CHANGED
@@ -11,6 +11,9 @@ import {
11
11
  axisOf,
12
12
  chartTypeOf,
13
13
  clone,
14
+ dateDisplayLocale,
15
+ dateFormatter,
16
+ dateRangeText,
14
17
  dateSpan,
15
18
  dayMs,
16
19
  dayText,
@@ -21,6 +24,7 @@ import {
21
24
  groupField,
22
25
  groupingName,
23
26
  groupingOf,
27
+ hiddenAfter,
24
28
  hiddenNot,
25
29
  importNow,
26
30
  isoDay,
@@ -29,7 +33,9 @@ import {
29
33
  linkNow,
30
34
  loadCheck,
31
35
  loadLink,
36
+ matchingFields,
32
37
  moveField,
38
+ namedUntil,
33
39
  numericResult,
34
40
  opOf,
35
41
  periodText,
@@ -38,7 +44,6 @@ import {
38
44
  rangeShare,
39
45
  readLinkParam,
40
46
  refLabel,
41
- relativeDays,
42
47
  relativeText,
43
48
  reorder,
44
49
  ruleOp,
@@ -52,20 +57,22 @@ import {
52
57
  sortOf,
53
58
  sortText,
54
59
  sourceOf,
60
+ todayIn,
55
61
  valueConditionText,
56
62
  valueLabel,
63
+ valueLabels,
57
64
  viewFromObject,
58
65
  viewFromText,
59
66
  wholeYears,
60
67
  withLinkParam,
61
68
  yearOf,
62
69
  yearText
63
- } from "./chunks/chunk-4WZ5F2TJ.js";
70
+ } from "./chunks/chunk-VMJMDP7C.js";
64
71
  import {
65
72
  addMenuTexts,
66
73
  hasMenuTexts,
67
74
  menuLabels
68
- } from "./chunks/chunk-TR2HROIK.js";
75
+ } from "./chunks/chunk-RNQ32FCN.js";
69
76
  import {
70
77
  listedFor,
71
78
  sheetOfSource
@@ -77,6 +84,8 @@ import {
77
84
  MenuButton,
78
85
  Option,
79
86
  Popover,
87
+ TYPE_ICON,
88
+ ZONE_ICON,
80
89
  activeIn,
81
90
  rootOf,
82
91
  stopAfter,
@@ -89,7 +98,7 @@ import {
89
98
  hostFailure,
90
99
  messageOf,
91
100
  plural
92
- } from "./chunks/chunk-XN5HNKJ2.js";
101
+ } from "./chunks/chunk-SJCG4I57.js";
93
102
 
94
103
  // src/chip-menus.jsx
95
104
  import React6, { useId as useId4, useMemo as useMemo3, useState as useState4 } from "react";
@@ -97,7 +106,7 @@ import { computePivot as computePivot2, fieldLabel as fieldLabel4 } from "pivotk
97
106
 
98
107
  // src/filter-level.jsx
99
108
  import React5, { useContext as useContext3, useEffect as useEffect2, useId as useId3, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
100
- import { CATALOG as CATALOG3, LIMITS as LIMITS2, fieldItems as fieldItems2, fieldLabel as fieldLabel3, formatter as formatter2, relativeDateRange } from "pivotkit-core";
109
+ import { CATALOG as CATALOG4, LIMITS as LIMITS2, fieldItems as fieldItems2, fieldLabel as fieldLabel3, formatter as formatter2, relativeDateRange } from "pivotkit-core";
101
110
 
102
111
  // src/filter.jsx
103
112
  import React, { useMemo, useState } from "react";
@@ -105,6 +114,62 @@ import { LIMITS, fieldItems, fieldLabel } from "pivotkit-core";
105
114
 
106
115
  // src/menu-ops.js
107
116
  import { CATALOG, MATCH_DEFAULTS, MAX_DATE_MS, computePivot, isFormat } from "pivotkit-core";
117
+
118
+ // src/numbers.js
119
+ var cache = /* @__PURE__ */ new Map();
120
+ function marks(locale) {
121
+ let m = cache.get(locale);
122
+ if (!m) {
123
+ let parts;
124
+ try {
125
+ parts = new Intl.NumberFormat(locale).formatToParts(12345.6);
126
+ } catch {
127
+ parts = new Intl.NumberFormat("en-US").formatToParts(12345.6);
128
+ }
129
+ m = {
130
+ decimal: parts.find((p) => p.type === "decimal")?.value ?? ".",
131
+ group: parts.find((p) => p.type === "group")?.value ?? ","
132
+ };
133
+ cache.set(locale, m);
134
+ }
135
+ return m;
136
+ }
137
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
138
+ var PLAIN = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
139
+ function parseNumber(text, locale) {
140
+ const t = String(text ?? "").replace(/[\s\u00a0\u202f]/g, "").replace(/\u2212/g, "-");
141
+ if (t === "") {
142
+ return null;
143
+ }
144
+ const { decimal, group } = marks(locale);
145
+ const g = /[\s\u00a0\u202f]/.test(group) ? "" : escape(group);
146
+ const d = escape(decimal);
147
+ const grouped = g ? `\\d{1,3}(?:${g}\\d{3})+` : "(?!)";
148
+ const local = new RegExp(`^([+-]?)(${grouped}|\\d+)?(?:${d}(\\d+))?$`);
149
+ const match = local.exec(t);
150
+ if (match && (match[2] !== void 0 || match[3] !== void 0)) {
151
+ const whole = (match[2] ?? "0").split(group).join("");
152
+ const n = Number(`${match[1]}${whole}${match[3] !== void 0 ? `.${match[3]}` : ""}`);
153
+ return Number.isFinite(n) ? n : null;
154
+ }
155
+ if (PLAIN.test(t)) {
156
+ const n = Number(t);
157
+ return Number.isFinite(n) ? n : null;
158
+ }
159
+ return null;
160
+ }
161
+ function numberText(n, locale) {
162
+ if (typeof n !== "number" || !Number.isFinite(n)) {
163
+ return "";
164
+ }
165
+ try {
166
+ return n.toLocaleString(locale, { useGrouping: false, maximumFractionDigits: 20 });
167
+ } catch {
168
+ return String(n);
169
+ }
170
+ }
171
+
172
+ // src/menu-ops.js
108
173
  var COUNTING = /* @__PURE__ */ new Set(["count", "countUnique", "listUnique"]);
109
174
  var unitOf = (agg) => COUNTING.has(agg) ? "count" : "field";
110
175
  function updateValue(view, index, patch, options = {}) {
@@ -411,6 +476,14 @@ function dateFromInput(text) {
411
476
  const iso = `${isoYear(Number(m[1]))}-${m[2]}-${m[3]}`;
412
477
  return Number.isNaN(dayMs(iso)) || isoDay(dayMs(iso)) !== iso ? null : iso;
413
478
  }
479
+ function parseTarget(text, locale, format) {
480
+ const percent = /^(.*?)[\s\u00a0\u202f]*%$/.exec(String(text ?? "").trim());
481
+ if (!percent) {
482
+ return parseNumber(text, locale);
483
+ }
484
+ const n = /^percent/.test(format ?? "") ? parseNumber(percent[1], locale) : null;
485
+ return n === null ? null : /^percent100/.test(format ?? "") ? n : n / 100;
486
+ }
414
487
 
415
488
  // src/filter.jsx
416
489
  var FILTER_LIST_MAX = 300;
@@ -454,7 +527,7 @@ function ValueList({ items, selected, onChange, labels, locale, autoFocus = fals
454
527
  /* searchItems gives the list itself without a search */
455
528
  ) : null), children));
456
529
  }
457
- function FilterBody({ view: current, base, field, encoded, locale, labels, commit, close }) {
530
+ function FilterBody({ view: current, base, field, encoded, locale, labels, commit, close, onCancel, titled = true }) {
458
531
  const view = base ?? current;
459
532
  const formName = useFormName();
460
533
  const info = useMemo(() => fieldItems(encoded, field, { view, locale, labels: labels.core }), [encoded, field, view, locale, labels]);
@@ -483,7 +556,7 @@ function FilterBody({ view: current, base, field, encoded, locale, labels, commi
483
556
  apply();
484
557
  }
485
558
  },
486
- /* @__PURE__ */ React.createElement("div", { className: "pk-popover-head" }, /* @__PURE__ */ React.createElement("h3", null, fill(labels.filterTitle, { field: name })), /* @__PURE__ */ React.createElement("span", { className: "pk-muted" }, fill(labels.selected, { count: selected.size.toLocaleString(locale) }))),
559
+ /* @__PURE__ */ React.createElement("div", { className: "pk-popover-head" }, titled ? /* @__PURE__ */ React.createElement("h3", null, fill(labels.filterTitle, { field: name })) : null, /* @__PURE__ */ React.createElement("span", { className: "pk-muted" }, fill(labels.selected, { count: selected.size.toLocaleString(locale) }))),
487
560
  /* @__PURE__ */ React.createElement(ValueList, { items: info.items, selected, onChange: setSelected, labels, locale, autoFocus: true }, kind ? /* @__PURE__ */ React.createElement("fieldset", { className: "pk-condition" }, /* @__PURE__ */ React.createElement("legend", null, kind === "number" ? labels.conditionNumber : labels.condition), /* @__PURE__ */ React.createElement("select", { name: `${formName}-op`, value: op, onChange: (e) => setOp(e.target.value), "aria-label": kind === "number" ? labels.conditionNumber : labels.condition }, /* @__PURE__ */ React.createElement("option", { value: "" }, labels.conditionNone), RULE_OPS.text.map((o) => /* @__PURE__ */ React.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))), op ? /* @__PURE__ */ React.createElement(
488
561
  ClearInput,
489
562
  {
@@ -502,7 +575,7 @@ function FilterBody({ view: current, base, field, encoded, locale, labels, commi
502
575
  "data-testid": "filter-condition-text"
503
576
  }
504
577
  ) : null) : null),
505
- /* @__PURE__ */ React.createElement("div", { className: "pk-popover-foot" }, /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-btn", onClick: close }, labels.cancel), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "pk-btn pk-primary", "data-testid": "filter-apply" }, labels.apply))
578
+ /* @__PURE__ */ React.createElement("div", { className: "pk-popover-foot" }, /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-btn", onClick: onCancel ?? close, "data-testid": "filter-cancel" }, labels.cancel), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "pk-btn pk-primary", "data-testid": "filter-apply" }, labels.apply))
506
579
  );
507
580
  }
508
581
  function FilterPopover({ target, onClose, view, encoded, locale, labels, commit }) {
@@ -529,10 +602,81 @@ function Section({ title, children, info }) {
529
602
  }
530
603
 
531
604
  // src/menu-topics.js
532
- import { CATALOG as CATALOG2, aggregatorsFor, fieldLabel as fieldLabel2, formatter, isFormat as isFormat2 } from "pivotkit-core";
605
+ import { CATALOG as CATALOG3, aggregatorsFor, fieldLabel as fieldLabel2, formatter, isFormat as isFormat2 } from "pivotkit-core";
606
+
607
+ // src/group-context.js
608
+ import { MAX_DATE_MS as MAX_DATE_MS2, isDateMs } from "pivotkit-core";
609
+ import { CATALOG as CATALOG2 } from "pivotkit-core";
610
+ function groupStats(encoded, field) {
611
+ const column = encoded?.column(field);
612
+ if (!column || column.type !== "date") return null;
613
+ let min = Infinity, max = -Infinity;
614
+ const months = /* @__PURE__ */ new Set();
615
+ const minYear = new Date(-MAX_DATE_MS2).getUTCFullYear();
616
+ const maxYear = new Date(MAX_DATE_MS2).getUTCFullYear();
617
+ const yearBits = new Uint8Array(Math.ceil((maxYear - minYear + 1) / 8));
618
+ let yearCount = 0;
619
+ const date = /* @__PURE__ */ new Date(0);
620
+ for (const value of column.dict) {
621
+ if (!isDateMs(value)) continue;
622
+ min = Math.min(min, value);
623
+ max = Math.max(max, value);
624
+ date.setTime(value);
625
+ const month = date.getUTCMonth();
626
+ const yearIndex = date.getUTCFullYear() - minYear;
627
+ const byte = yearIndex >> 3, mask = 1 << (yearIndex & 7);
628
+ if (!(yearBits[byte] & mask)) {
629
+ yearBits[byte] |= mask;
630
+ yearCount++;
631
+ }
632
+ months.add(month);
633
+ }
634
+ return min <= max ? { span: { min, max }, first: new Date(min), last: new Date(max), years: yearCount, months: [...months].sort((a, b) => a - b) } : null;
635
+ }
636
+ var calendarDays = (span) => Math.floor(span.max / 864e5) - Math.floor(span.min / 864e5) + 1;
637
+ function groupHint(encoded, field, unit, locale, labels, stats = groupStats(encoded, field)) {
638
+ const span = stats?.span;
639
+ if (!span || !stats) return labels.unitHints[unit] || void 0;
640
+ const { first, last, months, years } = stats;
641
+ const y1 = first.getUTCFullYear(), y2 = last.getUTCFullYear();
642
+ const era = y1 <= 0 ? "short" : void 0;
643
+ const firstYear = yearText(y1, locale), lastYear = yearText(y2, locale);
644
+ if (CATALOG2.cyclicUnits.includes(unit)) {
645
+ let example = labels.unitHints[unit];
646
+ if (unit === "month" || unit === "quarter") {
647
+ const name = (m) => unit === "quarter" ? `Q${Math.floor(m / 3) + 1}` : dateFormatter(locale, { calendar: "gregory", month: "short", timeZone: "UTC" }).format(new Date(Date.UTC(2e3, m, 1)));
648
+ const periods = [...new Set(months.map((m) => unit === "quarter" ? Math.floor(m / 3) : m))];
649
+ const runs = [];
650
+ const text = (p) => name(unit === "quarter" ? p * 3 : p);
651
+ for (let i = 0; i < periods.length; i++) {
652
+ const first2 = periods[i];
653
+ while (i + 1 < periods.length && periods[i + 1] === periods[i] + 1) i++;
654
+ runs.push(first2 === periods[i] ? text(first2) : `${text(first2)}\u2013${text(periods[i])}`);
655
+ }
656
+ example = runs.join(", ");
657
+ }
658
+ return `${example} \xB7 ${plural(labels.groupYearsTogether, years, { lang: labels.lang, locale })}`;
659
+ }
660
+ if (unit === "yearQuarter") {
661
+ const q1 = Math.floor(first.getUTCMonth() / 3) + 1, q2 = Math.floor(last.getUTCMonth() / 3) + 1;
662
+ return `Q${q1} ${firstYear} \u2026 Q${q2} ${lastYear} (${(y2 - y1) * 4 + q2 - q1 + 1})`;
663
+ }
664
+ if (unit === "year") return `${firstYear} \u2026 ${lastYear} (${y2 - y1 + 1})`;
665
+ if (unit === "yearMonth") {
666
+ const fmt = dateFormatter(locale, { year: "numeric", month: "short", timeZone: "UTC", era });
667
+ const start = /* @__PURE__ */ new Date(0), end = /* @__PURE__ */ new Date(0);
668
+ start.setUTCFullYear(y1, first.getUTCMonth(), 1);
669
+ end.setUTCFullYear(y2, last.getUTCMonth(), 1);
670
+ return `${fmt.format(start)} \u2026 ${fmt.format(end)} (${(y2 - y1) * 12 + last.getUTCMonth() - first.getUTCMonth() + 1})`;
671
+ }
672
+ return dateRangeText(span, locale);
673
+ }
674
+
675
+ // src/menu-topics.js
676
+ import { valueAddsUp } from "pivotkit-core";
533
677
  var FORMAT_CHOICES = Object.freeze(["number", "number:0", "number:2", "currency", "percent"].filter(isFormat2));
534
678
  var MORE_FORMATS = Object.freeze(["integer", "compact", "bytes", "duration:h", "duration:s"].filter(isFormat2));
535
- var COMMON_SHOW_AS = CATALOG2.showAs.filter((s) => ["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal"].includes(s));
679
+ var COMMON_SHOW_AS = CATALOG3.showAs.filter((s) => ["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal"].includes(s));
536
680
  var EXAMPLE = Object.freeze({ percent: 0.256, bytes: 1536e3, "duration:h": 1.5, "duration:s": 3725 });
537
681
  var TOP_COUNTS = Object.freeze([3, 5, 10]);
538
682
  function moveTopic(view, zone, index, count, labels, name, type, defaults) {
@@ -593,22 +737,26 @@ function axisTopics({ view, zone, index, field, types, labels, locale, state, de
593
737
  filterTopic({ view, field, labels, locale, state, encoded })
594
738
  ];
595
739
  if (date) {
740
+ const stats = groupStats(encoded, source);
741
+ const span = stats?.span;
742
+ const dateLocale = dateDisplayLocale(view.formatting?.locale || locale);
596
743
  const regroup = (unit2) => () => {
597
744
  const sourceName = fieldLabel2(source, labels.core);
598
745
  const grouped = unit2 ? groupingName(sourceName, unit2, labels) : null;
599
746
  return { view: groupField(view, field, unit2, { name: grouped ?? void 0 }).view, note: { step: "group", field: sourceName } };
600
747
  };
601
- const unit = (u) => ({ id: `group-${u}`, text: labels.units[u] ?? u, hint: labels.unitHints[u] || void 0, checked: grouping?.by === u, closes: true, change: regroup(u) });
748
+ const unit = (u) => ({ id: `group-${u}`, text: labels.units[u] ?? u, hint: groupHint(encoded, source, u, dateLocale, labels, stats), checked: grouping?.by === u, closes: true, change: regroup(u) });
602
749
  topics.push({
603
750
  id: "group",
751
+ intro: span ? fill(plural(labels.groupDataRange, calendarDays(span), { lang: labels.lang, locale: dateLocale }), { range: dateRangeText(span, dateLocale) }) : void 0,
604
752
  title: labels.groupTopic,
605
753
  kind: "menu",
606
754
  icon: "date",
607
755
  state: grouping ? labels.units[grouping.by] ?? grouping.by : labels.groupNoneShort,
608
756
  changed: Boolean(grouping),
609
757
  groups: [
610
- { title: labels.groupTimeline, choices: CATALOG2.timelineUnits.map(unit) },
611
- { title: labels.groupCyclic, choices: CATALOG2.cyclicUnits.map(unit) },
758
+ { title: labels.groupTimeline, choices: CATALOG3.timelineUnits.map(unit) },
759
+ { title: labels.groupCyclic, choices: CATALOG3.cyclicUnits.map(unit) },
612
760
  { choices: [{ id: "group-none", text: labels.groupNone, checked: !grouping, closes: true, change: regroup(null) }] }
613
761
  ]
614
762
  });
@@ -648,7 +796,7 @@ function filterTopic({ view, field, labels, locale, state, encoded }) {
648
796
  if (!Number.isSafeInteger(n) || n < 1) {
649
797
  return [];
650
798
  }
651
- const units = n > CATALOG2.relativeMaxCount ? [] : fk.months ? ["year", "month"] : ["year"];
799
+ const units = n > CATALOG3.relativeMaxCount ? [] : fk.months ? ["year", "month"] : ["year"];
652
800
  const anchor = filtersOf(view, field, ["relative"])[0]?.anchor;
653
801
  const previous = quickChoice(view, field, fk).filters[0] ?? null;
654
802
  const blanks = keepsBlanks(view, field) ? "include" : "exclude";
@@ -709,11 +857,11 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
709
857
  const spec = view.values[index];
710
858
  const type = spec.field ? types.get(spec.field.toLowerCase()) ?? "string" : "number";
711
859
  const defaults = spec.field ? defaultsOf?.(spec.field) : void 0;
712
- const name = valueLabel(spec, labels);
860
+ const name = valueLabels(view.values, labels)[index];
713
861
  const set = (patch) => () => ({ view: updateValue(view, index, patch, { defaults }), note: { step: "value", field: name } });
714
862
  const aggs = spec.field ? aggregatorsFor(type) : ["count"];
715
863
  const agg = (a) => ({ id: `agg-${a}`, text: labels.core.aggregators[a] ?? a, checked: spec.agg === a, closes: true, change: set({ agg: a }) });
716
- const rare = aggs.filter((a) => !CATALOG2.commonAggregators.includes(a));
864
+ const rare = aggs.filter((a) => !CATALOG3.commonAggregators.includes(a));
717
865
  const topics = [
718
866
  {
719
867
  id: "summarize",
@@ -721,7 +869,7 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
721
869
  kind: "menu",
722
870
  icon: "sigma",
723
871
  state: labels.core.aggregators[spec.agg] ?? spec.agg,
724
- groups: [{ choices: CATALOG2.commonAggregators.filter((a) => aggs.includes(a)).map(agg) }, ...rare.length ? [{ title: labels.moreStatistics, choices: rare.map(agg) }] : []]
872
+ groups: [{ choices: CATALOG3.commonAggregators.filter((a) => aggs.includes(a)).map(agg) }, ...rare.length ? [{ title: labels.moreStatistics, choices: rare.map(agg) }] : []]
725
873
  }
726
874
  ];
727
875
  if (numericResult(spec, type)) {
@@ -729,7 +877,7 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
729
877
  const text = labels.showAsNames[s] ?? s;
730
878
  return { id: `showas-${s}`, text, keywords: text.includes("%") ? labels.showAsKeywords : void 0, checked: spec.showAs?.type === s, change: set({ showAs: { type: s, axis: spec.showAs?.axis ?? "rows" } }) };
731
879
  };
732
- const along = spec.showAs && CATALOG2.showAsAlongAxis.includes(spec.showAs.type) ? spec.showAs : null;
880
+ const along = spec.showAs && CATALOG3.showAsAlongAxis.includes(spec.showAs.type) ? spec.showAs : null;
733
881
  topics.push({
734
882
  id: "showAs",
735
883
  title: labels.showAs,
@@ -740,7 +888,7 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
740
888
  changed: Boolean(spec.showAs),
741
889
  groups: [
742
890
  { choices: [{ id: "showas-none", text: labels.showAsNone, checked: !spec.showAs, change: set({ showAs: null }) }, ...COMMON_SHOW_AS.map(showAs)] },
743
- { title: labels.moreCalculations, choices: CATALOG2.showAs.filter((s) => !COMMON_SHOW_AS.includes(s)).map(showAs) },
891
+ { title: labels.moreCalculations, choices: CATALOG3.showAs.filter((s) => !COMMON_SHOW_AS.includes(s)).map(showAs) },
744
892
  ...along ? [{ title: labels.along, choices: ["rows", "cols"].map((axis) => ({ id: `along-${axis}`, text: labels.zones[axis], checked: along.axis === axis, change: set({ showAs: { ...along, axis } }) })) }] : []
745
893
  ]
746
894
  });
@@ -802,17 +950,29 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
802
950
  topics.push(moveTopic(view, "values", index, view.values.length, labels, name, type));
803
951
  return topics;
804
952
  }
805
- function optionTopics({ view, labels, folding, tips, explanations, act }) {
806
- const help = [];
807
- if (tips.controls) {
808
- help.push({ id: "show-tips", text: labels.showTips, checkbox: true, checked: tips.on, run: () => act.tipsOn(!tips.on) });
809
- }
810
- if (explanations) {
811
- help.push({ id: "show-explanations", text: labels.showSettingInfo, checkbox: true, checked: explanations.on, run: () => act.explain(!explanations.on) });
953
+ function rowFoldTexts(view, labels) {
954
+ if (view.rows.length < 2) {
955
+ return { expand: labels.chartShowDetails, collapse: labels.chartShowTotals, named: false };
812
956
  }
813
- if (tips.controls) {
814
- help.push({ id: "reset-tips", text: labels.resetTips, icon: "reset", disabled: !tips.canReset, run: act.resetTips });
957
+ const name = (f) => fieldLabel2(f, labels.core);
958
+ return { expand: fill(labels.chartShowEach, { field: name(view.rows.at(-1)) }), collapse: fill(labels.chartShowOnly, { field: name(view.rows[0]) }), named: true };
959
+ }
960
+ function foldState(view, folding, labels) {
961
+ const name = (f) => fieldLabel2(f, labels.core);
962
+ if (!folding.collapsed) {
963
+ return { text: fill(labels.chartFoldEach, { field: name(view.rows.at(-1)) }), changed: false };
815
964
  }
965
+ return { text: folding.canCollapse ? labels.chartFoldSome : fill(labels.chartFoldOnly, { field: name(view.rows[0]) }), changed: true };
966
+ }
967
+ function foldChoices(folding, labels, act, words, ids) {
968
+ const why = (key) => key && Object.hasOwn(labels, key) ? labels[key] : void 0;
969
+ return [
970
+ { id: ids[0], text: words.expand, icon: "plus", closes: true, disabled: !folding.canExpand, reason: why(folding.why.expand), run: act.expand },
971
+ { id: ids[1], text: words.collapse, icon: "chevronRight", hint: words.hint, closes: true, disabled: !folding.canCollapse, reason: why(folding.why.collapse), run: act.collapse }
972
+ ];
973
+ }
974
+ function tableTopics({ view, labels, folding, act }) {
975
+ const words = rowFoldTexts(view, labels);
816
976
  return [
817
977
  {
818
978
  id: "totals",
@@ -833,18 +993,157 @@ function optionTopics({ view, labels, folding, tips, explanations, act }) {
833
993
  title: labels.zones.rows,
834
994
  kind: "inline",
835
995
  titled: true,
996
+ groups: [{ choices: foldChoices(folding, labels, act, { expand: labels.expandAll, collapse: labels.collapseAll, hint: words.named ? words.collapse : void 0 }, ["expand-all", "collapse-all"]) }]
997
+ }
998
+ ];
999
+ }
1000
+ function moreTopics({ labels, tips, explanations, act }) {
1001
+ const help = [];
1002
+ if (tips.controls) {
1003
+ help.push({ id: "show-tips", text: labels.showTips, checkbox: true, checked: tips.on, run: () => act.tipsOn(!tips.on) });
1004
+ }
1005
+ if (explanations) {
1006
+ help.push({ id: "show-explanations", text: labels.showSettingInfo, checkbox: true, checked: explanations.on, run: () => act.explain(!explanations.on) });
1007
+ }
1008
+ if (tips.controls) {
1009
+ help.push({ id: "reset-tips", text: labels.resetTips, icon: "reset", disabled: !tips.canReset, run: act.resetTips });
1010
+ }
1011
+ help.push({ id: "shortcuts", text: labels.shortcutsTitle, icon: "info", open: "shortcuts" });
1012
+ return [
1013
+ { id: "help", title: labels.helpAndShortcuts, levelTitle: labels.help, kind: "menu", icon: "info", testId: "more-help", groups: [{ choices: help }] },
1014
+ { id: "shortcuts", title: labels.shortcutsTitle, kind: "panel", hidden: true, levelTitle: `${labels.help} \u203A ${labels.shortcutsTitle}` }
1015
+ ];
1016
+ }
1017
+ var VALUE_LABELS = Object.freeze({ slices: ["auto", "off", "value", "percent", "both"], other: ["auto", "off", "value"] });
1018
+ function chartTopics({ view, drawn, labels, names, act, lines = { rules: { average: true, trend: true, target: true, notes: [] }, targetText: "" }, drawnColors = /* @__PURE__ */ new Map(), folding }) {
1019
+ const chart = view.chart;
1020
+ const pie = SLICE_TYPES.includes(drawn);
1021
+ const axis = CHART_TYPES[drawn]?.axis ?? false;
1022
+ const pickOf = (key, value, text, id, info = void 0) => ({ id, text, checked: (chart[key] ?? null) === value, info, run: () => act.display({ [key]: value }) });
1023
+ const flip = (key, text, id, info = void 0) => ({ id, text, checkbox: true, checked: Boolean(chart[key]), info, run: () => act.display({ [key]: !chart[key] }) });
1024
+ const valueLabels2 = !pie && (chart.valueLabels === "percent" || chart.valueLabels === "both") ? "value" : chart.valueLabels;
1025
+ const topics = [
1026
+ {
1027
+ id: "valueLabels",
1028
+ title: labels.valueLabels,
1029
+ kind: "menu",
1030
+ state: labels.valueLabelNames[valueLabels2],
1031
+ changed: valueLabels2 !== "auto",
1032
+ groups: [{ choices: (pie ? VALUE_LABELS.slices : VALUE_LABELS.other).map((v) => ({ ...pickOf("valueLabels", v, labels.valueLabelNames[v], `labels-${v}`), checked: valueLabels2 === v })) }]
1033
+ },
1034
+ { id: "legend", title: labels.legend, kind: "menu", state: labels.legendNames[chart.legend], changed: chart.legend !== "auto", groups: [{ choices: ["auto", "bottom", "right", "off"].map((v) => pickOf("legend", v, labels.legendNames[v], `legend-${v}`)) }] },
1035
+ { id: "title", title: labels.chartTitle, kind: "panel", state: chart.title || labels.chartTitleNone, changed: Boolean(chart.title) }
1036
+ ];
1037
+ if (axis) {
1038
+ const groups = view.rows.length >= 2;
1039
+ const off = [groups && chart.groupLabels !== "auto" ? `${labels.groupLabels.toLowerCase()} ${labels.groupLabelNames[chart.groupLabels].toLowerCase()}` : null, chart.zoom !== "auto" ? `${labels.zoom.toLowerCase()} ${labels.zoomNames[chart.zoom].toLowerCase()}` : null].filter(Boolean);
1040
+ topics.push({
1041
+ id: "axis",
1042
+ title: labels.chartAxis,
1043
+ kind: "menu",
1044
+ state: [labels.axisLabelNames[chart.axisLabels], ...off].join(", "),
1045
+ changed: chart.axisLabels !== "auto" || off.length > 0,
1046
+ groups: [
1047
+ { title: labels.axisLabels, choices: ["auto", "all", "nth"].map((v) => pickOf("axisLabels", v, labels.axisLabelNames[v], `axis-${v}`)) },
1048
+ ...groups ? [{ title: labels.groupLabels, choices: ["auto", "on", "off"].map((v) => pickOf("groupLabels", v, labels.groupLabelNames[v], `groups-${v}`, v === "auto" ? "groupLabels" : void 0)) }] : [],
1049
+ { title: labels.zoom, choices: ["auto", "on", "off"].map((v) => pickOf("zoom", v, labels.zoomNames[v], `zoom-${v}`, v === "auto" ? "zoom" : void 0)) }
1050
+ ]
1051
+ });
1052
+ }
1053
+ if (drawn !== "heatmap") {
1054
+ const mode = chart.tooltip ?? "auto";
1055
+ const state = [axis ? labels.tooltipNames[mode] : null, chart.tooltipShare ? labels.tooltipShare : null].filter(Boolean).join(", ");
1056
+ topics.push({
1057
+ id: "tooltip",
1058
+ title: labels.tooltip,
1059
+ kind: "menu",
1060
+ info: axis ? "tooltip" : void 0,
1061
+ state: state || null,
1062
+ changed: mode !== "auto" || Boolean(chart.tooltipShare),
1063
+ groups: [...axis ? [{ choices: ["auto", "axis"].map((v) => pickOf("tooltip", v, labels.tooltipNames[v], `tooltip-${v}`)) }] : [], { choices: [flip("tooltipShare", labels.tooltipShare, "chart-tooltip-share")] }]
1064
+ });
1065
+ }
1066
+ if (axis) {
1067
+ const now = chart.referenceLines ?? { average: false, trend: false, target: null };
1068
+ const words = labels.core.referenceLines;
1069
+ const { rules, targetText } = lines;
1070
+ const notes = Array.isArray(rules.notes) ? rules.notes : [];
1071
+ const say = (keys) => {
1072
+ const note2 = notes.find((n) => keys.includes(n));
1073
+ return note2 && Object.hasOwn(labels.linesNotes, note2) ? labels.linesNotes[note2] : void 0;
1074
+ };
1075
+ const total = ["noTotal", "percentStack", "negative"];
1076
+ const set = (patch) => act.display({ referenceLines: { ...now, ...patch } });
1077
+ const choices = [
1078
+ { id: "line-average", text: words.average, checkbox: true, checked: now.average, disabled: !rules.average, reason: rules.average ? void 0 : say(total), run: () => set({ average: !now.average }) },
1079
+ { id: "line-trend", text: words.trend, checkbox: true, checked: now.trend, disabled: !rules.trend, reason: rules.trend ? void 0 : say([...total, "noTime"]), run: () => set({ trend: !now.trend }) },
1080
+ { id: "line-target", text: words.target, hint: now.target !== null ? targetText : labels.targetNone, open: "linesTarget", disabled: !rules.target, reason: rules.target ? void 0 : say(["noTotal", "percentStack", "mixedUnits"]) },
1081
+ // a target the chart cannot draw stays removable
1082
+ ...!rules.target && now.target !== null ? [{ id: "target-remove", text: labels.targetRemove, run: () => set({ target: null }) }] : []
1083
+ ];
1084
+ const on2 = [now.average ? words.average : null, now.trend ? words.trend : null, now.target !== null ? words.target : null].filter(Boolean);
1085
+ const note = notes.includes("table") ? labels.linesNotes.table : notes.includes("byIndex") && rules.trend ? labels.linesNotes.byIndex : null;
1086
+ topics.push({ id: "lines", title: labels.referenceLines, kind: "menu", state: on2.length ? on2.join(", ") : labels.linesOff, changed: on2.length > 0, groups: [{ choices }], note, noteId: "lines-note" });
1087
+ topics.push({ id: "linesTarget", title: words.target, kind: "panel", hidden: true, levelTitle: `${labels.referenceLines} \u203A ${words.target}` });
1088
+ }
1089
+ if (names.length > 0) {
1090
+ const only = names.length === 1;
1091
+ const hidden = (chart.hidden ?? []).filter((n) => names.includes(n)).length;
1092
+ const now = chart.hidden ?? [];
1093
+ const own = chart.colors ?? [];
1094
+ const same2 = (a, b) => a.toLowerCase() === b.toLowerCase();
1095
+ const recolor = (name, color) => act.display({ colors: [...own.filter((c) => !same2(c.name, name)), ...color ? [{ name, color }] : []] });
1096
+ const stale = own.filter((c) => !names.some((n) => same2(n, c.name)));
1097
+ topics.push({
1098
+ id: "series",
1099
+ title: labels.shownSeries,
1100
+ kind: "menu",
1101
+ info: "chartColors",
1102
+ state: fill(labels.seriesShownOf, { shown: String(names.length - hidden), count: String(names.length) }),
1103
+ changed: hidden > 0 || own.length > 0,
1104
+ // every series or slice, the level scrolls; a switch keeps the level open for the next one;
1105
+ // beside each its colour, and Default where the view fixes one
836
1106
  groups: [
837
1107
  {
838
- choices: [
839
- { id: "expand-all", text: labels.expandAll, icon: "plus", closes: true, disabled: !folding.canExpand, reason: folding.why.expand ? labels[folding.why.expand] : void 0, run: act.expand },
840
- { id: "collapse-all", text: labels.collapseAll, icon: "chevronRight", closes: true, disabled: !folding.canCollapse, reason: folding.why.collapse ? labels[folding.why.collapse] : void 0, run: act.collapse }
841
- ]
842
- }
1108
+ choices: names.map((name, i) => {
1109
+ const mine = own.find((c) => same2(c.name, name));
1110
+ return {
1111
+ id: `series-${i}`,
1112
+ text: name,
1113
+ checkbox: true,
1114
+ checked: only || !now.includes(name),
1115
+ ...only ? { disabled: true, reason: labels.seriesOnly } : {},
1116
+ run: () => act.display({ hidden: hiddenAfter(now, name, now.includes(name)) }),
1117
+ color: { id: `series-${i}-color`, value: mine?.color ?? drawnColors.get(name) ?? "", label: fill(labels.colorOf, { name }), pick: (c) => recolor(name, c) },
1118
+ ...mine ? { actions: [{ id: `series-${i}-default`, text: labels.colorDefault, label: `${labels.colorDefault}: ${name}`, icon: "reset", run: () => recolor(name, null) }] } : {}
1119
+ };
1120
+ })
1121
+ },
1122
+ // a view's colour for a name the chart does not show: Remove
1123
+ ...stale.length ? [{ title: labels.colorsNotShown, choices: stale.map((c, i) => ({ id: `color-stale-${i}`, text: c.name, label: `${labels.colorRemove}: ${c.name}`, icon: "x", run: () => recolor(c.name, null) })) }] : []
843
1124
  ]
844
- },
845
- { id: "help", title: labels.help, kind: "inline", titled: true, groups: [{ choices: help }] },
846
- { id: "shortcuts", title: labels.shortcutsTitle, kind: "panel", icon: "info" }
847
- ];
1125
+ });
1126
+ }
1127
+ const layout = [];
1128
+ if ((drawn === "stacked" || drawn === "area") && view.values.length > 0 && view.values.every(valueAddsUp)) {
1129
+ layout.push(flip("stackPercent", labels.stackPercent, "chart-stack-percent", "stackPercent"));
1130
+ }
1131
+ if (drawn === "line" || drawn === "area") {
1132
+ layout.push(flip("smooth", labels.smoothLines, "chart-smooth"));
1133
+ }
1134
+ if (pie) {
1135
+ layout.push(...["outside", "inside"].map((v) => ({ ...pickOf("labelPosition", v, labels.labelPositionNames[v], `label-position-${v}`, v === "outside" ? "labelPosition" : void 0), checked: (chart.labelPosition ?? "outside") === v, disabled: chart.valueLabels === "off" })));
1136
+ }
1137
+ const on = layout.filter((c) => c.checked && (c.checkbox || c.id === "label-position-inside")).map((c) => c.text);
1138
+ if (folding && act.expand && act.collapse) {
1139
+ layout.push(...foldChoices(folding, labels, { expand: act.expand, collapse: act.collapse }, rowFoldTexts(view, labels), ["chart-show-each", "chart-show-only"]));
1140
+ }
1141
+ const fold = folding && view.rows.length >= 2 ? foldState(view, folding, labels) : null;
1142
+ if (layout.length) {
1143
+ const state = [...on, ...fold ? [fold.text] : []].join(", ");
1144
+ topics.push({ id: "layout", title: labels.chartLayout, kind: "menu", state: state || null, changed: on.length > 0 || Boolean(fold?.changed), groups: [{ choices: layout }] });
1145
+ }
1146
+ return topics;
848
1147
  }
849
1148
  function entryIds(templates) {
850
1149
  const seen = /* @__PURE__ */ new Map();
@@ -942,7 +1241,7 @@ function tabLeaves(e, close) {
942
1241
  close();
943
1242
  return true;
944
1243
  }
945
- function MenuList({ label, labelledBy, className, close, children, testId }) {
1244
+ function MenuList({ label, labelledBy, describedBy, className, close, children, testId }) {
946
1245
  const ref = useRef(
947
1246
  /** @type {HTMLDivElement | null} */
948
1247
  null
@@ -994,6 +1293,7 @@ function MenuList({ label, labelledBy, className, close, children, testId }) {
994
1293
  e.preventDefault();
995
1294
  e.stopPropagation();
996
1295
  items[i].focus();
1296
+ items[i].scrollIntoView?.({ block: "nearest" });
997
1297
  }
998
1298
  };
999
1299
  const seg = (
@@ -1037,12 +1337,13 @@ function MenuList({ label, labelledBy, className, close, children, testId }) {
1037
1337
  go(typeAheadIndex(items.map((el) => el.dataset.pkText ?? el.textContent ?? ""), at, typed.current.text));
1038
1338
  }
1039
1339
  };
1040
- return /* @__PURE__ */ React3.createElement("div", { ref, role: "menu", "aria-label": label, "aria-labelledby": labelledBy, className: `pk-level-menu${className ? ` ${className}` : ""}`, onKeyDown, onFocus, "data-testid": testId }, children);
1340
+ return /* @__PURE__ */ React3.createElement("div", { ref, role: "menu", "aria-label": label, "aria-labelledby": labelledBy, "aria-describedby": describedBy, className: `pk-level-menu${className ? ` ${className}` : ""}`, onKeyDown, onFocus, "data-testid": testId }, children);
1041
1341
  }
1042
- function MenuItem({ id, text, onSelect, checked, checkbox, hint, icon, danger, testId, start, plain, label, className, disabled, reason, haspopup, level, description, current, children }) {
1342
+ function MenuItem({ id, text, onSelect, checked, checkbox, hint, icon, danger, testId, start, plain, label, className, disabled, reason, haspopup, level, description, current, note, children }) {
1043
1343
  const role = checked === void 0 ? "menuitem" : checkbox ? "menuitemcheckbox" : "menuitemradio";
1044
1344
  const reasonId = useId();
1045
- const describedBy = [disabled && reason ? reasonId : null, description ? `${reasonId}-d` : null].filter(Boolean).join(" ") || void 0;
1345
+ const sub = disabled ? reason : note;
1346
+ const describedBy = [sub ? reasonId : null, description ? `${reasonId}-d` : null].filter(Boolean).join(" ") || void 0;
1046
1347
  return /* @__PURE__ */ React3.createElement(
1047
1348
  "button",
1048
1349
  {
@@ -1068,7 +1369,7 @@ function MenuItem({ id, text, onSelect, checked, checkbox, hint, icon, danger, t
1068
1369
  /** @type {any} */
1069
1370
  icon
1070
1371
  ) }) : null),
1071
- /* @__PURE__ */ React3.createElement("span", { className: "pk-option-text" }, text, disabled && reason ? /* @__PURE__ */ React3.createElement("span", { id: reasonId, className: "pk-option-hint", "data-testid": `${testId ?? id}-reason` }, reason) : null),
1372
+ /* @__PURE__ */ React3.createElement("span", { className: "pk-option-text" }, text, sub ? /* @__PURE__ */ React3.createElement("span", { id: reasonId, className: "pk-option-hint", "data-testid": `${testId ?? id}-${disabled ? "reason" : "note"}` }, sub) : null),
1072
1373
  hint ? /* @__PURE__ */ React3.createElement("span", { className: "pk-item-hint" }, hint) : null,
1073
1374
  description ? /* @__PURE__ */ React3.createElement("span", { id: `${reasonId}-d`, hidden: true }, description) : null,
1074
1375
  children
@@ -1077,11 +1378,15 @@ function MenuItem({ id, text, onSelect, checked, checkbox, hint, icon, danger, t
1077
1378
  function ChoiceItem({ choice: c, onPick, start }) {
1078
1379
  const { explain, labels } = useContext2(HelpContext);
1079
1380
  const text = c.info && explain && labels?.settingInfo && Object.hasOwn(labels.settingInfo, c.info) ? labels.settingInfo[c.info] : null;
1080
- const item = /* @__PURE__ */ React3.createElement(MenuItem, { id: c.id, testId: c.testId, text: c.text, hint: c.hint, icon: c.icon, checked: c.checked, checkbox: c.checkbox, current: c.current, disabled: c.disabled, reason: c.reason, description: text, start, haspopup: c.open ? "dialog" : void 0, className: c.open ? "pk-topic-row" : void 0, onSelect: () => onPick(c) }, c.open ? /* @__PURE__ */ React3.createElement(Icon, { name: "chevronRight", size: 16, className: "pk-topic-chevron" }) : null);
1081
- if (!text && !c.actions?.length) {
1381
+ const className = [c.open ? "pk-topic-row" : null, c.className].filter(Boolean).join(" ") || void 0;
1382
+ const item = /* @__PURE__ */ React3.createElement(MenuItem, { id: c.id, testId: c.testId, text: c.text, label: c.label, hint: c.hint, icon: c.icon, checked: c.checked, checkbox: c.checkbox, current: c.current, disabled: c.disabled, reason: c.reason, description: text, note: c.note, start, haspopup: c.open ? "dialog" : void 0, className, onSelect: () => onPick(c) }, (c.tags ?? []).map((t) => /* @__PURE__ */ React3.createElement("span", { key: t.text, className: "pk-tag", "aria-hidden": "true" }, /* @__PURE__ */ React3.createElement(Icon, { name: (
1383
+ /** @type {any} */
1384
+ t.icon
1385
+ ), size: 12 }), t.text)), c.open ? /* @__PURE__ */ React3.createElement(Icon, { name: "chevronRight", size: 16, className: "pk-topic-chevron" }) : null);
1386
+ if (!text && !c.actions?.length && !c.color) {
1082
1387
  return item;
1083
1388
  }
1084
- return /* @__PURE__ */ React3.createElement("div", { role: "none", className: "pk-setting-row" }, item, (c.actions ?? []).map((a) => /* @__PURE__ */ React3.createElement("button", { key: a.id, type: "button", role: "menuitem", tabIndex: -1, className: "pk-icon-btn", "aria-label": a.label, title: a.label, "aria-haspopup": a.open ? "dialog" : void 0, "data-pk-item": a.id, "data-pk-text": a.label, "data-testid": a.testId ?? a.id, onClick: () => onPick(a) }, /* @__PURE__ */ React3.createElement(Icon, { name: (
1389
+ return /* @__PURE__ */ React3.createElement("div", { role: "none", className: "pk-setting-row" }, item, c.color ? /* @__PURE__ */ React3.createElement(ColorPick, { ...c.color }) : null, (c.actions ?? []).map((a) => /* @__PURE__ */ React3.createElement("button", { key: a.id, type: "button", role: "menuitem", tabIndex: -1, className: "pk-icon-btn", "aria-label": a.label, title: a.label, "aria-haspopup": a.open ? "dialog" : void 0, "data-pk-item": a.id, "data-pk-text": a.label, "data-testid": a.testId ?? a.id, onClick: () => onPick(a) }, /* @__PURE__ */ React3.createElement(Icon, { name: (
1085
1390
  /** @type {any} */
1086
1391
  a.icon
1087
1392
  ) }))), text ? /* @__PURE__ */ React3.createElement("span", { "aria-hidden": "true" }, /* @__PURE__ */ React3.createElement(SettingInfo, { id: (
@@ -1089,11 +1394,43 @@ function ChoiceItem({ choice: c, onPick, start }) {
1089
1394
  c.info
1090
1395
  ), name: c.text, tabIndex: -1 })) : null);
1091
1396
  }
1397
+ function ColorPick({ id, value, label, pick: pick2 }) {
1398
+ const field = useRef(
1399
+ /** @type {HTMLInputElement | null} */
1400
+ null
1401
+ );
1402
+ const button = useRef(
1403
+ /** @type {HTMLButtonElement | null} */
1404
+ null
1405
+ );
1406
+ const latest = useRef(pick2);
1407
+ useEffect(() => {
1408
+ latest.current = pick2;
1409
+ });
1410
+ useEffect(() => {
1411
+ const el = field.current;
1412
+ const picked = () => {
1413
+ if (el) {
1414
+ latest.current(el.value);
1415
+ button.current?.focus({ preventScroll: true });
1416
+ }
1417
+ };
1418
+ el?.addEventListener("change", picked);
1419
+ return () => el?.removeEventListener("change", picked);
1420
+ }, []);
1421
+ useEffect(() => {
1422
+ if (field.current && value && field.current.value !== value) {
1423
+ field.current.value = value;
1424
+ }
1425
+ }, [value]);
1426
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("button", { ref: button, type: "button", role: "menuitem", tabIndex: -1, className: "pk-icon-btn pk-color-pick", "aria-label": value ? `${label}, ${value}` : label, "aria-haspopup": "dialog", title: label, "data-pk-item": id, "data-pk-text": label, "data-testid": id, onClick: () => field.current?.click() }, /* @__PURE__ */ React3.createElement("span", { className: "pk-dot", "aria-hidden": "true", ref: (el) => el?.style.setProperty("background-color", value || "transparent") })), /* @__PURE__ */ React3.createElement("input", { ref: field, type: "color", className: "pk-sr", tabIndex: -1, "aria-hidden": "true", defaultValue: value || void 0, "data-testid": `${id}-field` }));
1427
+ }
1092
1428
  function TopicRow({ topic, labels, onOpen }) {
1093
1429
  return /* @__PURE__ */ React3.createElement(
1094
1430
  MenuItem,
1095
1431
  {
1096
1432
  id: `topic-${topic.id}`,
1433
+ testId: topic.testId,
1097
1434
  level: topic.id,
1098
1435
  text: topic.title,
1099
1436
  plain: topic.title,
@@ -1139,7 +1476,7 @@ function SearchHits({ hits, labels, onPick, onOpen, close }) {
1139
1476
  }
1140
1477
  return /* @__PURE__ */ React3.createElement(MenuList, { label: labels.searchResults, close, testId: "menu-search-hits" }, hits.map((h) => /* @__PURE__ */ React3.createElement(MenuItem, { key: h.id, id: `hit-${h.id}`, text: h.choice ? h.text : `${h.text}\u2026`, plain: h.text, checked: h.choice?.checked, icon: h.choice ? h.topic.icon : "chevronRight", hint: h.path || void 0, haspopup: h.choice ? void 0 : "dialog", onSelect: () => h.choice ? onPick(h.choice) : onOpen(h.topic.id, void 0, h.focus) })));
1141
1478
  }
1142
- function LevelMenu({ name, labels, topics, close, onPick, panel, head, foot, search = false, locale, focusAgain }) {
1479
+ function LevelMenu({ name, labels, topics, close, onPick, panel, head, foot, search = false, locale, focusAgain, filter, searchText }) {
1143
1480
  const [nav, setNav] = useState2(
1144
1481
  /** @type {{ stack: Array<{ level: string, from: string, hint?: string }>, focus: string | null }} */
1145
1482
  { stack: [], focus: null }
@@ -1178,6 +1515,11 @@ function LevelMenu({ name, labels, topics, close, onPick, panel, head, foot, sea
1178
1515
  open(choice.open, choice.backTo ?? `item:${choice.id}`);
1179
1516
  return;
1180
1517
  }
1518
+ if (choice.checkbox && nav.stack.length) {
1519
+ onPick(choice);
1520
+ setNav({ stack: nav.stack, focus: `item:${choice.id}` });
1521
+ return;
1522
+ }
1181
1523
  if (!choice.closes) {
1182
1524
  setNav({ stack: [], focus: query ? "search" : nav.stack.length ? nav.stack[0].from : `item:${choice.id}` });
1183
1525
  setQuery("");
@@ -1208,17 +1550,21 @@ function LevelMenu({ name, labels, topics, close, onPick, panel, head, foot, sea
1208
1550
  }
1209
1551
  };
1210
1552
  const first = () => {
1211
- const hits = search && query.trim() ? searchHits(searchEntries(topics, query), query, locale) : null;
1212
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, head, search ? /* @__PURE__ */ React3.createElement("label", { className: "pk-search pk-level-search" }, /* @__PURE__ */ React3.createElement(Icon, { name: "search" }), /* @__PURE__ */ React3.createElement("span", { className: "pk-sr" }, fill(labels.searchMenu, { name })), /* @__PURE__ */ React3.createElement(
1553
+ const typed = search && query.trim() ? query : "";
1554
+ const shown = typed && filter ? filter(typed) : topics;
1555
+ const hits = typed && !filter ? searchHits(searchEntries(topics, query), query, locale) : null;
1556
+ const none = typed && filter && !shown.some((t) => !t.hidden && (t.groups ?? []).some((g) => g.choices.length));
1557
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null, head, search ? /* @__PURE__ */ React3.createElement("label", { className: "pk-search pk-level-search" }, /* @__PURE__ */ React3.createElement(Icon, { name: "search" }), /* @__PURE__ */ React3.createElement("span", { className: "pk-sr" }, searchText ?? fill(labels.searchMenu, { name })), /* @__PURE__ */ React3.createElement(
1213
1558
  ClearInput,
1214
1559
  {
1215
1560
  type: "search",
1216
1561
  value: query,
1217
- placeholder: labels.searchMenuShort,
1562
+ placeholder: searchText ?? labels.searchMenuShort,
1218
1563
  onChange: setQuery,
1219
1564
  clearLabel: labels.clearText,
1220
- "aria-label": fill(labels.searchMenu, { name }),
1565
+ "aria-label": searchText ?? fill(labels.searchMenu, { name }),
1221
1566
  autoComplete: "off",
1567
+ "data-autofocus": filter ? "" : void 0,
1222
1568
  "data-testid": "menu-search",
1223
1569
  onKeyDown: (e) => {
1224
1570
  if (e.key === "ArrowDown") {
@@ -1229,9 +1575,9 @@ function LevelMenu({ name, labels, topics, close, onPick, panel, head, foot, sea
1229
1575
  }
1230
1576
  }
1231
1577
  }
1232
- )) : null, /* @__PURE__ */ React3.createElement("div", { className: "pk-level-first" }, hits ? /* @__PURE__ */ React3.createElement(SearchHits, { hits, labels, onPick: pick2, onOpen: open, close }) : /* @__PURE__ */ React3.createElement(MenuList, { label: name, close, testId: "level-first" }, topics.map((t) => /* @__PURE__ */ React3.createElement(TopicFirst, { key: t.id, topic: t, labels, onPick: pick2, onOpen: () => open(t.id) })), foot ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { role: "separator", className: "pk-level-sep" }), foot) : null)));
1578
+ )) : null, /* @__PURE__ */ React3.createElement("div", { className: "pk-level-first" }, hits || none ? /* @__PURE__ */ React3.createElement(SearchHits, { hits: hits ?? [], labels, onPick: pick2, onOpen: open, close }) : /* @__PURE__ */ React3.createElement(MenuList, { label: name, close, testId: "level-first" }, shown.map((t) => /* @__PURE__ */ React3.createElement(TopicFirst, { key: t.id, topic: t, labels, onPick: pick2, onOpen: () => open(t.id) })), foot ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { role: "separator", className: "pk-level-sep" }), foot) : null)));
1233
1579
  };
1234
- return /* @__PURE__ */ React3.createElement("div", { ref: box, className: "pk-levels", onKeyDown, "data-level": level ?? "" }, topic ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { className: "pk-level-head" }, /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-link pk-level-back", onClick: () => back(), "aria-label": fill(labels.backTo, { name }), "data-testid": "level-back" }, /* @__PURE__ */ React3.createElement(Icon, { name: "chevronRight", size: 16, className: "pk-flip" }), labels.back), /* @__PURE__ */ React3.createElement("h3", { id: titleId, className: "pk-level-title", "data-testid": "level-title" }, fill(labels.levelTitle, { name, topic: topic.levelTitle ?? topic.title })), topic.info ? /* @__PURE__ */ React3.createElement(SettingInfo, { id: topic.info, name: topic.title }) : null), /* @__PURE__ */ React3.createElement("div", { className: "pk-level-body", "data-testid": `level-${topic.id}` }, topic.kind === "menu" ? /* @__PURE__ */ React3.createElement(MenuList, { labelledBy: titleId, close }, /* @__PURE__ */ React3.createElement(Groups, { topic, onPick: pick2 })) : /* @__PURE__ */ React3.createElement("div", { role: "group", "aria-labelledby": titleId, className: "pk-level-panel" }, panel(topic.id, back, nav.stack[nav.stack.length - 1]?.hint)))) : first());
1580
+ return /* @__PURE__ */ React3.createElement("div", { ref: box, className: "pk-levels", onKeyDown, "data-level": level ?? "" }, topic ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { className: "pk-level-head" }, /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-link pk-level-back", onClick: () => back(), "aria-label": fill(labels.backTo, { name }), "data-testid": "level-back" }, /* @__PURE__ */ React3.createElement(Icon, { name: "chevronRight", size: 16, className: "pk-flip" }), labels.back), /* @__PURE__ */ React3.createElement("h3", { id: titleId, className: "pk-level-title", "data-testid": "level-title" }, fill(labels.levelTitle, { name, topic: topic.levelTitle ?? topic.title })), topic.info ? /* @__PURE__ */ React3.createElement(SettingInfo, { id: topic.info, name: topic.title }) : null), /* @__PURE__ */ React3.createElement("div", { className: "pk-level-body", "data-testid": `level-${topic.id}` }, topic.kind === "menu" ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, topic.intro ? /* @__PURE__ */ React3.createElement("p", { id: `${titleId}-intro`, className: "pk-hint pk-menu-hint" }, topic.intro) : null, /* @__PURE__ */ React3.createElement(MenuList, { labelledBy: titleId, describedBy: topic.intro ? `${titleId}-intro` : void 0, close }, /* @__PURE__ */ React3.createElement(Groups, { topic, onPick: pick2 }))) : /* @__PURE__ */ React3.createElement("div", { role: "group", "aria-labelledby": titleId, className: "pk-level-panel" }, panel(topic.id, back, nav.stack[nav.stack.length - 1]?.hint)))) : first());
1235
1581
  }
1236
1582
  function useLater(wait = 450) {
1237
1583
  const timer = useRef(
@@ -1320,62 +1666,6 @@ function useAppliedText(applied, apply, wait = 450) {
1320
1666
 
1321
1667
  // src/menu-fields.jsx
1322
1668
  import React4, { useId as useId2 } from "react";
1323
-
1324
- // src/numbers.js
1325
- var cache = /* @__PURE__ */ new Map();
1326
- function marks(locale) {
1327
- let m = cache.get(locale);
1328
- if (!m) {
1329
- let parts;
1330
- try {
1331
- parts = new Intl.NumberFormat(locale).formatToParts(12345.6);
1332
- } catch {
1333
- parts = new Intl.NumberFormat("en-US").formatToParts(12345.6);
1334
- }
1335
- m = {
1336
- decimal: parts.find((p) => p.type === "decimal")?.value ?? ".",
1337
- group: parts.find((p) => p.type === "group")?.value ?? ","
1338
- };
1339
- cache.set(locale, m);
1340
- }
1341
- return m;
1342
- }
1343
- var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1344
- var PLAIN = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
1345
- function parseNumber(text, locale) {
1346
- const t = String(text ?? "").replace(/[\s\u00a0\u202f]/g, "").replace(/\u2212/g, "-");
1347
- if (t === "") {
1348
- return null;
1349
- }
1350
- const { decimal, group } = marks(locale);
1351
- const g = /[\s\u00a0\u202f]/.test(group) ? "" : escape(group);
1352
- const d = escape(decimal);
1353
- const grouped = g ? `\\d{1,3}(?:${g}\\d{3})+` : "(?!)";
1354
- const local = new RegExp(`^([+-]?)(${grouped}|\\d+)?(?:${d}(\\d+))?$`);
1355
- const match = local.exec(t);
1356
- if (match && (match[2] !== void 0 || match[3] !== void 0)) {
1357
- const whole = (match[2] ?? "0").split(group).join("");
1358
- const n = Number(`${match[1]}${whole}${match[3] !== void 0 ? `.${match[3]}` : ""}`);
1359
- return Number.isFinite(n) ? n : null;
1360
- }
1361
- if (PLAIN.test(t)) {
1362
- const n = Number(t);
1363
- return Number.isFinite(n) ? n : null;
1364
- }
1365
- return null;
1366
- }
1367
- function numberText(n, locale) {
1368
- if (typeof n !== "number" || !Number.isFinite(n)) {
1369
- return "";
1370
- }
1371
- try {
1372
- return n.toLocaleString(locale, { useGrouping: false, maximumFractionDigits: 20 });
1373
- } catch {
1374
- return String(n);
1375
- }
1376
- }
1377
-
1378
- // src/menu-fields.jsx
1379
1669
  function readNumber(text, { kind = "number", required = true, tried = false, max, labels, locale }) {
1380
1670
  const value = parseNumber(text, locale);
1381
1671
  if (max !== void 0 && value !== null && Number.isInteger(value) && value > max) {
@@ -1547,6 +1837,7 @@ function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts
1547
1837
  const weekStart = view.formatting?.weekStart;
1548
1838
  const latestDay = isoDay(span.max);
1549
1839
  const [now] = useState3(() => Date.now());
1840
+ const todayIso = todayIn(timeZone, now);
1550
1841
  const datesOf = (spec, at = anchor) => {
1551
1842
  try {
1552
1843
  return relativeDateRange(spec.unit, spec.count ?? 1, { ...spec, anchor: at, timeZone, now, latest: span.max, first: span.min, weekStart });
@@ -1566,7 +1857,7 @@ function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts
1566
1857
  };
1567
1858
  const defaultCount = (unit) => Math.max(2, reach(unit));
1568
1859
  const firstUnit = units.includes("month") ? "month" : units[0];
1569
- const readCount = (text) => readNumber(text, { kind: "count", max: CATALOG3.relativeMaxCount, labels, locale });
1860
+ const readCount = (text) => readNumber(text, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale });
1570
1861
  const rowOf = (d) => quick.id === d ? { text: numberText(quick.count, locale), unit: quick.unit, current: quick.includeCurrent } : { text: numberText(d === "next" ? 1 : defaultCount(firstUnit), locale), unit: firstUnit, current: true };
1571
1862
  const [rows, setRows] = useState3(() => Object.fromEntries(COUNTED.map((d) => [d, rowOf(d)])));
1572
1863
  const [thisUnit, setThisUnit] = useState3(quick.id === "this" ? quick.unit : "year");
@@ -1613,10 +1904,10 @@ function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts
1613
1904
  if (range.from === null) {
1614
1905
  period = fill(more.until, { to: periodText({ from: range.to, to: range.to }, shownUnit, locale) });
1615
1906
  } else {
1616
- const share = rangeShare(range, shownUnit, span, locale);
1907
+ const share = rangeShare(range, shownUnit, span, locale, todayIso);
1617
1908
  if (share?.none) {
1618
1909
  period = "";
1619
- missing = fill(plural(labels.noData, 1, lang), { range: periodText(range, shownUnit, locale) });
1910
+ missing = fill(plural(labels.noData, 1, lang), { range: periodText({ from: range.from, to: share.to ?? range.to }, shownUnit, locale) });
1620
1911
  } else {
1621
1912
  period = share ? `${share.data} ` : periodText(range, shownUnit, locale);
1622
1913
  missing = share ? fill(plural(labels.noData, share.count, lang), { range: share.missing.join(", ") }) : null;
@@ -1693,7 +1984,7 @@ function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts
1693
1984
  change({ unit, ...keep ? {} : { text: numberText(defaultCount(unit), locale) } });
1694
1985
  };
1695
1986
  const current = datesOf({ direction: "this", unit: row.unit });
1696
- const currentEmpty = current?.from ? rowsOf(current) === 0 : false;
1987
+ const currentEmpty = current?.from ? rowsOf(current) === 0 && dayMs(namedUntil({ from: current.from, to: current.to }, span, todayIso)) >= dayMs(current.from) : false;
1697
1988
  return /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-row", key: d }, radio(d, quick.id === d, () => change({}), name, /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, capital(before.trimEnd(), locale)), range !== null), /* @__PURE__ */ React5.createElement(
1698
1989
  NumberField,
1699
1990
  {
@@ -1738,7 +2029,7 @@ function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts
1738
2029
  ), sub(range, row.unit, d), quick.id === d && !rolling ? /* @__PURE__ */ React5.createElement("label", { className: "pk-check pk-quick-current" }, /* @__PURE__ */ React5.createElement("input", { type: "checkbox", name: `${formName}-${d}-current`, checked: row.current, onChange: (e) => change({ current: e.target.checked }), "data-testid": `quick-${d}-current` }), /* @__PURE__ */ React5.createElement("span", null, labels.quickCurrent[row.unit], currentEmpty ? /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-missing" }, ` (${fill(plural(labels.noData, 1, lang), { range: current?.from ? periodText({ from: current.from, to: current.to }, row.unit, locale) : "" })})`) : null)) : null, quick.id === d && d !== "next" && currentEmpty && anchor === "today" ? /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-fix" }, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-btn pk-small-btn", onClick: () => setAnchorTo("latest"), "data-testid": `quick-${d}-from-latest` }, /* @__PURE__ */ React5.createElement(Icon, { name: "date", size: 14 }), /* @__PURE__ */ React5.createElement("span", { className: "pk-btn-text" }, fill(labels.anchorUseLatest, { date: dayText(latestDay, locale) })))) : null);
1739
2030
  };
1740
2031
  main.push(counted("last"));
1741
- const today = new Date(relativeDays({ unit: "day", count: 1 }, timeZone, now)?.from ?? isoDay(now));
2032
+ const today = new Date(todayIso);
1742
2033
  const periodStart = fk.months ? Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1) : Date.UTC(today.getUTCFullYear(), 0, 1);
1743
2034
  const [anchorOutside] = useState3(() => span.max < periodStart || anchor !== "today");
1744
2035
  const anchorKind = ["today", "latest", "first"].includes(anchor) ? anchor : "date";
@@ -1930,7 +2221,7 @@ function ItemRule({ rule, ctx, apply, unset, first }) {
1930
2221
  const read = (text) => fk.item === "number" ? parseNumber(text, locale) : fk.item === "date" ? /^\d{4,}-\d{2}-\d{2}$/.test(text) ? text : null : text === "" ? null : Number(text);
1931
2222
  const entryOf = (x) => {
1932
2223
  if (x.op === "last") {
1933
- const n = readNumber(x.count, { kind: "count", max: CATALOG3.relativeMaxCount, labels, locale }).value;
2224
+ const n = readNumber(x.count, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale }).value;
1934
2225
  return n !== null ? { ...relativeRule(field, { unit: x.unit, count: n, anchor: ranged?.anchor }), ...ranged ? { not: ranged.not, blanks: ranged.blanks } : {} } : null;
1935
2226
  }
1936
2227
  const [a, b] = [read(x.a), read(x.b)];
@@ -1981,7 +2272,7 @@ function ItemRule({ rule, ctx, apply, unset, first }) {
1981
2272
  };
1982
2273
  const label = fk.item === "date" ? labels.ruleDate : labels.ruleValue;
1983
2274
  const lang = { lang: labels.lang, locale };
1984
- const counted = readNumber(s.count, { kind: "count", max: CATALOG3.relativeMaxCount, labels, locale });
2275
+ const counted = readNumber(s.count, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale });
1985
2276
  const many = counted.value ?? 2;
1986
2277
  return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-subject" }, fieldLabel3(field, labels.core)), /* @__PURE__ */ React5.createElement("select", { className: "pk-rule-op", name: `${formName}-op`, value: s.op, onChange: (e) => change({ op: e.target.value }), "aria-label": labels.valueFilterOp, "data-autofocus": first ? "" : void 0, "data-testid": "rule-item-op" }, ops.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, o === "last" ? plural(labels.lastOp, many, lang) : words[o] ?? o))), s.op === "last" ? /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement(
1987
2278
  NumberField,
@@ -2766,7 +3057,7 @@ function FilterMenu({ view, index, field, types, labels, commit, close, onRemove
2766
3057
  }
2767
3058
  function ValueMenu({ view, index, types, labels, commit, close, onRemove, defaultsOf, info, earlier, locale = "en-US" }) {
2768
3059
  const { explain } = React6.useContext(HelpContext);
2769
- const name = valueLabel(view.values[index], labels);
3060
+ const name = valueLabels(view.values, labels)[index];
2770
3061
  const topics = valueTopics({ view, index, types, labels, locale, defaultsOf, earlier });
2771
3062
  return /* @__PURE__ */ React6.createElement(
2772
3063
  LevelMenu,
@@ -2785,9 +3076,104 @@ function ValueMenu({ view, index, types, labels, commit, close, onRemove, defaul
2785
3076
  );
2786
3077
  }
2787
3078
 
3079
+ // src/add-menu.jsx
3080
+ import React7, { useState as useState5 } from "react";
3081
+ var OTHER = { rows: "cols", cols: "rows" };
3082
+ function addEffect(view, zone, name) {
3083
+ const inFilters = filterZoneFields(view).some((f) => same(f, name));
3084
+ if (zone === "values") {
3085
+ return { from: null, already: false };
3086
+ }
3087
+ if (zone === "filters") {
3088
+ return { from: inFilters ? null : axisOf(view, name) ?? null, already: inFilters };
3089
+ }
3090
+ if (view[zone].some((f) => same(f, name))) {
3091
+ return { from: null, already: true };
3092
+ }
3093
+ return { from: view[OTHER[zone]].some((f) => same(f, name)) ? OTHER[zone] : inFilters ? "filters" : null, already: false };
3094
+ }
3095
+ function AddMenu({ zone, view, fields, placed, nameOf, info, labels, close, placeName, onAdd, filterDraft, onAdded, commit, encoded, locale, fullText }) {
3096
+ const [picked, setPicked] = useState5(
3097
+ /** @type {{ field: string, from: string | null } | null} */
3098
+ null
3099
+ );
3100
+ const zoneName = labels.zones[zone];
3101
+ const full = zone === "filters" ? null : fullText(zone, view[zone].length);
3102
+ const name = fill(labels.addTo, { zone: zoneName });
3103
+ const choiceOf = (f) => {
3104
+ const { from, already } = addEffect(view, zone, placeName(f.name, zone));
3105
+ const where = placed.get(f.name.toLowerCase()) ?? [];
3106
+ const second = zone === "values" && where.includes("values");
3107
+ return {
3108
+ id: `add-${f.name}`,
3109
+ testId: `add-pick-${f.name}`,
3110
+ text: nameOf(f.name),
3111
+ icon: TYPE_ICON[f.type] ?? "text",
3112
+ className: `pk-add-type-${f.type}`,
3113
+ tags: where.map((z) => ({ icon: ZONE_ICON[z], text: labels.zones[z] })),
3114
+ note: already ? void 0 : from ? fill(labels.addMoves, { zone: labels.zones[from] }) : second ? labels.addSecond : void 0,
3115
+ disabled: already || Boolean(full),
3116
+ reason: already ? fill(labels.addAlready, { zone: zoneName }) : full ?? void 0,
3117
+ closes: zone !== "filters",
3118
+ open: zone === "filters" ? "filter" : void 0,
3119
+ run: () => {
3120
+ if (zone === "filters") {
3121
+ setPicked({ field: f.name, from });
3122
+ } else {
3123
+ close();
3124
+ onAdded(from, () => onAdd(f.name, zone));
3125
+ }
3126
+ }
3127
+ };
3128
+ };
3129
+ const topicOf = (list) => ({ id: "fields", title: name, kind: (
3130
+ /** @type {const} */
3131
+ "inline"
3132
+ ), groups: [{ choices: list.map(choiceOf) }], note: fields.length ? null : labels.emptyFields, noteId: "add-empty" });
3133
+ const draft = picked ? filterDraft(picked.field) : null;
3134
+ const topics = [
3135
+ topicOf(fields),
3136
+ // the filter of the field picked for Filters: a level of its own, with no row
3137
+ { id: "filter", title: picked ? nameOf(picked.field) : "", kind: (
3138
+ /** @type {const} */
3139
+ "panel"
3140
+ ), hidden: true }
3141
+ ];
3142
+ return /* @__PURE__ */ React7.createElement("div", { className: "pk-add-menu", "data-testid": `add-menu-${zone}` }, /* @__PURE__ */ React7.createElement(
3143
+ LevelMenu,
3144
+ {
3145
+ name,
3146
+ labels,
3147
+ locale,
3148
+ topics,
3149
+ close,
3150
+ onPick: (choice) => choice.run?.(),
3151
+ search: true,
3152
+ searchText: labels.searchFields,
3153
+ filter: (query) => [topicOf(matchingFields(fields, query, info))],
3154
+ head: /* @__PURE__ */ React7.createElement("div", { className: "pk-level-name" }, /* @__PURE__ */ React7.createElement("span", { className: "pk-level-name-text", "data-testid": "menu-head" }, name)),
3155
+ panel: (id, back) => id === "filter" && picked && draft ? /* @__PURE__ */ React7.createElement(
3156
+ FilterBody,
3157
+ {
3158
+ view,
3159
+ base: draft.base,
3160
+ field: draft.field,
3161
+ encoded,
3162
+ locale,
3163
+ labels,
3164
+ commit: (next, note) => onAdded(picked.from, () => commit(next, note)),
3165
+ close,
3166
+ onCancel: () => back(),
3167
+ titled: false
3168
+ }
3169
+ ) : null
3170
+ }
3171
+ ));
3172
+ }
3173
+
2788
3174
  // src/toolbar-panels.jsx
2789
- import React7, { useEffect as useEffect3, useId as useId5, useRef as useRef3, useState as useState5 } from "react";
2790
- import { VIEW_FILE_LIMITS } from "pivotkit-core";
3175
+ import React8, { useEffect as useEffect3, useId as useId5, useRef as useRef3, useState as useState6 } from "react";
3176
+ import { VIEW_FILE_LIMITS, referenceLineRules, swapAxes } from "pivotkit-core";
2791
3177
 
2792
3178
  // src/export-scope.js
2793
3179
  function dataExportOf(exportData, names) {
@@ -2813,6 +3199,12 @@ function dataExportOf(exportData, names) {
2813
3199
  const unknown = wanted.filter((w) => !known.has(w.toLowerCase()));
2814
3200
  return { source: picked.length > 0, columns: picked, unknown };
2815
3201
  }
3202
+ function drillExportOn(scope, { drillDownExport = false } = {}) {
3203
+ if (scope.columns) {
3204
+ return scope.columns.length > 0;
3205
+ }
3206
+ return scope.source || drillDownExport === true;
3207
+ }
2816
3208
  function pickColumns(names, wanted) {
2817
3209
  if (wanted === void 0) {
2818
3210
  return names.map((_n, i) => i);
@@ -2929,9 +3321,21 @@ async function copyText(text, container) {
2929
3321
  before?.focus?.({ preventScroll: true });
2930
3322
  return ok;
2931
3323
  }
3324
+ async function copyImage(blob, env = { clipboard: typeof navigator !== "undefined" ? navigator.clipboard : void 0, ClipboardItem: typeof ClipboardItem !== "undefined" ? ClipboardItem : void 0 }) {
3325
+ const { clipboard, ClipboardItem: Item } = env;
3326
+ if (!clipboard || typeof clipboard.write !== "function" || typeof Item !== "function") {
3327
+ return false;
3328
+ }
3329
+ try {
3330
+ await clipboard.write([new Item({ [blob.type || "image/png"]: blob })]);
3331
+ return true;
3332
+ } catch {
3333
+ return false;
3334
+ }
3335
+ }
2932
3336
 
2933
3337
  // src/version.js
2934
- var VERSION = true ? "0.7.0" : "0.0.0-source";
3338
+ var VERSION = true ? "0.8.0" : "0.0.0-source";
2935
3339
 
2936
3340
  // src/share-actions.js
2937
3341
  var here = () => typeof location !== "undefined" ? location.href : void 0;
@@ -3055,981 +3459,1087 @@ function saveAsTarget(name, entries, can) {
3055
3459
  return old ? { kind: "store", at: old.at, storeSource: old.sourceId ?? null, storeSheet: old.sheet ?? null, replaces: old } : { kind: "store", storeSource: can.sourceId ?? null, storeSheet: can.sheet ?? null, replaces: null };
3056
3460
  }
3057
3461
 
3058
- // src/view-store.js
3059
- import { toViewFile as toViewFile2 } from "pivotkit-core";
3060
- import { parseTemplates } from "pivotkit-core/templates";
3061
- var VIEW_STORE_LIMITS = Object.freeze({ count: 100, text: 5e5 });
3062
- var warnedLarge = false;
3063
- function readAll(raw) {
3064
- if (!raw) {
3065
- return [];
3066
- }
3067
- if (raw.length > VIEW_STORE_LIMITS.text) {
3068
- if (!warnedLarge) {
3069
- warnedLarge = true;
3070
- console.warn(`pivotkit: the browser store of views holds more than ${VIEW_STORE_LIMITS.text} characters; it is not read, and the next save replaces it`);
3071
- }
3072
- return [];
3462
+ // src/export-run.js
3463
+ import { chartThemeFrom, toGrid } from "pivotkit-core";
3464
+
3465
+ // src/print-frame.js
3466
+ var FRAME_CLASS = "pk-print-frame";
3467
+ var listeners = /* @__PURE__ */ new WeakMap();
3468
+ function removeFrame(frame) {
3469
+ listeners.get(frame)?.abort();
3470
+ frame.remove();
3471
+ }
3472
+ var PRINT_LOAD_TIMEOUT = 5e3;
3473
+ function printParts(html, parser) {
3474
+ const styles = [];
3475
+ const text = html.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => (styles.push(css), ""));
3476
+ const parsed = parser.parseFromString(text, "text/html");
3477
+ for (const node of parsed.querySelectorAll("style, script, meta, link, base")) {
3478
+ node.remove();
3073
3479
  }
3074
- return parseTemplates(raw).templates;
3480
+ return { css: styles.join("\n"), lang: parsed.documentElement.getAttribute("lang") ?? "", dir: parsed.documentElement.getAttribute("dir") ?? "", title: parsed.title, body: parsed.body };
3075
3481
  }
3076
- function storedViews(raw, sourceId, shown = { sheet: null, sheets: [] }) {
3077
- return readAll(raw).map((t, at) => {
3078
- const sheet = sheetOfSource(t.source);
3079
- return { name: t.name, view: t.view, at, ...t.source?.id ? { sourceId: t.source.id } : {}, ...sheet ? { sheet } : {} };
3080
- }).filter((t) => listedFor(t, { id: sourceId, ...shown }));
3482
+ var ready = /* @__PURE__ */ new WeakMap();
3483
+ function newSlot(container) {
3484
+ const doc = container.ownerDocument;
3485
+ const frame = doc.createElement("iframe");
3486
+ frame.className = FRAME_CLASS;
3487
+ frame.setAttribute("sandbox", "allow-same-origin allow-modals");
3488
+ frame.setAttribute("aria-hidden", "true");
3489
+ frame.setAttribute("tabindex", "-1");
3490
+ frame.hidden = true;
3491
+ const slot = { frame, isLoaded: false, loaded: Promise.resolve(false) };
3492
+ const loading = new AbortController();
3493
+ listeners.set(frame, loading);
3494
+ slot.loaded = new Promise((resolve) => {
3495
+ const timer = setTimeout(() => resolve(false), PRINT_LOAD_TIMEOUT);
3496
+ loading.signal.addEventListener("abort", () => {
3497
+ clearTimeout(timer);
3498
+ resolve(false);
3499
+ });
3500
+ const done = () => {
3501
+ if (frame.contentDocument?.URL === "about:srcdoc" && frame.contentDocument.readyState === "complete") {
3502
+ frame.hidden = false;
3503
+ slot.isLoaded = true;
3504
+ resolve(true);
3505
+ loading.abort();
3506
+ }
3507
+ };
3508
+ frame.addEventListener("load", done, { signal: loading.signal });
3509
+ });
3510
+ frame.srcdoc = '<!doctype html><html><head><meta charset="utf-8"><title></title></head><body></body></html>';
3511
+ container.append(frame);
3512
+ return slot;
3081
3513
  }
3082
- var sourceOf2 = (id, sheet) => id ? { id, ...sheet ? { params: { sheet } } : {} } : void 0;
3083
- function changedViews(raw, change, message) {
3084
- const all = readAll(raw);
3085
- let next = all;
3086
- if (change.remove !== void 0) {
3087
- if (all[change.remove]?.name !== change.removeName) {
3088
- throw new Error(message("changed", 0));
3089
- }
3090
- next = all.filter((t, i) => i !== change.remove);
3091
- }
3092
- const saving = Boolean(change.name && change.view);
3093
- if (saving && change.replace !== void 0) {
3094
- const old = all[change.replace];
3095
- if (old?.name !== change.name) {
3096
- throw new Error(message("changed", 0));
3097
- }
3098
- const source = old.source?.id && old.source.id === change.sourceId ? sourceOf2(change.sourceId, change.sheet) : old.source;
3099
- next = all.map((t, i) => i === change.replace ? { name: old.name, view: (
3100
- /** @type {Record<string, unknown>} */
3101
- change.view
3102
- ), ...source ? { source } : {} } : t);
3103
- } else if (saving) {
3104
- const id = change.sourceId;
3105
- const sheet = id ? change.sheet ?? null : null;
3106
- next = next.filter((t) => t.name !== change.name || (t.source?.id ?? void 0) !== id || sheetOfSource(t.source) !== sheet);
3107
- const source = sourceOf2(id, sheet);
3108
- next.push({ name: (
3109
- /** @type {string} */
3110
- change.name
3111
- ), view: (
3112
- /** @type {Record<string, unknown>} */
3113
- change.view
3114
- ), ...source ? { source } : {} });
3115
- if (next.length > VIEW_STORE_LIMITS.count) {
3116
- throw new Error(message("count", VIEW_STORE_LIMITS.count));
3117
- }
3118
- }
3119
- const text = next.length ? JSON.stringify(next.map((t) => toViewFile2(t.view, { name: t.name, source: t.source }, { link: true }))) : null;
3120
- if (saving && text && text.length > VIEW_STORE_LIMITS.text) {
3121
- throw new Error(message("text", VIEW_STORE_LIMITS.text));
3514
+ function preparePrintFrame(container) {
3515
+ if (!ready.get(container)?.frame.isConnected) {
3516
+ ready.set(container, newSlot(container));
3122
3517
  }
3123
- return text;
3124
3518
  }
3125
- function storeViews(raw, change, labels, locale, keep) {
3126
- const texts = { count: labels.storeFull, text: labels.storeTooLarge, changed: labels.storeChanged };
3127
- const text = changedViews(raw, change, (kind, max) => fill(texts[kind], { max: max.toLocaleString(locale) }));
3128
- if (!keep(text)) {
3129
- throw new Error(labels.storeRefused);
3519
+ function releasePrintFrame(container) {
3520
+ const slot = ready.get(container);
3521
+ if (slot) {
3522
+ ready.delete(container);
3523
+ removeFrame(slot.frame);
3130
3524
  }
3131
3525
  }
3132
-
3133
- // src/toolbar-panels.jsx
3134
- function ChartTypeOptions({ view, plan, labels, onChart, close }) {
3135
- const current = chartTypeOf(view.chart);
3136
- return CHART_TYPE_NAMES.map((p) => /* @__PURE__ */ React7.createElement(
3137
- Option,
3138
- {
3139
- key: p,
3140
- icon: CHART_TYPES[p].icon,
3141
- checked: view.display === "chart" && current === p,
3142
- hint: p === "auto" && plan ? fill(labels.chartAutoNow, { type: labels.chartTypes[plan.name] }) : void 0,
3143
- onSelect: () => {
3144
- close();
3145
- onChart(p);
3146
- },
3147
- testId: `chart-${p}`
3148
- },
3149
- labels.chartTypes[p]
3150
- ));
3151
- }
3152
- var VALUE_LABELS = { slices: ["auto", "off", "value", "percent", "both"], other: ["auto", "off", "value"] };
3153
- var LABEL_POSITIONS = ["outside", "inside"];
3154
- var LEGENDS = ["auto", "bottom", "right", "off"];
3155
- var AXIS_LABELS = ["auto", "all", "nth"];
3156
- var GROUP_LABELS = ["auto", "on", "off"];
3157
- function ChartTitle({ title, labels, onDisplay }) {
3158
- const [text, setText] = useState5(title ?? "");
3159
- const [last, setLast] = useState5(title);
3160
- if (title !== last) {
3161
- setLast(title);
3162
- setText(title ?? "");
3526
+ function takePrintFrame(container) {
3527
+ const kept = ready.get(container);
3528
+ const slot = kept?.frame.isConnected ? kept : newSlot(container);
3529
+ ready.delete(container);
3530
+ for (const old of container.querySelectorAll(`iframe.${FRAME_CLASS}`)) {
3531
+ if (old !== slot.frame) {
3532
+ removeFrame(
3533
+ /** @type {HTMLIFrameElement} */
3534
+ old
3535
+ );
3536
+ }
3163
3537
  }
3164
- return /* @__PURE__ */ React7.createElement(
3165
- "form",
3166
- {
3167
- className: "pk-inline-form",
3168
- onSubmit: (e) => {
3169
- e.preventDefault();
3170
- onDisplay({ title: text.trim() || null });
3171
- }
3172
- },
3173
- /* @__PURE__ */ React7.createElement(
3174
- ClearInput,
3175
- {
3176
- type: "text",
3177
- value: text,
3178
- onChange: setText,
3179
- onClear: () => title ? onDisplay({ title: null }) : void 0,
3180
- clearLabel: labels.clearText,
3181
- placeholder: labels.chartTitleNone,
3182
- "aria-label": labels.chartTitle,
3183
- maxLength: 200,
3184
- "data-testid": "chart-title"
3185
- }
3186
- ),
3187
- /* @__PURE__ */ React7.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: (text.trim() || null) === (title ?? null) }, labels.apply)
3188
- );
3189
- }
3190
- function Sub({ title, info, children }) {
3191
- const titleId = useId5();
3192
- return /* @__PURE__ */ React7.createElement("div", { className: "pk-subsection", role: title ? "group" : void 0, "aria-labelledby": title ? titleId : void 0 }, title ? /* @__PURE__ */ React7.createElement("div", { className: `pk-subtitle${info ? " pk-setting-row" : ""}` }, /* @__PURE__ */ React7.createElement("span", { id: titleId }, title), info ? /* @__PURE__ */ React7.createElement(SettingInfo, { id: info, name: title }) : null) : null, children);
3193
- }
3194
- function ChartDisplay({ view, plan, labels, onDisplay }) {
3195
- const chart = view.chart;
3196
- const drawn = plan ? plan.name : chartTypeOf(chart);
3197
- const pie = SLICE_TYPES.includes(drawn);
3198
- const axis = CHART_TYPES[drawn].axis;
3199
- const choices = pie ? VALUE_LABELS.slices : VALUE_LABELS.other;
3200
- const valueLabels = !pie && (chart.valueLabels === "percent" || chart.valueLabels === "both") ? "value" : chart.valueLabels;
3201
- return /* @__PURE__ */ React7.createElement(Section, { title: labels.chartDisplay }, /* @__PURE__ */ React7.createElement(Sub, { title: labels.valueLabels }, /* @__PURE__ */ React7.createElement("div", { className: "pk-choice-grid" }, choices.map((v) => /* @__PURE__ */ React7.createElement(Option, { key: v, checked: valueLabels === v, onSelect: () => onDisplay({ valueLabels: v }), testId: `labels-${v}` }, labels.valueLabelNames[v])))), pie ? /* @__PURE__ */ React7.createElement(Sub, { title: labels.labelPosition, info: "labelPosition" }, /* @__PURE__ */ React7.createElement("div", { className: "pk-choice-grid" }, LABEL_POSITIONS.map((v) => /* @__PURE__ */ React7.createElement(Option, { key: v, checked: (chart.labelPosition ?? "outside") === v, disabled: chart.valueLabels === "off", onSelect: () => onDisplay({ labelPosition: v }), testId: `label-position-${v}` }, labels.labelPositionNames[v])))) : null, /* @__PURE__ */ React7.createElement(Sub, { title: labels.legend }, /* @__PURE__ */ React7.createElement("div", { className: "pk-choice-grid" }, LEGENDS.map((v) => /* @__PURE__ */ React7.createElement(Option, { key: v, checked: chart.legend === v, onSelect: () => onDisplay({ legend: v }), testId: `legend-${v}` }, labels.legendNames[v])))), /* @__PURE__ */ React7.createElement(Sub, { title: labels.chartTitle }, /* @__PURE__ */ React7.createElement(ChartTitle, { title: chart.title, labels, onDisplay })), axis ? /* @__PURE__ */ React7.createElement(Sub, { title: labels.axisLabels }, /* @__PURE__ */ React7.createElement("div", { className: "pk-choice-grid" }, AXIS_LABELS.map((v) => /* @__PURE__ */ React7.createElement(Option, { key: v, checked: chart.axisLabels === v, onSelect: () => onDisplay({ axisLabels: v }), testId: `axis-${v}` }, labels.axisLabelNames[v])))) : null, axis && view.rows.length >= 2 ? /* @__PURE__ */ React7.createElement(Sub, { title: labels.groupLabels, info: "groupLabels" }, /* @__PURE__ */ React7.createElement("div", { className: "pk-choice-grid" }, GROUP_LABELS.map((v) => /* @__PURE__ */ React7.createElement(Option, { key: v, checked: chart.groupLabels === v, onSelect: () => onDisplay({ groupLabels: v }), testId: `groups-${v}` }, labels.groupLabelNames[v])))) : null, drawn === "line" || drawn === "area" ? /* @__PURE__ */ React7.createElement(Sub, null, /* @__PURE__ */ React7.createElement(Switch, { checked: chart.smooth, onChange: (on) => onDisplay({ smooth: on }), testId: "chart-smooth" }, labels.smoothLines)) : null);
3202
- }
3203
- function ChartTypePanel({ view, plan, labels, onChart, onDisplay, close }) {
3204
- return /* @__PURE__ */ React7.createElement(React7.Fragment, null, /* @__PURE__ */ React7.createElement(Section, { title: labels.chartType }, /* @__PURE__ */ React7.createElement("div", { className: "pk-choice-grid" }, /* @__PURE__ */ React7.createElement(ChartTypeOptions, { view, plan, labels, onChart, close }))), /* @__PURE__ */ React7.createElement(ChartDisplay, { view, plan, labels, onDisplay }));
3205
- }
3206
- function Shortcuts({ labels, mod }) {
3207
- const key = (k) => k === "Mod" ? mod === "\u2318" ? "\u2318" : labels.keys.Mod : Object.hasOwn(labels.keys, k) ? labels.keys[k] : k;
3208
- return /* @__PURE__ */ React7.createElement("dl", { className: "pk-shortcuts", "data-testid": "shortcuts" }, SHORTCUTS.map((s) => /* @__PURE__ */ React7.createElement("div", { key: s.text, className: "pk-shortcut" }, /* @__PURE__ */ React7.createElement("dt", null, s.keys.map((k, i) => /* @__PURE__ */ React7.createElement(React7.Fragment, { key: k }, i ? " + " : null, /* @__PURE__ */ React7.createElement("kbd", null, key(k))))), /* @__PURE__ */ React7.createElement("dd", null, labels.shortcuts[s.text]))));
3209
- }
3210
- function Switch({ checked, onChange, testId, children }) {
3211
- const name = useFormName();
3212
- return /* @__PURE__ */ React7.createElement("label", { className: "pk-switch" }, /* @__PURE__ */ React7.createElement("input", { type: "checkbox", name, checked, onChange: (e) => onChange(e.target.checked), "data-testid": testId }), /* @__PURE__ */ React7.createElement("span", { className: "pk-switch-track", "aria-hidden": "true" }), /* @__PURE__ */ React7.createElement("span", { className: "pk-switch-text" }, children));
3538
+ return slot;
3213
3539
  }
3214
- function OptionsPanel({ view, labels, onTotal, onExpand, onCollapse, close, tips, mod, folding, help }) {
3215
- const topics = optionTopics({
3216
- view,
3217
- labels,
3218
- folding,
3219
- tips,
3220
- explanations: help?.explanations ?? null,
3221
- act: {
3222
- total: onTotal,
3223
- expand: () => onExpand(labels),
3224
- collapse: () => onCollapse(labels),
3225
- tipsOn: (on) => tips.onOn(on),
3226
- resetTips: () => tips.onReset(),
3227
- explain: (on) => help?.explanations?.set(on)
3540
+ var dropPrintFrame = (slot) => removeFrame(slot.frame);
3541
+ function printHtml(html, slot) {
3542
+ if (slot.isLoaded) {
3543
+ return Promise.resolve(fillAndPrint(html, slot.frame));
3544
+ }
3545
+ return slot.loaded.then((ok) => {
3546
+ if (!ok) {
3547
+ removeFrame(slot.frame);
3228
3548
  }
3549
+ return ok && fillAndPrint(html, slot.frame);
3229
3550
  });
3230
- return /* @__PURE__ */ React7.createElement(LevelMenu, { name: labels.options, labels, topics, close, onPick: runChoice(close), panel: (id) => id === "shortcuts" ? /* @__PURE__ */ React7.createElement(Shortcuts, { labels, mod }) : null });
3231
3551
  }
3232
- var runChoice = (close) => (c) => {
3233
- if (c.closes) {
3234
- close();
3552
+ function fillAndPrint(html, frame) {
3553
+ try {
3554
+ return fillAndPrintIn(html, frame);
3555
+ } catch (error) {
3556
+ removeFrame(frame);
3557
+ throw error;
3235
3558
  }
3236
- c.run?.();
3237
- };
3238
- function Confirm({ question, action, cancel, onYes, onNo, testId, yesId, noId, danger = false, busy = false, focusYes = false }) {
3239
- const no = useRef3(
3240
- /** @type {HTMLButtonElement | null} */
3241
- null
3242
- );
3243
- const yes = useRef3(
3244
- /** @type {HTMLButtonElement | null} */
3245
- null
3246
- );
3247
- useEffect3(() => {
3248
- (focusYes ? yes : no).current?.focus({ preventScroll: true });
3249
- }, [focusYes]);
3250
- return /* @__PURE__ */ React7.createElement("div", { className: "pk-confirm pk-save-confirm", role: "group", "aria-label": question, "data-testid": testId }, /* @__PURE__ */ React7.createElement("span", { className: "pk-confirm-text" }, question), /* @__PURE__ */ React7.createElement("button", { ref: yes, type: "button", className: danger ? "pk-btn pk-danger-btn" : "pk-btn pk-primary", disabled: busy, "data-autofocus": focusYes ? "" : void 0, "data-testid": yesId, onClick: onYes }, action), /* @__PURE__ */ React7.createElement("button", { ref: no, type: "button", className: "pk-btn", disabled: busy, "data-autofocus": focusYes ? void 0 : "", "data-testid": noId, onClick: onNo }, cancel));
3251
3559
  }
3252
- function SaveView({ labels, button, onSave, resolve, close }) {
3253
- const [name, setName] = useState5("");
3254
- const [asking, setAsking] = useState5(
3560
+ function fillAndPrintIn(html, frame) {
3561
+ const win = frame.contentWindow;
3562
+ const fdoc = frame.contentDocument;
3563
+ if (!frame.isConnected) {
3564
+ return true;
3565
+ }
3566
+ if (!win || !fdoc || !fdoc.body) {
3567
+ removeFrame(frame);
3568
+ return false;
3569
+ }
3570
+ const parts = printParts(html, new /** @type {any} */
3571
+ frame.ownerDocument.defaultView.DOMParser());
3572
+ frame.title = parts.title;
3573
+ fdoc.documentElement.lang = parts.lang;
3574
+ fdoc.documentElement.dir = parts.dir;
3575
+ fdoc.title = parts.title;
3576
+ const FrameSheet = (
3255
3577
  /** @type {any} */
3256
- null
3257
- );
3258
- const field = useRef3(
3259
- /** @type {HTMLInputElement | null} */
3260
- null
3578
+ win.CSSStyleSheet
3261
3579
  );
3262
- const asked = useRef3(false);
3263
- useEffect3(() => {
3264
- if (asking) {
3265
- asked.current = true;
3266
- } else if (asked.current) {
3267
- field.current?.focus({ preventScroll: true });
3268
- }
3269
- }, [asking]);
3270
- if (asking) {
3271
- return /* @__PURE__ */ React7.createElement(
3272
- Confirm,
3273
- {
3274
- question: fill(labels.replaceConfirm, { name: asking.name }),
3275
- action: labels.replaceAction,
3276
- cancel: labels.cancel,
3277
- testId: "replace-confirm",
3278
- yesId: "confirm-replace",
3279
- noId: "cancel-replace",
3280
- onYes: () => {
3281
- close();
3282
- onSave(asking.name, asking.target);
3283
- },
3284
- onNo: () => setAsking(null)
3285
- }
3286
- );
3580
+ if (typeof FrameSheet === "function" && "adoptedStyleSheets" in fdoc) {
3581
+ const sheet = new FrameSheet();
3582
+ sheet.replaceSync(parts.css);
3583
+ fdoc.adoptedStyleSheets = [sheet];
3584
+ } else {
3585
+ const style = fdoc.createElement("style");
3586
+ style.textContent = parts.css;
3587
+ fdoc.head.append(style);
3287
3588
  }
3288
- return /* @__PURE__ */ React7.createElement(
3289
- "form",
3290
- {
3291
- className: "pk-inline-form",
3292
- onSubmit: (e) => {
3293
- e.preventDefault();
3294
- const wanted = name.trim();
3295
- const target = wanted ? resolve(wanted) : null;
3296
- if (target?.replaces) {
3297
- setAsking({ name: wanted, target });
3298
- } else if (target) {
3299
- close();
3300
- onSave(wanted, target);
3301
- }
3302
- }
3303
- },
3304
- /* @__PURE__ */ React7.createElement(ClearInput, { type: "text", value: name, onChange: setName, clearLabel: labels.clearText, placeholder: labels.viewName, "aria-label": labels.viewName, maxLength: 120, "data-testid": "saved-view-name", inputRef: field }),
3305
- /* @__PURE__ */ React7.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: !name.trim() }, button)
3306
- );
3589
+ fdoc.body.replaceChildren(...[...parts.body.childNodes].map((node) => fdoc.importNode(node, true)));
3590
+ void fdoc.documentElement.getBoundingClientRect();
3591
+ const view = frame.ownerDocument.defaultView;
3592
+ const ended = new AbortController();
3593
+ listeners.set(frame, ended);
3594
+ const after = () => setTimeout(() => removeFrame(frame), 0);
3595
+ win.addEventListener("afterprint", after, { once: true, signal: ended.signal });
3596
+ view?.addEventListener("afterprint", after, { once: true, signal: ended.signal });
3597
+ win.print();
3598
+ return true;
3307
3599
  }
3308
- function LoadCheck({ check, labels, onCancel, close, title, quiet = false }) {
3309
- const titleId = useId5();
3310
- const first = useRef3(
3311
- /** @type {HTMLButtonElement | null} */
3312
- null
3600
+
3601
+ // src/theme-tokens.js
3602
+ function themeTokens(root, theme, names, more = () => ({})) {
3603
+ const host = (
3604
+ /** @type {{ host?: Element }} */
3605
+ root.getRootNode().host
3313
3606
  );
3314
- useEffect3(() => {
3315
- if (!quiet) {
3316
- first.current?.focus({ preventScroll: true });
3607
+ const other = theme === "light" ? "dark" : "light";
3608
+ const shown = [root, ...host ? [host] : []].filter((el) => el.getAttribute("data-pk-theme") === other);
3609
+ const read = () => {
3610
+ const style = getComputedStyle(root);
3611
+ return { ...Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name).trim()]).filter(([, value]) => value)), ...more() };
3612
+ };
3613
+ if (!shown.length) {
3614
+ return read();
3615
+ }
3616
+ const kept = [root.style.getPropertyValue("--pk-duration"), root.style.getPropertyPriority("--pk-duration")];
3617
+ root.style.setProperty("--pk-duration", "0ms", "important");
3618
+ try {
3619
+ for (const el of shown) {
3620
+ el.setAttribute("data-pk-theme", theme);
3317
3621
  }
3318
- }, [quiet]);
3319
- return /* @__PURE__ */ React7.createElement("div", { className: "pk-load-check", role: "group", "aria-labelledby": titleId, "data-testid": "load-check" }, /* @__PURE__ */ React7.createElement("p", { id: titleId, className: "pk-load-check-title" }, /* @__PURE__ */ React7.createElement(Icon, { name: "info", size: 16 }), /* @__PURE__ */ React7.createElement("span", null, title ?? labels.loadCheckTitle)), /* @__PURE__ */ React7.createElement("ul", { className: "pk-load-check-lines" }, check.lines.map((line, i) => /* @__PURE__ */ React7.createElement("li", { key: i }, line))), /* @__PURE__ */ React7.createElement("div", { className: "pk-load-check-actions" }, check.switchTo ? /* @__PURE__ */ React7.createElement("button", { ref: first, type: "button", className: "pk-btn pk-primary", "data-autofocus": "", "data-testid": "load-switch", onClick: () => {
3320
- close();
3321
- check.switchTo?.run();
3322
- } }, fill(labels.switchAndLoad, { source: check.switchTo.name })) : null, /* @__PURE__ */ React7.createElement("button", { ref: check.switchTo ? void 0 : first, type: "button", className: check.switchTo ? "pk-btn" : "pk-btn pk-primary", "data-autofocus": check.switchTo ? void 0 : "", "data-testid": "load-anyway", onClick: () => {
3323
- close();
3324
- check.load();
3325
- } }, labels.loadAnyway), /* @__PURE__ */ React7.createElement("button", { type: "button", className: "pk-btn", "data-testid": "load-cancel", onClick: onCancel }, labels.cancel)), check.switchTo ? /* @__PURE__ */ React7.createElement("p", { className: "pk-hint" }, labels.switchStartsFresh) : null);
3326
- }
3327
- function LoadView({ labels, onLoadText, close }) {
3328
- const [text, setText] = useState5("");
3329
- const [problem, setProblem] = useState5(
3330
- /** @type {string | null} */
3331
- null
3332
- );
3333
- const [check, setCheck] = useState5(
3334
- /** @type {any} */
3335
- null
3336
- );
3337
- const [busy, setBusy] = useState5(false);
3338
- const file = useRef3(
3339
- /** @type {HTMLInputElement | null} */
3340
- null
3341
- );
3342
- const field = useRef3(
3343
- /** @type {HTMLTextAreaElement | null} */
3344
- null
3345
- );
3346
- const problemId = useId5();
3347
- const fileName = useFormName();
3348
- useEffect3(() => {
3349
- if (!check) {
3350
- field.current?.focus({ preventScroll: true });
3622
+ try {
3623
+ return read();
3624
+ } finally {
3625
+ for (const el of shown) {
3626
+ el.setAttribute("data-pk-theme", other);
3627
+ }
3628
+ getComputedStyle(root).getPropertyValue("--pk-duration");
3351
3629
  }
3352
- }, [check]);
3353
- const load = async (value) => {
3354
- setBusy(true);
3355
- const outcome = await onLoadText(value);
3356
- setBusy(false);
3357
- if (typeof outcome === "string") {
3358
- setProblem(outcome);
3359
- } else if (outcome) {
3360
- setCheck(outcome);
3630
+ } finally {
3631
+ if (kept[0]) {
3632
+ root.style.setProperty("--pk-duration", kept[0], kept[1]);
3361
3633
  } else {
3362
- close();
3634
+ root.style.removeProperty("--pk-duration");
3363
3635
  }
3364
- };
3365
- if (check) {
3366
- return /* @__PURE__ */ React7.createElement(LoadCheck, { check, labels, onCancel: () => setCheck(null), close });
3367
3636
  }
3368
- return /* @__PURE__ */ React7.createElement(
3369
- "form",
3370
- {
3371
- className: "pk-inline-form pk-load-view",
3372
- onSubmit: (e) => {
3373
- e.preventDefault();
3374
- load(text);
3375
- }
3637
+ }
3638
+
3639
+ // src/export-run.js
3640
+ var XLSX_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
3641
+ var exporters = null;
3642
+ var pending = null;
3643
+ function loadExporters() {
3644
+ pending ??= import("pivotkit-core/export").then(
3645
+ (m) => {
3646
+ exporters = m;
3647
+ return m;
3376
3648
  },
3377
- /* @__PURE__ */ React7.createElement("p", { className: "pk-hint" }, labels.loadViewHint),
3378
- /* @__PURE__ */ React7.createElement(
3379
- ClearInput,
3380
- {
3381
- multiline: true,
3382
- value: text,
3383
- onChange: (v) => {
3384
- setText(v);
3385
- setProblem(null);
3386
- },
3387
- clearLabel: labels.clearText,
3388
- "aria-label": labels.loadViewText,
3389
- placeholder: labels.loadViewText,
3390
- rows: 4,
3391
- spellCheck: false,
3392
- "aria-invalid": problem ? true : void 0,
3393
- "aria-describedby": problem ? problemId : void 0,
3394
- "data-testid": "load-view-text",
3395
- inputRef: field
3396
- }
3397
- ),
3398
- problem ? /* @__PURE__ */ React7.createElement("p", { id: problemId, className: "pk-form-problem", role: "alert", "data-testid": "load-view-problem" }, problem) : null,
3399
- /* @__PURE__ */ React7.createElement(
3400
- "input",
3401
- {
3402
- ref: file,
3403
- type: "file",
3404
- name: `${fileName}-file`,
3405
- accept: "application/json,.json",
3406
- className: "pk-sr",
3407
- tabIndex: -1,
3408
- "aria-hidden": "true",
3409
- "aria-label": labels.chooseFile,
3410
- "data-testid": "load-view-file",
3411
- onChange: async (e) => {
3412
- const chosen = e.target.files?.[0];
3413
- e.target.value = "";
3414
- if (chosen) {
3415
- let content;
3416
- try {
3417
- content = chosen.size > VIEW_FILE_LIMITS.text ? null : await chosen.text();
3418
- } catch {
3419
- content = null;
3420
- }
3421
- if (content === null) {
3422
- setProblem(chosen.size > VIEW_FILE_LIMITS.text ? labels.viewFailed.tooLarge : labels.viewFailed.file);
3423
- } else {
3424
- load(content);
3425
- }
3426
- }
3427
- }
3428
- }
3429
- ),
3430
- /* @__PURE__ */ React7.createElement("button", { type: "button", className: "pk-btn", onClick: () => file.current?.click(), disabled: busy, "data-testid": "load-view-choose" }, /* @__PURE__ */ React7.createElement(Icon, { name: "file" }), /* @__PURE__ */ React7.createElement("span", { className: "pk-btn-text" }, labels.chooseFile)),
3431
- /* @__PURE__ */ React7.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: busy || !text.trim(), "data-testid": "load-view-apply" }, labels.load)
3649
+ (error) => {
3650
+ pending = null;
3651
+ throw error;
3652
+ }
3432
3653
  );
3654
+ return pending;
3433
3655
  }
3434
- function viewActions(ctx, labels) {
3435
- const run = (task, done, failed, rejected, name) => Promise.resolve().then(task).then(
3436
- () => {
3437
- ctx.announce(fill(done, { name }));
3438
- return true;
3439
- },
3440
- (e) => {
3441
- ctx.announce(hostFailure(failed, rejected, e), { tone: "error" });
3442
- return false;
3656
+ var reportPending = null;
3657
+ var reportModules = null;
3658
+ function loadReport(loadECharts) {
3659
+ reportPending ??= Promise.all([import("./chunks/report-run-HU4WPOB7.js"), loadECharts()]).then(
3660
+ (modules) => reportModules = modules,
3661
+ (error) => {
3662
+ reportPending = null;
3663
+ throw error;
3443
3664
  }
3444
3665
  );
3445
- const write = (change) => storeViews(ctx.viewsText, change, labels, ctx.locale, ctx.keep);
3446
- const save = (target, name) => {
3447
- const key = ctx.viewKey;
3448
- return run(
3449
- () => target.kind === "publish" ? ctx.onPublish(name, ctx.view, { source: ctx.source }) : target.kind === "host" ? ctx.onSave(name, ctx.view, { scope: "user", source: ctx.source }) : write({ name, view: ctx.view, sourceId: ctx.sourceId, sheet: ctx.sheet, replace: target.at }),
3450
- labels.toastSaved,
3451
- labels.toastSaveFailed,
3452
- labels.toastSaveRejected,
3453
- name
3454
- ).then((ok) => ok && ctx.onSaved({ name, scope: target.kind === "publish" ? "shared" : "user", store: target.kind === "store", storeSource: target.kind === "store" ? target.storeSource : null, storeSheet: target.kind === "store" ? storedSheet(target, ctx) : null }, key));
3455
- };
3456
- return {
3457
- // Save and Save as: where to is view-save.js's (the host's onSaveTemplate wins over the store)
3458
- save,
3459
- remove: ctx.onDelete || ctx.store ? (t) => run(() => t.at !== void 0 ? write({ remove: t.at, removeName: t.name }) : ctx.onDelete(t.name, { scope: t.scope }), labels.toastDeleted, labels.toastDeleteFailed, labels.toastDeleteRejected, t.name) : null,
3460
- // a view of the menu is published with the data it was made for, which is the data shown unless
3461
- // the entry names other data (a view of the browser store kept for another file or sheet)
3462
- publish: ctx.onPublish ? (t) => run(() => ctx.onPublish(t.name, ctx.normalized(t.view), { source: entrySource(t, ctx.source) }), labels.toastPublished, labels.toastPublishFailed, labels.toastPublishRejected, t.name) : null
3463
- };
3666
+ return reportPending;
3464
3667
  }
3465
- var entrySource = (t, shown) => {
3466
- const id = t.sourceId ?? t.sheetOf ?? t.fileSource;
3467
- if (!id) {
3468
- return shown ?? null;
3668
+ var exportersNow = () => exporters;
3669
+ var prepareExporters = () => void loadExporters().catch(() => void 0);
3670
+ function prepareExport(what, root, loadECharts) {
3671
+ if (what === "print") {
3672
+ if (loadECharts) {
3673
+ void loadReport(loadECharts).catch(() => void 0);
3674
+ }
3675
+ return void 0;
3469
3676
  }
3470
- return { id, ...shown?.id === id && shown.name ? { name: shown.name } : {}, ...t.sheet ? { params: { sheet: t.sheet } } : {} };
3471
- };
3472
- var storedSheet = (target, ctx) => target.storeSource && target.storeSource === ctx.sourceId ? ctx.sheet ?? null : target.storeSheet ?? null;
3473
- function ViewsPanel({ templates, labels, onLoad, actions, close, share }) {
3474
- const { save, remove: onDelete, publish: onPublish } = viewActions(actions, labels);
3475
- const can = { host: Boolean(actions.onSave), store: Boolean(actions.store), publish: Boolean(onPublish), sourceId: actions.sourceId, sheet: actions.sheet ?? null };
3476
- const target = saveTarget(actions.loaded, templates, can, actions.empty);
3477
- const store = actions.store && !actions.onSave;
3478
- const [asking, setAsking] = useState5(
3479
- /** @type {{ kind: "delete" | "publish" | "replaceShared", t?: any, focus?: string } | null} */
3480
- null
3481
- );
3482
- const [busy, setBusy] = useState5(false);
3483
- useEffect3(() => {
3484
- share?.prepare?.();
3485
- }, [share]);
3486
- const sharedChange = Boolean(onPublish) || templates.some((t) => t.scope === "shared" && t.deletable);
3487
- const ids = entryIds(templates);
3488
- const group = (scope) => templates.flatMap((t, at) => t.scope === scope ? [at] : []);
3489
- const entry = (at, list) => {
3490
- const t = templates[at];
3491
- const id = ids[at];
3492
- const next = afterDelete(list, list.indexOf(at));
3493
- const ask = (kind, focus) => () => setAsking({ kind, t, focus });
3494
- return {
3495
- id,
3496
- testId: `saved-view-${t.name}`,
3497
- text: t.name,
3498
- // while a workbook's sheet is shown, a view made on a sheet says which (two views of a
3499
- // name can be kept, one per sheet; one of another sheet reads that sheet when opened)
3500
- hint: t.sheet && actions.sheet ? fill(labels.viewSheet, { sheet: t.sheet }) : void 0,
3501
- icon: "bookmark",
3502
- current: isLoadedEntry(t, actions.loaded),
3503
- closes: true,
3504
- run: () => onLoad(t),
3505
- info: t.scope === "shared" && sharedChange && !(onDelete && t.deletable) ? "sharedView" : void 0,
3506
- actions: [
3507
- ...onPublish && t.scope === "user" ? [{ id: `publish:${id}`, testId: `publish-view-${t.name}`, text: t.name, label: fill(labels.publishView, { name: t.name }), icon: "upload", open: "confirm", backTo: `item:${id}`, run: ask("publish", `item:${id}`) }] : [],
3508
- ...onDelete && t.deletable ? [{ id: `delete:${id}`, testId: `delete-view-${t.name}`, text: t.name, label: fill(labels.deleteView, { name: t.name }), icon: "trash", open: "confirm", backTo: `item:${id}`, run: ask("delete", next === void 0 ? void 0 : `item:${ids[next]}`) }] : []
3509
- ]
3510
- };
3677
+ prepareExporters();
3678
+ const container = root.current;
3679
+ if (!container) {
3680
+ return void 0;
3681
+ }
3682
+ preparePrintFrame(container);
3683
+ return () => releasePrintFrame(container);
3684
+ }
3685
+ function deliver(blob, { doc, onExport, ...file }) {
3686
+ if (onExport?.({ ...file, blob }) === false) {
3687
+ return false;
3688
+ }
3689
+ saveBlob(blob, file.fileName, doc);
3690
+ return true;
3691
+ }
3692
+ async function copyOut(text, { type, container, onExport, ...file }) {
3693
+ if (onExport?.({ ...file, blob: new Blob([text], { type }), text }) === false) {
3694
+ return "kept";
3695
+ }
3696
+ return await copyText(text, container) ? "copied" : "blocked";
3697
+ }
3698
+ var isColor = (text) => typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("color", text);
3699
+ function hexColor(text, ctx, supports = isColor) {
3700
+ if (!text || !ctx || !supports(text)) {
3701
+ return null;
3702
+ }
3703
+ ctx.fillStyle = text;
3704
+ const hex = String(ctx.fillStyle).toLowerCase();
3705
+ return /^#[0-9a-f]{6}$/.test(hex) ? hex : null;
3706
+ }
3707
+ var XLSX_TOKENS = Object.freeze(["--pk-scale-low", "--pk-scale-mid", "--pk-scale-high", "--pk-chart-1"]);
3708
+ function xlsxThemeOf(style, toHex) {
3709
+ const { colorScale = [], dataBar = "" } = chartThemeFrom(style);
3710
+ const scale = colorScale.map(toHex);
3711
+ const [low, high, mid] = [scale[0], scale.at(-1), scale.length === 3 ? scale[1] : null];
3712
+ const bar = toHex(dataBar);
3713
+ return {
3714
+ ...low && high ? { colorScale: mid ? [low, mid, high] : [low, high] } : {},
3715
+ ...bar ? { dataBar: bar } : {}
3511
3716
  };
3512
- const shared = group("shared");
3513
- const mine = group("user");
3514
- const thisView = [];
3515
- if (target) {
3516
- thisView.push({
3517
- id: "save-loaded",
3518
- text: fill(labels.saveNamed, { name: actions.loaded.name }),
3519
- icon: "save",
3520
- disabled: target.kind === null,
3521
- reason: target.kind === null ? labels[target.why] : void 0,
3522
- // over a shared view: asked first, everyone sees the change
3523
- ...target.kind === "publish" ? { open: "confirm", run: () => setAsking({ kind: "replaceShared" }) } : { closes: true, run: () => save(target, actions.loaded.name) }
3524
- });
3717
+ }
3718
+ function xlsxTheme(root) {
3719
+ if (!root) {
3720
+ return void 0;
3525
3721
  }
3526
- if (canSaveAs(can)) {
3527
- thisView.push({ id: "save-as", text: actions.loaded ? labels.saveAs : `${labels.saveView}\u2026`, icon: "save", open: "saveAs" });
3722
+ const tokens = themeTokens(root, "light", XLSX_TOKENS);
3723
+ const ctx = root.ownerDocument.createElement("canvas").getContext("2d");
3724
+ return xlsxThemeOf({ getPropertyValue: (name) => tokens[name] ?? "" }, (text) => hexColor(text, ctx));
3725
+ }
3726
+ function reportTokens(root, report, chart, dark) {
3727
+ if (!root) {
3728
+ return {};
3528
3729
  }
3529
- const act = share ? shareActions(share, labels) : null;
3530
- const question = asking?.kind === "replaceShared" ? { text: fill(labels.replaceSharedConfirm, { name: actions.loaded?.name }), action: labels.replaceAction, testId: "replace-shared-confirm", yesId: "confirm-replace-shared", noId: "cancel-replace-shared" } : asking ? { text: fill(asking.kind === "publish" ? labels.publishConfirm : labels.deleteConfirm, { name: asking.t.name }), action: asking.kind === "publish" ? labels.publishAction : labels.deleteAction, testId: `${asking.kind}-confirm`, yesId: `confirm-${asking.kind}`, noId: `cancel-${asking.kind}` } : null;
3531
- const topics = [
3532
- ...thisView.length ? [{ id: "thisView", title: labels.thisView, kind: (
3533
- /** @type {const} */
3534
- "inline"
3535
- ), titled: true, groups: [{ choices: thisView }] }] : [],
3536
- ...shared.length ? [{ id: "sharedViews", title: labels.sharedViews, kind: (
3537
- /** @type {const} */
3538
- "inline"
3539
- ), titled: true, groups: [{ choices: shared.map((at) => entry(at, shared)) }] }] : [],
3540
- ...mine.length || canSaveAs(can) || !shared.length ? [
3541
- {
3542
- id: "myViews",
3543
- title: labels.myViews,
3544
- kind: (
3545
- /** @type {const} */
3546
- "inline"
3547
- ),
3548
- titled: true,
3549
- groups: [{ choices: mine.map((at) => entry(at, mine)) }],
3550
- // empty: one line, with the store's note in short
3551
- note: mine.length ? store ? labels.storeNote : null : store ? labels.noViewsStore : labels.noViews,
3552
- noteId: store ? "store-note" : void 0
3553
- }
3554
- ] : [],
3555
- ...act ? [
3556
- {
3557
- id: "share",
3558
- title: labels.shareThisView,
3559
- kind: (
3560
- /** @type {const} */
3561
- "inline"
3562
- ),
3563
- titled: true,
3564
- groups: [
3565
- {
3566
- choices: [
3567
- ...share.canLink ? [{ id: "copy-link", text: labels.copyLink, icon: "link", closes: true, run: act.copyLink }] : [],
3568
- { id: "copy-json", text: labels.copyJson, icon: "copy", closes: true, run: act.copyJson },
3569
- { id: "download-view", text: labels.downloadView, icon: "download", closes: true, run: act.download },
3570
- { id: "load-view", text: labels.loadView, icon: "upload", open: "load" }
3571
- ]
3730
+ const mix = chart.screenColor(root.ownerDocument, (c) => /^#[\da-f]{6}$/i.test(c));
3731
+ const mixable = (found) => Object.fromEntries(Object.entries(found).map(([name, value]) => [name, MIXED_TOKENS.includes(name) ? mix(value) ?? value : value]));
3732
+ const tokens = mixable(themeTokens(root, "light", report.REPORT_TOKENS, () => chart.tokenLengths(root, [...chart.LENGTH_TOKENS, ...report.REPORT_LENGTHS])));
3733
+ const darkTokens = dark ? mixable(themeTokens(root, "dark", report.REPORT_DARK_TOKENS)) : {};
3734
+ return { ...Object.keys(tokens).length ? { tokens } : {}, ...Object.keys(darkTokens).length ? { darkTokens } : {} };
3735
+ }
3736
+ var MIXED_TOKENS = Object.freeze(["--pk-heat-low", "--pk-heat-high", "--pk-scale-low", "--pk-scale-mid", "--pk-scale-high"]);
3737
+ async function runExport(kind, { fileName, result, encoded, exportData, locale, labels, limits, root, chartRef, announce, onExport, title, source, loadECharts, colorMap }) {
3738
+ labels = menuLabels(labels);
3739
+ const base = safeFileName(fileName);
3740
+ const doc = root.current?.ownerDocument;
3741
+ try {
3742
+ if (kind === "png" || kind === "copy-chart") {
3743
+ const surface = root.current ? getComputedStyle(root.current).getPropertyValue("--pk-surface").trim() : "";
3744
+ const url = chartRef.current?.getDataURL({ type: "png", pixelRatio: 2, backgroundColor: surface || void 0, excludeComponents: ["dataZoom"] });
3745
+ const file2 = `${base}.png`;
3746
+ if (kind === "copy-chart") {
3747
+ if (!url) {
3748
+ announce(labels.toastChartNotDrawn, { tone: "error" });
3749
+ return;
3750
+ }
3751
+ const blob = dataUrlToBlob(url);
3752
+ if (onExport?.({ kind, fileName: file2, blob }) === false) {
3753
+ return;
3754
+ }
3755
+ if (await copyImage(blob)) {
3756
+ announce(labels.toastChartCopied);
3757
+ return;
3758
+ }
3759
+ const download = () => {
3760
+ if (deliver(blob, { kind: "png", fileName: file2, doc, onExport })) {
3761
+ announce(fill(labels.toastExported, { file: file2 }));
3572
3762
  }
3573
- ],
3574
- // what leaves the report with a view: filter values can be values of the data
3575
- note: labels.sharePrivacy,
3576
- noteId: "share-privacy"
3763
+ };
3764
+ announce(labels.toastImageCopyBlocked, { tone: "error", action: { label: labels.downloadPng, run: download } });
3765
+ return;
3577
3766
  }
3578
- ] : [],
3579
- { id: "saveAs", title: labels.saveAs, levelTitle: (actions.loaded ? labels.saveAs : labels.saveView).replace(/…$/, ""), kind: "panel", hidden: true },
3580
- { id: "load", title: labels.loadView, levelTitle: labels.loadView.replace(/…$/, ""), kind: "panel", hidden: true },
3581
- { id: "confirm", title: question?.action ?? "", kind: "panel", hidden: true }
3582
- ];
3583
- const panel = (id, back) => {
3584
- if (id === "saveAs") {
3585
- return /* @__PURE__ */ React7.createElement(SaveView, { labels, button: actions.loaded ? labels.saveAs.replace(/…$/, "") : labels.save, onSave: (name, t) => save(t, name), resolve: (name) => saveAsTarget(name, templates, can), close });
3767
+ if (url && deliver(dataUrlToBlob(url), { kind, fileName: file2, doc, onExport })) {
3768
+ announce(fill(labels.toastExported, { file: file2 }));
3769
+ }
3770
+ return;
3586
3771
  }
3587
- if (id === "load" && act) {
3588
- return /* @__PURE__ */ React7.createElement(LoadView, { labels, onLoadText: act.loadText, close });
3772
+ if (kind === "data-csv" || kind === "data-json") {
3773
+ const data = encoded ?? result?.encoded;
3774
+ if (!data) {
3775
+ return;
3776
+ }
3777
+ const scope = dataExportFor(exportData, data);
3778
+ if (!scope.source) {
3779
+ return;
3780
+ }
3781
+ const m2 = exporters ?? await loadExporters();
3782
+ const csv = kind === "data-csv";
3783
+ const file2 = `${base}-data.${csv ? "csv" : "json"}`;
3784
+ const options = { ...limits ? { limits } : {}, ...scope.columns ? { columns: scope.columns } : {} };
3785
+ const blob = csv ? new Blob(
3786
+ /** @type {BlobPart[]} */
3787
+ m2.dataToCsvParts(data, options),
3788
+ { type: "text/csv;charset=utf-8" }
3789
+ ) : new Blob([m2.dataToJson(data, options)], { type: "application/json" });
3790
+ if (deliver(blob, { kind, fileName: file2, doc, onExport })) {
3791
+ announce(fill(labels.toastExported, { file: file2 }));
3792
+ }
3793
+ return;
3589
3794
  }
3590
- if (id === "confirm" && question && asking) {
3591
- return /* @__PURE__ */ React7.createElement(
3592
- Confirm,
3593
- {
3594
- question: question.text,
3595
- action: question.action,
3596
- cancel: labels.cancel,
3597
- danger: asking.kind === "delete",
3598
- focusYes: asking.kind !== "replaceShared",
3599
- busy,
3600
- testId: question.testId,
3601
- yesId: question.yesId,
3602
- noId: question.noId,
3603
- onNo: () => back(),
3604
- onYes: async () => {
3605
- if (asking.kind === "replaceShared") {
3606
- close();
3607
- save(target, actions.loaded.name);
3608
- return;
3609
- }
3610
- setBusy(true);
3611
- const ok = await (asking.kind === "publish" ? onPublish : onDelete)?.(asking.t);
3612
- setBusy(false);
3613
- if (ok) {
3614
- back(asking.focus);
3615
- }
3795
+ if (!result) {
3796
+ return;
3797
+ }
3798
+ if (kind === "html" || kind === "svg" || kind === "print") {
3799
+ const slot = kind === "print" && root.current ? takePrintFrame(root.current) : null;
3800
+ let printing = false;
3801
+ try {
3802
+ const [report, echarts] = reportModules ?? await loadReport(
3803
+ /** @type {() => Promise<any>} */
3804
+ loadECharts
3805
+ );
3806
+ const chart = chartRef.current;
3807
+ const size = chart ? { width: clampSize(chart.getWidth()), height: clampSize(chart.getHeight()) } : void 0;
3808
+ const rendered = await report.render(result.view, result.encoded, {
3809
+ format: kind === "svg" ? "svg" : "html",
3810
+ echarts,
3811
+ locale,
3812
+ trusted: true,
3813
+ labels: labels.core,
3814
+ ...limits ? { limits } : {},
3815
+ timeZone: result.timeZone,
3816
+ ...title ? { title } : {},
3817
+ ...source ? { source } : {},
3818
+ ...size ? { size } : {},
3819
+ ...reportTokens(root.current, report, echarts, kind === "html"),
3820
+ // the host's fixed colours, as the light chart draws them (a file is light)
3821
+ ...echarts.colorMapFor(colorMap, "light") ? { colorMap: echarts.colorMapFor(colorMap, "light") } : {},
3822
+ chartEmbed: kind === "print" ? "inline" : "image"
3823
+ });
3824
+ const file2 = `${base}.${kind === "svg" ? "svg" : "html"}`;
3825
+ const blob = new Blob([
3826
+ /** @type {BlobPart} */
3827
+ rendered.body
3828
+ ], { type: rendered.mediaType });
3829
+ if (kind !== "print") {
3830
+ if (deliver(blob, { kind, fileName: file2, doc, onExport })) {
3831
+ announce(fill(labels.toastExported, { file: file2 }));
3616
3832
  }
3833
+ return;
3617
3834
  }
3618
- );
3835
+ if (onExport?.({ kind, fileName: file2, blob }) === false) {
3836
+ return;
3837
+ }
3838
+ printing = true;
3839
+ if (!slot || !await printHtml(
3840
+ /** @type {string} */
3841
+ rendered.text,
3842
+ slot
3843
+ )) {
3844
+ announce(labels.toastPrintBlocked, { tone: "error" });
3845
+ }
3846
+ return;
3847
+ } finally {
3848
+ if (slot && !printing) {
3849
+ dropPrintFrame(slot);
3850
+ }
3851
+ }
3619
3852
  }
3620
- return null;
3621
- };
3622
- return /* @__PURE__ */ React7.createElement(LevelMenu, { name: labels.views, labels, topics, close, onPick: runChoice(close), panel, focusAgain: templates.length });
3853
+ const m = exporters ?? await loadExporters();
3854
+ const grid = toGrid(result, { locale, labels: labels.core, limits });
3855
+ if (kind === "copy-table" || kind === "copy-json") {
3856
+ const json = kind === "copy-json";
3857
+ const done = await copyOut(json ? m.toJson(grid) : m.toTsv(grid), { kind, fileName: `${base}.${json ? "json" : "tsv"}`, type: json ? "application/json" : "text/tab-separated-values", container: root.current, onExport });
3858
+ if (done !== "kept") {
3859
+ announce(done === "copied" ? json ? labels.toastDataCopied : labels.toastTableCopied : labels.toastCopyBlocked, done === "copied" ? void 0 : { tone: "error" });
3860
+ }
3861
+ return;
3862
+ }
3863
+ const file = `${base}.${kind}`;
3864
+ const bytes = kind === "xlsx" ? m.toXlsx(grid, { sheetName: base, theme: xlsxTheme(root.current) }) : m.toCsvBytes(grid, { bom: true });
3865
+ if (deliver(new Blob([
3866
+ /** @type {BlobPart} */
3867
+ bytes
3868
+ ], { type: kind === "xlsx" ? XLSX_TYPE : "text/csv;charset=utf-8" }), { kind, fileName: file, doc, onExport })) {
3869
+ announce(fill(labels.toastExported, { file }));
3870
+ }
3871
+ } catch (e) {
3872
+ announce(fill(labels.toastExportFailed, { message: messageOf(e) }), { tone: "error" });
3873
+ }
3623
3874
  }
3624
- function ExportOption({ icon, text, info, onSelect, testId, disabled, reason, onIntent }) {
3625
- const option = /* @__PURE__ */ React7.createElement(Option, { icon, onSelect, disabled, reason, testId }, text);
3626
- return info ? /* @__PURE__ */ React7.createElement("div", { className: "pk-setting-row", onPointerEnter: onIntent, onPointerDown: onIntent, onFocus: onIntent }, option, /* @__PURE__ */ React7.createElement(SettingInfo, { id: (
3627
- /** @type {any} */
3628
- info
3629
- ), name: text })) : option;
3875
+ var clampSize = (px) => Math.max(100, Math.min(8e3, Math.round(Number(px) || 0)));
3876
+
3877
+ // src/view-store.js
3878
+ import { toViewFile as toViewFile2 } from "pivotkit-core";
3879
+ import { parseTemplates } from "pivotkit-core/templates";
3880
+ var VIEW_STORE_LIMITS = Object.freeze({ count: 100, text: 5e5 });
3881
+ var warnedLarge = false;
3882
+ function readAll(raw) {
3883
+ if (!raw) {
3884
+ return [];
3885
+ }
3886
+ if (raw.length > VIEW_STORE_LIMITS.text) {
3887
+ if (!warnedLarge) {
3888
+ warnedLarge = true;
3889
+ console.warn(`pivotkit: the browser store of views holds more than ${VIEW_STORE_LIMITS.text} characters; it is not read, and the next save replaces it`);
3890
+ }
3891
+ return [];
3892
+ }
3893
+ return parseTemplates(raw).templates;
3630
3894
  }
3631
- function ExportPanel({ labels, onExport, chartReady, display, empty = false, dataExport, prepare, close }) {
3632
- const source = dataExport ? dataExportFor(dataExport.exportData, dataExport.encoded).source : false;
3633
- useEffect3(() => prepare("menu"), [prepare]);
3634
- const run = (kind) => () => {
3635
- close();
3636
- onExport(kind);
3637
- };
3638
- const off = empty ? { disabled: true, reason: labels.exportNeedsField } : {};
3639
- return /* @__PURE__ */ React7.createElement(React7.Fragment, null, /* @__PURE__ */ React7.createElement(Section, { title: labels.exportDownload }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportXlsx, info: "exportXlsx", onSelect: run("xlsx"), ...off, testId: "export-xlsx" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportCsv, info: "exportCsv", onSelect: run("csv"), ...off, testId: "export-csv" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportHtml, info: "exportHtml", onSelect: run("html"), ...off, testId: "export-html" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "image", text: labels.exportPng, disabled: empty || !chartReady, reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("png"), testId: "export-png" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "image", text: labels.exportSvg, disabled: empty || display !== "chart", reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("svg"), testId: "export-svg" })), /* @__PURE__ */ React7.createElement(Section, { title: labels.exportPrintGroup }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "print", text: labels.exportPrint, info: "exportPrint", onSelect: run("print"), ...off, testId: "export-print", onIntent: () => prepare("print") })), /* @__PURE__ */ React7.createElement(Section, { title: labels.exportCopy }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "copy", text: labels.copyTable, info: "copyTable", onSelect: run("copy-table"), ...off, testId: "export-copy-table" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "copy", text: labels.copyDataJson, info: "copyDataJson", onSelect: run("copy-json"), ...off, testId: "export-copy-json" })), source ? /* @__PURE__ */ React7.createElement(Section, { title: labels.exportDataGroup }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportDataCsv, info: "exportDataCsv", onSelect: run("data-csv"), testId: "export-data-csv" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportDataJson, info: "exportDataJson", onSelect: run("data-json"), testId: "export-data-json" })) : null);
3895
+ function storedViews(raw, sourceId, shown = { sheet: null, sheets: [] }) {
3896
+ return readAll(raw).map((t, at) => {
3897
+ const sheet = sheetOfSource(t.source);
3898
+ return { name: t.name, view: t.view, at, ...t.source?.id ? { sourceId: t.source.id } : {}, ...sheet ? { sheet } : {} };
3899
+ }).filter((t) => listedFor(t, { id: sourceId, ...shown }));
3640
3900
  }
3641
-
3642
- // src/drill-panel.jsx
3643
- import React8, { useContext as useContext4, useEffect as useEffect4, useId as useId6, useMemo as useMemo4, useRef as useRef4, useState as useState6 } from "react";
3644
-
3645
- // src/export-run.js
3646
- import { chartThemeFrom, toGrid } from "pivotkit-core";
3647
-
3648
- // src/print-frame.js
3649
- var FRAME_CLASS = "pk-print-frame";
3650
- var listeners = /* @__PURE__ */ new WeakMap();
3651
- function removeFrame(frame) {
3652
- listeners.get(frame)?.abort();
3653
- frame.remove();
3901
+ var sourceOf2 = (id, sheet) => id ? { id, ...sheet ? { params: { sheet } } : {} } : void 0;
3902
+ function changedViews(raw, change, message) {
3903
+ const all = readAll(raw);
3904
+ let next = all;
3905
+ if (change.remove !== void 0) {
3906
+ if (all[change.remove]?.name !== change.removeName) {
3907
+ throw new Error(message("changed", 0));
3908
+ }
3909
+ next = all.filter((t, i) => i !== change.remove);
3910
+ }
3911
+ const saving = Boolean(change.name && change.view);
3912
+ if (saving && change.replace !== void 0) {
3913
+ const old = all[change.replace];
3914
+ if (old?.name !== change.name) {
3915
+ throw new Error(message("changed", 0));
3916
+ }
3917
+ const source = old.source?.id && old.source.id === change.sourceId ? sourceOf2(change.sourceId, change.sheet) : old.source;
3918
+ next = all.map((t, i) => i === change.replace ? { name: old.name, view: (
3919
+ /** @type {Record<string, unknown>} */
3920
+ change.view
3921
+ ), ...source ? { source } : {} } : t);
3922
+ } else if (saving) {
3923
+ const id = change.sourceId;
3924
+ const sheet = id ? change.sheet ?? null : null;
3925
+ next = next.filter((t) => t.name !== change.name || (t.source?.id ?? void 0) !== id || sheetOfSource(t.source) !== sheet);
3926
+ const source = sourceOf2(id, sheet);
3927
+ next.push({ name: (
3928
+ /** @type {string} */
3929
+ change.name
3930
+ ), view: (
3931
+ /** @type {Record<string, unknown>} */
3932
+ change.view
3933
+ ), ...source ? { source } : {} });
3934
+ if (next.length > VIEW_STORE_LIMITS.count) {
3935
+ throw new Error(message("count", VIEW_STORE_LIMITS.count));
3936
+ }
3937
+ }
3938
+ const text = next.length ? JSON.stringify(next.map((t) => toViewFile2(t.view, { name: t.name, source: t.source }, { link: true }))) : null;
3939
+ if (saving && text && text.length > VIEW_STORE_LIMITS.text) {
3940
+ throw new Error(message("text", VIEW_STORE_LIMITS.text));
3941
+ }
3942
+ return text;
3654
3943
  }
3655
- var PRINT_LOAD_TIMEOUT = 5e3;
3656
- function printParts(html, parser) {
3657
- const styles = [];
3658
- const text = html.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => (styles.push(css), ""));
3659
- const parsed = parser.parseFromString(text, "text/html");
3660
- for (const node of parsed.querySelectorAll("style, script, meta, link, base")) {
3661
- node.remove();
3944
+ function storeViews(raw, change, labels, locale, keep) {
3945
+ const texts = { count: labels.storeFull, text: labels.storeTooLarge, changed: labels.storeChanged };
3946
+ const text = changedViews(raw, change, (kind, max) => fill(texts[kind], { max: max.toLocaleString(locale) }));
3947
+ if (!keep(text)) {
3948
+ throw new Error(labels.storeRefused);
3662
3949
  }
3663
- return { css: styles.join("\n"), lang: parsed.documentElement.getAttribute("lang") ?? "", dir: parsed.documentElement.getAttribute("dir") ?? "", title: parsed.title, body: parsed.body };
3664
3950
  }
3665
- var ready = /* @__PURE__ */ new WeakMap();
3666
- function newSlot(container) {
3667
- const doc = container.ownerDocument;
3668
- const frame = doc.createElement("iframe");
3669
- frame.className = FRAME_CLASS;
3670
- frame.setAttribute("sandbox", "allow-same-origin allow-modals");
3671
- frame.setAttribute("aria-hidden", "true");
3672
- frame.setAttribute("tabindex", "-1");
3673
- frame.hidden = true;
3674
- const slot = { frame, isLoaded: false, loaded: Promise.resolve(false) };
3675
- const loading = new AbortController();
3676
- listeners.set(frame, loading);
3677
- slot.loaded = new Promise((resolve) => {
3678
- const timer = setTimeout(() => resolve(false), PRINT_LOAD_TIMEOUT);
3679
- loading.signal.addEventListener("abort", () => {
3680
- clearTimeout(timer);
3681
- resolve(false);
3682
- });
3683
- const done = () => {
3684
- if (frame.contentDocument?.URL === "about:srcdoc" && frame.contentDocument.readyState === "complete") {
3685
- frame.hidden = false;
3686
- slot.isLoaded = true;
3687
- resolve(true);
3688
- loading.abort();
3689
- }
3690
- };
3691
- frame.addEventListener("load", done, { signal: loading.signal });
3692
- });
3693
- frame.srcdoc = '<!doctype html><html><head><meta charset="utf-8"><title></title></head><body></body></html>';
3694
- container.append(frame);
3695
- return slot;
3951
+
3952
+ // src/toolbar-panels.jsx
3953
+ function ChartTypeOptions({ view, plan, labels, onChart, close }) {
3954
+ const current = chartTypeOf(view.chart);
3955
+ return CHART_TYPE_NAMES.map((p) => /* @__PURE__ */ React8.createElement(
3956
+ Option,
3957
+ {
3958
+ key: p,
3959
+ icon: CHART_TYPES[p].icon,
3960
+ checked: view.display === "chart" && current === p,
3961
+ hint: p === "auto" && plan ? fill(labels.chartAutoNow, { type: labels.chartTypes[plan.name] }) : void 0,
3962
+ onSelect: () => {
3963
+ close();
3964
+ onChart(p);
3965
+ },
3966
+ testId: `chart-${p}`
3967
+ },
3968
+ labels.chartTypes[p]
3969
+ ));
3696
3970
  }
3697
- function preparePrintFrame(container) {
3698
- if (!ready.get(container)?.frame.isConnected) {
3699
- ready.set(container, newSlot(container));
3971
+ function legendNames(drawn, series) {
3972
+ if (!series || drawn === "heatmap") {
3973
+ return [];
3700
3974
  }
3975
+ return [...new Set(SLICE_TYPES.includes(drawn) ? series.categories : series.series.map((s) => s.name))];
3701
3976
  }
3702
- function releasePrintFrame(container) {
3703
- const slot = ready.get(container);
3704
- if (slot) {
3705
- ready.delete(container);
3706
- removeFrame(slot.frame);
3977
+ function ChartTitle({ title, labels, onDisplay }) {
3978
+ const [text, setText] = useState6(title ?? "");
3979
+ const [last, setLast] = useState6(title);
3980
+ if (title !== last) {
3981
+ setLast(title);
3982
+ setText(title ?? "");
3707
3983
  }
3984
+ return /* @__PURE__ */ React8.createElement(
3985
+ "form",
3986
+ {
3987
+ className: "pk-inline-form",
3988
+ onSubmit: (e) => {
3989
+ e.preventDefault();
3990
+ onDisplay({ title: text.trim() || null });
3991
+ }
3992
+ },
3993
+ /* @__PURE__ */ React8.createElement(
3994
+ ClearInput,
3995
+ {
3996
+ type: "text",
3997
+ value: text,
3998
+ onChange: setText,
3999
+ onClear: () => title ? onDisplay({ title: null }) : void 0,
4000
+ clearLabel: labels.clearText,
4001
+ placeholder: labels.chartTitleNone,
4002
+ "aria-label": labels.chartTitle,
4003
+ maxLength: 200,
4004
+ "data-testid": "chart-title"
4005
+ }
4006
+ ),
4007
+ /* @__PURE__ */ React8.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: (text.trim() || null) === (title ?? null) }, labels.apply)
4008
+ );
3708
4009
  }
3709
- function takePrintFrame(container) {
3710
- const kept = ready.get(container);
3711
- const slot = kept?.frame.isConnected ? kept : newSlot(container);
3712
- ready.delete(container);
3713
- for (const old of container.querySelectorAll(`iframe.${FRAME_CLASS}`)) {
3714
- if (old !== slot.frame) {
3715
- removeFrame(
3716
- /** @type {HTMLIFrameElement} */
3717
- old
3718
- );
4010
+ function colorsDrawn(instance) {
4011
+ const out = /* @__PURE__ */ new Map();
4012
+ const option = instance.getOption?.();
4013
+ const palette = Array.isArray(option?.color) ? option.color : [];
4014
+ const of = (item, i) => item?.itemStyle?.color ?? palette[i % Math.max(1, palette.length)];
4015
+ for (const [i, s] of (option?.series ?? []).entries()) {
4016
+ if (s.type === "pie") {
4017
+ (s.data ?? []).forEach((d, j) => out.set(String(d.name), of(d, j)));
4018
+ } else {
4019
+ out.set(String(s.name), of(s, i));
3719
4020
  }
3720
4021
  }
3721
- return slot;
4022
+ return out;
3722
4023
  }
3723
- var dropPrintFrame = (slot) => removeFrame(slot.frame);
3724
- function printHtml(html, slot) {
3725
- if (slot.isLoaded) {
3726
- return Promise.resolve(fillAndPrint(html, slot.frame));
3727
- }
3728
- return slot.loaded.then((ok) => {
3729
- if (!ok) {
3730
- removeFrame(slot.frame);
4024
+ function TargetField({ target, labels, locale, format, onTarget }) {
4025
+ const [text, setText] = useState6(numberText(target, locale));
4026
+ const [last, setLast] = useState6(target);
4027
+ if (target !== last) {
4028
+ setLast(target);
4029
+ setText(numberText(target, locale));
4030
+ }
4031
+ const value = parseTarget(text, locale, format);
4032
+ const bad = text.trim() !== "" && value === null;
4033
+ const hintId = useId5();
4034
+ const warnId = useId5();
4035
+ const share = /^percent(?!100)/.test(format ?? "");
4036
+ const hint = share ? labels.targetPercent : /^percent100/.test(format ?? "") ? labels.targetPercent100 : null;
4037
+ const typed = text.trim();
4038
+ const high = share && value !== null && value > 1 && !typed.endsWith("%");
4039
+ const shown = (n) => new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 2 }).format(n);
4040
+ const describedBy = [hint ? hintId : "", high ? warnId : ""].filter(Boolean).join(" ") || void 0;
4041
+ return /* @__PURE__ */ React8.createElement(React8.Fragment, null, /* @__PURE__ */ React8.createElement(
4042
+ "form",
4043
+ {
4044
+ className: "pk-inline-form",
4045
+ onSubmit: (e) => {
4046
+ e.preventDefault();
4047
+ if (!bad) {
4048
+ onTarget(value);
4049
+ }
4050
+ }
4051
+ },
4052
+ /* @__PURE__ */ React8.createElement(
4053
+ ClearInput,
4054
+ {
4055
+ type: "text",
4056
+ inputMode: "decimal",
4057
+ value: text,
4058
+ onChange: setText,
4059
+ onClear: () => target !== null ? onTarget(null) : void 0,
4060
+ clearLabel: labels.clearText,
4061
+ placeholder: labels.targetNone,
4062
+ "aria-label": labels.core.referenceLines.target,
4063
+ "aria-invalid": bad || void 0,
4064
+ "aria-describedby": describedBy,
4065
+ "data-testid": "chart-target"
4066
+ }
4067
+ ),
4068
+ /* @__PURE__ */ React8.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: bad || value === target }, labels.apply)
4069
+ ), hint ? /* @__PURE__ */ React8.createElement("p", { id: hintId, className: "pk-hint pk-subtitle", "data-testid": "target-hint" }, hint) : null, high ? /* @__PURE__ */ React8.createElement("p", { id: warnId, className: "pk-hint pk-subtitle", role: "status", "data-testid": "target-warning" }, fill(labels.targetPercentHigh, { typed, shown: shown(
4070
+ /** @type {number} */
4071
+ value
4072
+ ), share: shown(
4073
+ /** @type {number} */
4074
+ value / 100
4075
+ ) })) : null, target !== null ? /* @__PURE__ */ React8.createElement("button", { type: "button", className: "pk-btn", onClick: () => onTarget(null), "data-testid": "target-remove" }, labels.targetRemove) : null);
4076
+ }
4077
+ function ChartSettingsPanel({ view, plan, encoded, lineChecks, labels, locale, onChart, onDisplay, close, series, colors, folding, onExpand, onCollapse }) {
4078
+ const drawn = plan ? plan.name : chartTypeOf(view.chart);
4079
+ const names = legendNames(drawn, series);
4080
+ const lines = view.chart.referenceLines;
4081
+ const plain = plan?.chart && encoded ? referenceLineRules(plan.swap ? swapAxes(view) : view, { ...view.chart, ...plan.chart }, encoded) : { average: true, trend: true, target: true };
4082
+ const rules = lineChecks ?? { ...plain, notes: ["table"] };
4083
+ const [drawnColors, setDrawnColors] = useState6(
4084
+ /** @type {Map<string, string>} */
4085
+ /* @__PURE__ */ new Map()
4086
+ );
4087
+ useEffect3(() => {
4088
+ const instance = colors?.chart?.current;
4089
+ if (!instance) {
4090
+ return void 0;
3731
4091
  }
3732
- return ok && fillAndPrint(html, slot.frame);
4092
+ const ctx = instance.getDom?.()?.ownerDocument?.createElement("canvas").getContext("2d") ?? null;
4093
+ const read = () => setDrawnColors(new Map([...colorsDrawn(instance)].map(([name, c]) => [name, hexColor(String(c), ctx) ?? ""])));
4094
+ read();
4095
+ instance.on("finished", read);
4096
+ return () => instance.off("finished", read);
4097
+ }, [colors?.chart]);
4098
+ const topics = chartTopics({ view, drawn, labels, names, act: { display: onDisplay, expand: () => onExpand(labels), collapse: () => onCollapse(labels) }, lines: { rules, targetText: numberText(lines?.target, locale) }, drawnColors, folding });
4099
+ const head = /* @__PURE__ */ React8.createElement(Section, { title: labels.chartType }, /* @__PURE__ */ React8.createElement("div", { className: "pk-choice-grid", role: "group", "aria-label": fill(labels.chartTypeIs, { type: labels.chartTypes[plan?.auto ? "auto" : drawn] }), "data-testid": "chart-types" }, /* @__PURE__ */ React8.createElement(ChartTypeOptions, { view, plan, labels, onChart, close })));
4100
+ return /* @__PURE__ */ React8.createElement(
4101
+ LevelMenu,
4102
+ {
4103
+ name: labels.chartSettings,
4104
+ labels,
4105
+ topics,
4106
+ close,
4107
+ onPick: runChoice(close),
4108
+ head,
4109
+ panel: (id) => id === "title" ? /* @__PURE__ */ React8.createElement(ChartTitle, { title: view.chart.title, labels, onDisplay }) : id === "linesTarget" ? /* @__PURE__ */ React8.createElement(TargetField, { target: lines?.target ?? null, labels, locale, format: lineChecks?.format, onTarget: (target) => onDisplay({ referenceLines: { ...lines, target } }) }) : null
4110
+ }
4111
+ );
4112
+ }
4113
+ function Shortcuts({ labels, mod }) {
4114
+ const key = (k) => k === "Mod" ? mod === "\u2318" ? "\u2318" : labels.keys.Mod : Object.hasOwn(labels.keys, k) ? labels.keys[k] : k;
4115
+ return /* @__PURE__ */ React8.createElement("dl", { className: "pk-shortcuts", "data-testid": "shortcuts" }, SHORTCUTS.map((s) => /* @__PURE__ */ React8.createElement("div", { key: s.text, className: "pk-shortcut" }, /* @__PURE__ */ React8.createElement("dt", null, s.keys.map((k, i) => /* @__PURE__ */ React8.createElement(React8.Fragment, { key: k }, i ? " + " : null, /* @__PURE__ */ React8.createElement("kbd", null, key(k))))), /* @__PURE__ */ React8.createElement("dd", null, labels.shortcuts[s.text]))));
4116
+ }
4117
+ function TableSettingsPanel({ view, labels, onTotal, onExpand, onCollapse, close, folding }) {
4118
+ const topics = tableTopics({ view, labels, folding, act: { total: onTotal, expand: () => onExpand(labels), collapse: () => onCollapse(labels) } });
4119
+ return /* @__PURE__ */ React8.createElement(LevelMenu, { name: labels.tableSettings, labels, topics, close, onPick: runChoice(close), panel: () => null });
4120
+ }
4121
+ function MorePanel({ labels, tips, mod, help, close, foot }) {
4122
+ const topics = moreTopics({
4123
+ labels,
4124
+ tips,
4125
+ explanations: help?.explanations ?? null,
4126
+ act: { tipsOn: (on) => tips.onOn(on), resetTips: () => tips.onReset(), explain: (on) => help?.explanations?.set(on) }
3733
4127
  });
4128
+ return /* @__PURE__ */ React8.createElement(LevelMenu, { name: labels.more, labels, topics, close, onPick: runChoice(close), foot: foot?.(close), panel: (id) => id === "shortcuts" ? /* @__PURE__ */ React8.createElement(Shortcuts, { labels, mod }) : null });
3734
4129
  }
3735
- function fillAndPrint(html, frame) {
3736
- try {
3737
- return fillAndPrintIn(html, frame);
3738
- } catch (error) {
3739
- removeFrame(frame);
3740
- throw error;
4130
+ var runChoice = (close) => (c) => {
4131
+ if (c.closes) {
4132
+ close();
3741
4133
  }
4134
+ c.run?.();
4135
+ };
4136
+ function Confirm({ question, action, cancel, onYes, onNo, testId, yesId, noId, danger = false, busy = false, focusYes = false }) {
4137
+ const no = useRef3(
4138
+ /** @type {HTMLButtonElement | null} */
4139
+ null
4140
+ );
4141
+ const yes = useRef3(
4142
+ /** @type {HTMLButtonElement | null} */
4143
+ null
4144
+ );
4145
+ useEffect3(() => {
4146
+ (focusYes ? yes : no).current?.focus({ preventScroll: true });
4147
+ }, [focusYes]);
4148
+ return /* @__PURE__ */ React8.createElement("div", { className: "pk-confirm pk-save-confirm", role: "group", "aria-label": question, "data-testid": testId }, /* @__PURE__ */ React8.createElement("span", { className: "pk-confirm-text" }, question), /* @__PURE__ */ React8.createElement("button", { ref: yes, type: "button", className: danger ? "pk-btn pk-danger-btn" : "pk-btn pk-primary", disabled: busy, "data-autofocus": focusYes ? "" : void 0, "data-testid": yesId, onClick: onYes }, action), /* @__PURE__ */ React8.createElement("button", { ref: no, type: "button", className: "pk-btn", disabled: busy, "data-autofocus": focusYes ? void 0 : "", "data-testid": noId, onClick: onNo }, cancel));
3742
4149
  }
3743
- function fillAndPrintIn(html, frame) {
3744
- const win = frame.contentWindow;
3745
- const fdoc = frame.contentDocument;
3746
- if (!frame.isConnected) {
3747
- return true;
3748
- }
3749
- if (!win || !fdoc || !fdoc.body) {
3750
- removeFrame(frame);
3751
- return false;
3752
- }
3753
- const parts = printParts(html, new /** @type {any} */
3754
- frame.ownerDocument.defaultView.DOMParser());
3755
- frame.title = parts.title;
3756
- fdoc.documentElement.lang = parts.lang;
3757
- fdoc.documentElement.dir = parts.dir;
3758
- fdoc.title = parts.title;
3759
- const FrameSheet = (
4150
+ function SaveView({ labels, button, onSave, resolve, close }) {
4151
+ const [name, setName] = useState6("");
4152
+ const [asking, setAsking] = useState6(
3760
4153
  /** @type {any} */
3761
- win.CSSStyleSheet
4154
+ null
3762
4155
  );
3763
- if (typeof FrameSheet === "function" && "adoptedStyleSheets" in fdoc) {
3764
- const sheet = new FrameSheet();
3765
- sheet.replaceSync(parts.css);
3766
- fdoc.adoptedStyleSheets = [sheet];
3767
- } else {
3768
- const style = fdoc.createElement("style");
3769
- style.textContent = parts.css;
3770
- fdoc.head.append(style);
4156
+ const field = useRef3(
4157
+ /** @type {HTMLInputElement | null} */
4158
+ null
4159
+ );
4160
+ const asked = useRef3(false);
4161
+ useEffect3(() => {
4162
+ if (asking) {
4163
+ asked.current = true;
4164
+ } else if (asked.current) {
4165
+ field.current?.focus({ preventScroll: true });
4166
+ }
4167
+ }, [asking]);
4168
+ if (asking) {
4169
+ return /* @__PURE__ */ React8.createElement(
4170
+ Confirm,
4171
+ {
4172
+ question: fill(labels.replaceConfirm, { name: asking.name }),
4173
+ action: labels.replaceAction,
4174
+ cancel: labels.cancel,
4175
+ testId: "replace-confirm",
4176
+ yesId: "confirm-replace",
4177
+ noId: "cancel-replace",
4178
+ onYes: () => {
4179
+ close();
4180
+ onSave(asking.name, asking.target);
4181
+ },
4182
+ onNo: () => setAsking(null)
4183
+ }
4184
+ );
3771
4185
  }
3772
- fdoc.body.replaceChildren(...[...parts.body.childNodes].map((node) => fdoc.importNode(node, true)));
3773
- void fdoc.documentElement.getBoundingClientRect();
3774
- const view = frame.ownerDocument.defaultView;
3775
- const ended = new AbortController();
3776
- listeners.set(frame, ended);
3777
- const after = () => setTimeout(() => removeFrame(frame), 0);
3778
- win.addEventListener("afterprint", after, { once: true, signal: ended.signal });
3779
- view?.addEventListener("afterprint", after, { once: true, signal: ended.signal });
3780
- win.print();
3781
- return true;
4186
+ return /* @__PURE__ */ React8.createElement(
4187
+ "form",
4188
+ {
4189
+ className: "pk-inline-form",
4190
+ onSubmit: (e) => {
4191
+ e.preventDefault();
4192
+ const wanted = name.trim();
4193
+ const target = wanted ? resolve(wanted) : null;
4194
+ if (target?.replaces) {
4195
+ setAsking({ name: wanted, target });
4196
+ } else if (target) {
4197
+ close();
4198
+ onSave(wanted, target);
4199
+ }
4200
+ }
4201
+ },
4202
+ /* @__PURE__ */ React8.createElement(ClearInput, { type: "text", value: name, onChange: setName, clearLabel: labels.clearText, placeholder: labels.viewName, "aria-label": labels.viewName, maxLength: 120, "data-testid": "saved-view-name", inputRef: field }),
4203
+ /* @__PURE__ */ React8.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: !name.trim() }, button)
4204
+ );
3782
4205
  }
3783
-
3784
- // src/theme-tokens.js
3785
- function themeTokens(root, theme, names, more = () => ({})) {
3786
- const host = (
3787
- /** @type {{ host?: Element }} */
3788
- root.getRootNode().host
4206
+ function LoadCheck({ check, labels, onCancel, close, title, quiet = false }) {
4207
+ const titleId = useId5();
4208
+ const first = useRef3(
4209
+ /** @type {HTMLButtonElement | null} */
4210
+ null
3789
4211
  );
3790
- const other = theme === "light" ? "dark" : "light";
3791
- const shown = [root, ...host ? [host] : []].filter((el) => el.getAttribute("data-pk-theme") === other);
3792
- const read = () => {
3793
- const style = getComputedStyle(root);
3794
- return { ...Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name).trim()]).filter(([, value]) => value)), ...more() };
3795
- };
3796
- if (!shown.length) {
3797
- return read();
3798
- }
3799
- const kept = [root.style.getPropertyValue("--pk-duration"), root.style.getPropertyPriority("--pk-duration")];
3800
- root.style.setProperty("--pk-duration", "0ms", "important");
3801
- try {
3802
- for (const el of shown) {
3803
- el.setAttribute("data-pk-theme", theme);
4212
+ useEffect3(() => {
4213
+ if (!quiet) {
4214
+ first.current?.focus({ preventScroll: true });
3804
4215
  }
3805
- try {
3806
- return read();
3807
- } finally {
3808
- for (const el of shown) {
3809
- el.setAttribute("data-pk-theme", other);
3810
- }
3811
- getComputedStyle(root).getPropertyValue("--pk-duration");
4216
+ }, [quiet]);
4217
+ return /* @__PURE__ */ React8.createElement("div", { className: "pk-load-check", role: "group", "aria-labelledby": titleId, "data-testid": "load-check" }, /* @__PURE__ */ React8.createElement("p", { id: titleId, className: "pk-load-check-title" }, /* @__PURE__ */ React8.createElement(Icon, { name: "info", size: 16 }), /* @__PURE__ */ React8.createElement("span", null, title ?? labels.loadCheckTitle)), /* @__PURE__ */ React8.createElement("ul", { className: "pk-load-check-lines" }, check.lines.map((line, i) => /* @__PURE__ */ React8.createElement("li", { key: i }, line))), /* @__PURE__ */ React8.createElement("div", { className: "pk-load-check-actions" }, check.switchTo ? /* @__PURE__ */ React8.createElement("button", { ref: first, type: "button", className: "pk-btn pk-primary", "data-autofocus": "", "data-testid": "load-switch", onClick: () => {
4218
+ close();
4219
+ check.switchTo?.run();
4220
+ } }, fill(labels.switchAndLoad, { source: check.switchTo.name })) : null, /* @__PURE__ */ React8.createElement("button", { ref: check.switchTo ? void 0 : first, type: "button", className: check.switchTo ? "pk-btn" : "pk-btn pk-primary", "data-autofocus": check.switchTo ? void 0 : "", "data-testid": "load-anyway", onClick: () => {
4221
+ close();
4222
+ check.load();
4223
+ } }, labels.loadAnyway), /* @__PURE__ */ React8.createElement("button", { type: "button", className: "pk-btn", "data-testid": "load-cancel", onClick: onCancel }, labels.cancel)), check.switchTo ? /* @__PURE__ */ React8.createElement("p", { className: "pk-hint" }, labels.switchStartsFresh) : null);
4224
+ }
4225
+ function LoadView({ labels, onLoadText, close }) {
4226
+ const [text, setText] = useState6("");
4227
+ const [problem, setProblem] = useState6(
4228
+ /** @type {string | null} */
4229
+ null
4230
+ );
4231
+ const [check, setCheck] = useState6(
4232
+ /** @type {any} */
4233
+ null
4234
+ );
4235
+ const [busy, setBusy] = useState6(false);
4236
+ const file = useRef3(
4237
+ /** @type {HTMLInputElement | null} */
4238
+ null
4239
+ );
4240
+ const field = useRef3(
4241
+ /** @type {HTMLTextAreaElement | null} */
4242
+ null
4243
+ );
4244
+ const problemId = useId5();
4245
+ const fileName = useFormName();
4246
+ useEffect3(() => {
4247
+ if (!check) {
4248
+ field.current?.focus({ preventScroll: true });
3812
4249
  }
3813
- } finally {
3814
- if (kept[0]) {
3815
- root.style.setProperty("--pk-duration", kept[0], kept[1]);
4250
+ }, [check]);
4251
+ const load = async (value) => {
4252
+ setBusy(true);
4253
+ const outcome = await onLoadText(value);
4254
+ setBusy(false);
4255
+ if (typeof outcome === "string") {
4256
+ setProblem(outcome);
4257
+ } else if (outcome) {
4258
+ setCheck(outcome);
3816
4259
  } else {
3817
- root.style.removeProperty("--pk-duration");
4260
+ close();
3818
4261
  }
4262
+ };
4263
+ if (check) {
4264
+ return /* @__PURE__ */ React8.createElement(LoadCheck, { check, labels, onCancel: () => setCheck(null), close });
3819
4265
  }
3820
- }
3821
-
3822
- // src/export-run.js
3823
- var XLSX_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
3824
- var exporters = null;
3825
- var pending = null;
3826
- function loadExporters() {
3827
- pending ??= import("pivotkit-core/export").then(
3828
- (m) => {
3829
- exporters = m;
3830
- return m;
4266
+ return /* @__PURE__ */ React8.createElement(
4267
+ "form",
4268
+ {
4269
+ className: "pk-inline-form pk-load-view",
4270
+ onSubmit: (e) => {
4271
+ e.preventDefault();
4272
+ load(text);
4273
+ }
3831
4274
  },
3832
- (error) => {
3833
- pending = null;
3834
- throw error;
3835
- }
4275
+ /* @__PURE__ */ React8.createElement("p", { className: "pk-hint" }, labels.loadViewHint),
4276
+ /* @__PURE__ */ React8.createElement(
4277
+ ClearInput,
4278
+ {
4279
+ multiline: true,
4280
+ value: text,
4281
+ onChange: (v) => {
4282
+ setText(v);
4283
+ setProblem(null);
4284
+ },
4285
+ clearLabel: labels.clearText,
4286
+ "aria-label": labels.loadViewText,
4287
+ placeholder: labels.loadViewText,
4288
+ rows: 4,
4289
+ spellCheck: false,
4290
+ "aria-invalid": problem ? true : void 0,
4291
+ "aria-describedby": problem ? problemId : void 0,
4292
+ "data-testid": "load-view-text",
4293
+ inputRef: field
4294
+ }
4295
+ ),
4296
+ problem ? /* @__PURE__ */ React8.createElement("p", { id: problemId, className: "pk-form-problem", role: "alert", "data-testid": "load-view-problem" }, problem) : null,
4297
+ /* @__PURE__ */ React8.createElement(
4298
+ "input",
4299
+ {
4300
+ ref: file,
4301
+ type: "file",
4302
+ name: `${fileName}-file`,
4303
+ accept: "application/json,.json",
4304
+ className: "pk-sr",
4305
+ tabIndex: -1,
4306
+ "aria-hidden": "true",
4307
+ "aria-label": labels.chooseFile,
4308
+ "data-testid": "load-view-file",
4309
+ onChange: async (e) => {
4310
+ const chosen = e.target.files?.[0];
4311
+ e.target.value = "";
4312
+ if (chosen) {
4313
+ let content;
4314
+ try {
4315
+ content = chosen.size > VIEW_FILE_LIMITS.text ? null : await chosen.text();
4316
+ } catch {
4317
+ content = null;
4318
+ }
4319
+ if (content === null) {
4320
+ setProblem(chosen.size > VIEW_FILE_LIMITS.text ? labels.viewFailed.tooLarge : labels.viewFailed.file);
4321
+ } else {
4322
+ load(content);
4323
+ }
4324
+ }
4325
+ }
4326
+ }
4327
+ ),
4328
+ /* @__PURE__ */ React8.createElement("button", { type: "button", className: "pk-btn", onClick: () => file.current?.click(), disabled: busy, "data-testid": "load-view-choose" }, /* @__PURE__ */ React8.createElement(Icon, { name: "file" }), /* @__PURE__ */ React8.createElement("span", { className: "pk-btn-text" }, labels.chooseFile)),
4329
+ /* @__PURE__ */ React8.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: busy || !text.trim(), "data-testid": "load-view-apply" }, labels.load)
3836
4330
  );
3837
- return pending;
3838
4331
  }
3839
- var reportPending = null;
3840
- var reportModules = null;
3841
- function loadReport(loadECharts) {
3842
- reportPending ??= Promise.all([import("./chunks/report-run-HU4WPOB7.js"), loadECharts()]).then(
3843
- (modules) => reportModules = modules,
3844
- (error) => {
3845
- reportPending = null;
3846
- throw error;
4332
+ function viewActions(ctx, labels) {
4333
+ const run = (task, done, failed, rejected, name) => Promise.resolve().then(task).then(
4334
+ () => {
4335
+ ctx.announce(fill(done, { name }));
4336
+ return true;
4337
+ },
4338
+ (e) => {
4339
+ ctx.announce(hostFailure(failed, rejected, e), { tone: "error" });
4340
+ return false;
3847
4341
  }
3848
4342
  );
3849
- return reportPending;
3850
- }
3851
- var exportersNow = () => exporters;
3852
- var prepareExporters = () => void loadExporters().catch(() => void 0);
3853
- function prepareExport(what, root, loadECharts) {
3854
- if (what === "print") {
3855
- if (loadECharts) {
3856
- void loadReport(loadECharts).catch(() => void 0);
3857
- }
3858
- return void 0;
3859
- }
3860
- prepareExporters();
3861
- const container = root.current;
3862
- if (!container) {
3863
- return void 0;
3864
- }
3865
- preparePrintFrame(container);
3866
- return () => releasePrintFrame(container);
3867
- }
3868
- function deliver(blob, { doc, onExport, ...file }) {
3869
- if (onExport?.({ ...file, blob }) === false) {
3870
- return false;
3871
- }
3872
- saveBlob(blob, file.fileName, doc);
3873
- return true;
3874
- }
3875
- async function copyOut(text, { type, container, onExport, ...file }) {
3876
- if (onExport?.({ ...file, blob: new Blob([text], { type }), text }) === false) {
3877
- return "kept";
3878
- }
3879
- return await copyText(text, container) ? "copied" : "blocked";
4343
+ const write = (change) => storeViews(ctx.viewsText, change, labels, ctx.locale, ctx.keep);
4344
+ const save = (target, name) => {
4345
+ const key = ctx.viewKey;
4346
+ return run(
4347
+ () => target.kind === "publish" ? ctx.onPublish(name, ctx.view, { source: ctx.source }) : target.kind === "host" ? ctx.onSave(name, ctx.view, { scope: "user", source: ctx.source }) : write({ name, view: ctx.view, sourceId: ctx.sourceId, sheet: ctx.sheet, replace: target.at }),
4348
+ labels.toastSaved,
4349
+ labels.toastSaveFailed,
4350
+ labels.toastSaveRejected,
4351
+ name
4352
+ ).then((ok) => ok && ctx.onSaved({ name, scope: target.kind === "publish" ? "shared" : "user", store: target.kind === "store", storeSource: target.kind === "store" ? target.storeSource : null, storeSheet: target.kind === "store" ? storedSheet(target, ctx) : null }, key));
4353
+ };
4354
+ return {
4355
+ // Save and Save as: where to is view-save.js's (the host's onSaveTemplate wins over the store)
4356
+ save,
4357
+ remove: ctx.onDelete || ctx.store ? (t) => run(() => t.at !== void 0 ? write({ remove: t.at, removeName: t.name }) : ctx.onDelete(t.name, { scope: t.scope }), labels.toastDeleted, labels.toastDeleteFailed, labels.toastDeleteRejected, t.name) : null,
4358
+ // a view of the menu is published with the data it was made for, which is the data shown unless
4359
+ // the entry names other data (a view of the browser store kept for another file or sheet)
4360
+ publish: ctx.onPublish ? (t) => run(() => ctx.onPublish(t.name, ctx.normalized(t.view), { source: entrySource(t, ctx.source) }), labels.toastPublished, labels.toastPublishFailed, labels.toastPublishRejected, t.name) : null
4361
+ };
3880
4362
  }
3881
- var isColor = (text) => typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("color", text);
3882
- function hexColor(text, ctx, supports = isColor) {
3883
- if (!text || !ctx || !supports(text)) {
3884
- return null;
4363
+ var entrySource = (t, shown) => {
4364
+ const id = t.sourceId ?? t.sheetOf ?? t.fileSource;
4365
+ if (!id) {
4366
+ return shown ?? null;
3885
4367
  }
3886
- ctx.fillStyle = text;
3887
- const hex = String(ctx.fillStyle).toLowerCase();
3888
- return /^#[0-9a-f]{6}$/.test(hex) ? hex : null;
3889
- }
3890
- var XLSX_TOKENS = Object.freeze(["--pk-scale-low", "--pk-scale-mid", "--pk-scale-high", "--pk-chart-1"]);
3891
- function xlsxThemeOf(style, toHex) {
3892
- const { colorScale = [], dataBar = "" } = chartThemeFrom(style);
3893
- const scale = colorScale.map(toHex);
3894
- const [low, high, mid] = [scale[0], scale.at(-1), scale.length === 3 ? scale[1] : null];
3895
- const bar = toHex(dataBar);
3896
- return {
3897
- ...low && high ? { colorScale: mid ? [low, mid, high] : [low, high] } : {},
3898
- ...bar ? { dataBar: bar } : {}
4368
+ return { id, ...shown?.id === id && shown.name ? { name: shown.name } : {}, ...t.sheet ? { params: { sheet: t.sheet } } : {} };
4369
+ };
4370
+ var storedSheet = (target, ctx) => target.storeSource && target.storeSource === ctx.sourceId ? ctx.sheet ?? null : target.storeSheet ?? null;
4371
+ function ViewsPanel({ templates, labels, onLoad, actions, close, share }) {
4372
+ const { save, remove: onDelete, publish: onPublish } = viewActions(actions, labels);
4373
+ const can = { host: Boolean(actions.onSave), store: Boolean(actions.store), publish: Boolean(onPublish), sourceId: actions.sourceId, sheet: actions.sheet ?? null };
4374
+ const target = saveTarget(actions.loaded, templates, can, actions.empty);
4375
+ const store = actions.store && !actions.onSave;
4376
+ const [asking, setAsking] = useState6(
4377
+ /** @type {{ kind: "delete" | "publish" | "replaceShared", t?: any, focus?: string } | null} */
4378
+ null
4379
+ );
4380
+ const [busy, setBusy] = useState6(false);
4381
+ useEffect3(() => {
4382
+ share?.prepare?.();
4383
+ }, [share]);
4384
+ const sharedChange = Boolean(onPublish) || templates.some((t) => t.scope === "shared" && t.deletable);
4385
+ const ids = entryIds(templates);
4386
+ const group = (scope) => templates.flatMap((t, at) => t.scope === scope ? [at] : []);
4387
+ const entry = (at, list) => {
4388
+ const t = templates[at];
4389
+ const id = ids[at];
4390
+ const next = afterDelete(list, list.indexOf(at));
4391
+ const ask = (kind, focus) => () => setAsking({ kind, t, focus });
4392
+ return {
4393
+ id,
4394
+ testId: `saved-view-${t.name}`,
4395
+ text: t.name,
4396
+ // while a workbook's sheet is shown, a view made on a sheet says which (two views of a
4397
+ // name can be kept, one per sheet; one of another sheet reads that sheet when opened)
4398
+ hint: t.sheet && actions.sheet ? fill(labels.viewSheet, { sheet: t.sheet }) : void 0,
4399
+ icon: "bookmark",
4400
+ current: isLoadedEntry(t, actions.loaded),
4401
+ closes: true,
4402
+ run: () => onLoad(t),
4403
+ info: t.scope === "shared" && sharedChange && !(onDelete && t.deletable) ? "sharedView" : void 0,
4404
+ actions: [
4405
+ ...onPublish && t.scope === "user" ? [{ id: `publish:${id}`, testId: `publish-view-${t.name}`, text: t.name, label: fill(labels.publishView, { name: t.name }), icon: "upload", open: "confirm", backTo: `item:${id}`, run: ask("publish", `item:${id}`) }] : [],
4406
+ ...onDelete && t.deletable ? [{ id: `delete:${id}`, testId: `delete-view-${t.name}`, text: t.name, label: fill(labels.deleteView, { name: t.name }), icon: "trash", open: "confirm", backTo: `item:${id}`, run: ask("delete", next === void 0 ? void 0 : `item:${ids[next]}`) }] : []
4407
+ ]
4408
+ };
3899
4409
  };
3900
- }
3901
- function xlsxTheme(root) {
3902
- if (!root) {
3903
- return void 0;
4410
+ const shared = group("shared");
4411
+ const mine = group("user");
4412
+ const thisView = [];
4413
+ if (target) {
4414
+ thisView.push({
4415
+ id: "save-loaded",
4416
+ text: fill(labels.saveNamed, { name: actions.loaded.name }),
4417
+ icon: "save",
4418
+ disabled: target.kind === null,
4419
+ reason: target.kind === null ? labels[target.why] : void 0,
4420
+ // over a shared view: asked first, everyone sees the change
4421
+ ...target.kind === "publish" ? { open: "confirm", run: () => setAsking({ kind: "replaceShared" }) } : { closes: true, run: () => save(target, actions.loaded.name) }
4422
+ });
3904
4423
  }
3905
- const tokens = themeTokens(root, "light", XLSX_TOKENS);
3906
- const ctx = root.ownerDocument.createElement("canvas").getContext("2d");
3907
- return xlsxThemeOf({ getPropertyValue: (name) => tokens[name] ?? "" }, (text) => hexColor(text, ctx));
3908
- }
3909
- function reportTokens(root, report, chart, dark) {
3910
- if (!root) {
3911
- return {};
4424
+ if (canSaveAs(can)) {
4425
+ thisView.push({ id: "save-as", text: actions.loaded ? labels.saveAs : `${labels.saveView}\u2026`, icon: "save", open: "saveAs" });
3912
4426
  }
3913
- const tokens = themeTokens(root, "light", report.REPORT_TOKENS, () => chart.tokenLengths(root, [...chart.LENGTH_TOKENS, ...report.REPORT_LENGTHS]));
3914
- const darkTokens = dark ? themeTokens(root, "dark", report.REPORT_DARK_TOKENS) : {};
3915
- return { ...Object.keys(tokens).length ? { tokens } : {}, ...Object.keys(darkTokens).length ? { darkTokens } : {} };
3916
- }
3917
- async function runExport(kind, { fileName, result, encoded, exportData, locale, labels, limits, root, chartRef, announce, onExport, title, source, loadECharts }) {
3918
- labels = menuLabels(labels);
3919
- const base = safeFileName(fileName);
3920
- const doc = root.current?.ownerDocument;
3921
- try {
3922
- if (kind === "png") {
3923
- const surface = root.current ? getComputedStyle(root.current).getPropertyValue("--pk-surface").trim() : "";
3924
- const url = chartRef.current?.getDataURL({ type: "png", pixelRatio: 2, backgroundColor: surface || void 0 });
3925
- const file2 = `${base}.png`;
3926
- if (url && deliver(dataUrlToBlob(url), { kind, fileName: file2, doc, onExport })) {
3927
- announce(fill(labels.toastExported, { file: file2 }));
3928
- }
3929
- return;
3930
- }
3931
- if (kind === "data-csv" || kind === "data-json") {
3932
- const data = encoded ?? result?.encoded;
3933
- if (!data) {
3934
- return;
3935
- }
3936
- const scope = dataExportFor(exportData, data);
3937
- if (!scope.source) {
3938
- return;
4427
+ const act = share ? shareActions(share, labels) : null;
4428
+ const question = asking?.kind === "replaceShared" ? { text: fill(labels.replaceSharedConfirm, { name: actions.loaded?.name }), action: labels.replaceAction, testId: "replace-shared-confirm", yesId: "confirm-replace-shared", noId: "cancel-replace-shared" } : asking ? { text: fill(asking.kind === "publish" ? labels.publishConfirm : labels.deleteConfirm, { name: asking.t.name }), action: asking.kind === "publish" ? labels.publishAction : labels.deleteAction, testId: `${asking.kind}-confirm`, yesId: `confirm-${asking.kind}`, noId: `cancel-${asking.kind}` } : null;
4429
+ const topics = [
4430
+ ...thisView.length ? [{ id: "thisView", title: labels.thisView, kind: (
4431
+ /** @type {const} */
4432
+ "inline"
4433
+ ), titled: true, groups: [{ choices: thisView }] }] : [],
4434
+ ...shared.length ? [{ id: "sharedViews", title: labels.sharedViews, kind: (
4435
+ /** @type {const} */
4436
+ "inline"
4437
+ ), titled: true, groups: [{ choices: shared.map((at) => entry(at, shared)) }] }] : [],
4438
+ ...mine.length || canSaveAs(can) || !shared.length ? [
4439
+ {
4440
+ id: "myViews",
4441
+ title: labels.myViews,
4442
+ kind: (
4443
+ /** @type {const} */
4444
+ "inline"
4445
+ ),
4446
+ titled: true,
4447
+ groups: [{ choices: mine.map((at) => entry(at, mine)) }],
4448
+ // empty: one line, with the store's note in short
4449
+ note: mine.length ? store ? labels.storeNote : null : store ? labels.noViewsStore : labels.noViews,
4450
+ noteId: store ? "store-note" : void 0
3939
4451
  }
3940
- const m2 = exporters ?? await loadExporters();
3941
- const csv = kind === "data-csv";
3942
- const file2 = `${base}-data.${csv ? "csv" : "json"}`;
3943
- const options = { ...limits ? { limits } : {}, ...scope.columns ? { columns: scope.columns } : {} };
3944
- const blob = csv ? new Blob(
3945
- /** @type {BlobPart[]} */
3946
- m2.dataToCsvParts(data, options),
3947
- { type: "text/csv;charset=utf-8" }
3948
- ) : new Blob([m2.dataToJson(data, options)], { type: "application/json" });
3949
- if (deliver(blob, { kind, fileName: file2, doc, onExport })) {
3950
- announce(fill(labels.toastExported, { file: file2 }));
4452
+ ] : [],
4453
+ ...act ? [
4454
+ {
4455
+ id: "share",
4456
+ title: labels.shareThisView,
4457
+ kind: (
4458
+ /** @type {const} */
4459
+ "inline"
4460
+ ),
4461
+ titled: true,
4462
+ groups: [
4463
+ {
4464
+ choices: [
4465
+ ...share.canLink ? [{ id: "copy-link", text: labels.copyLink, icon: "link", closes: true, run: act.copyLink }] : [],
4466
+ { id: "copy-json", text: labels.copyJson, icon: "copy", closes: true, run: act.copyJson },
4467
+ { id: "download-view", text: labels.downloadView, icon: "download", closes: true, run: act.download },
4468
+ { id: "load-view", text: labels.loadView, icon: "upload", open: "load" }
4469
+ ]
4470
+ }
4471
+ ],
4472
+ // what leaves the report with a view: filter values can be values of the data
4473
+ note: labels.sharePrivacy,
4474
+ noteId: "share-privacy"
3951
4475
  }
3952
- return;
4476
+ ] : [],
4477
+ { id: "saveAs", title: labels.saveAs, levelTitle: (actions.loaded ? labels.saveAs : labels.saveView).replace(/…$/, ""), kind: "panel", hidden: true },
4478
+ { id: "load", title: labels.loadView, levelTitle: labels.loadView.replace(/…$/, ""), kind: "panel", hidden: true },
4479
+ { id: "confirm", title: question?.action ?? "", kind: "panel", hidden: true }
4480
+ ];
4481
+ const panel = (id, back) => {
4482
+ if (id === "saveAs") {
4483
+ return /* @__PURE__ */ React8.createElement(SaveView, { labels, button: actions.loaded ? labels.saveAs.replace(/…$/, "") : labels.save, onSave: (name, t) => save(t, name), resolve: (name) => saveAsTarget(name, templates, can), close });
3953
4484
  }
3954
- if (!result) {
3955
- return;
4485
+ if (id === "load" && act) {
4486
+ return /* @__PURE__ */ React8.createElement(LoadView, { labels, onLoadText: act.loadText, close });
3956
4487
  }
3957
- if (kind === "html" || kind === "svg" || kind === "print") {
3958
- const slot = kind === "print" && root.current ? takePrintFrame(root.current) : null;
3959
- let printing = false;
3960
- try {
3961
- const [report, echarts] = reportModules ?? await loadReport(
3962
- /** @type {() => Promise<any>} */
3963
- loadECharts
3964
- );
3965
- const chart = chartRef.current;
3966
- const size = chart ? { width: clampSize(chart.getWidth()), height: clampSize(chart.getHeight()) } : void 0;
3967
- const rendered = await report.render(result.view, result.encoded, {
3968
- format: kind === "svg" ? "svg" : "html",
3969
- echarts,
3970
- locale,
3971
- trusted: true,
3972
- labels: labels.core,
3973
- ...limits ? { limits } : {},
3974
- timeZone: result.timeZone,
3975
- ...title ? { title } : {},
3976
- ...source ? { source } : {},
3977
- ...size ? { size } : {},
3978
- ...reportTokens(root.current, report, echarts, kind === "html"),
3979
- chartEmbed: kind === "print" ? "inline" : "image"
3980
- });
3981
- const file2 = `${base}.${kind === "svg" ? "svg" : "html"}`;
3982
- const blob = new Blob([
3983
- /** @type {BlobPart} */
3984
- rendered.body
3985
- ], { type: rendered.mediaType });
3986
- if (kind !== "print") {
3987
- if (deliver(blob, { kind, fileName: file2, doc, onExport })) {
3988
- announce(fill(labels.toastExported, { file: file2 }));
4488
+ if (id === "confirm" && question && asking) {
4489
+ return /* @__PURE__ */ React8.createElement(
4490
+ Confirm,
4491
+ {
4492
+ question: question.text,
4493
+ action: question.action,
4494
+ cancel: labels.cancel,
4495
+ danger: asking.kind === "delete",
4496
+ focusYes: asking.kind !== "replaceShared",
4497
+ busy,
4498
+ testId: question.testId,
4499
+ yesId: question.yesId,
4500
+ noId: question.noId,
4501
+ onNo: () => back(),
4502
+ onYes: async () => {
4503
+ if (asking.kind === "replaceShared") {
4504
+ close();
4505
+ save(target, actions.loaded.name);
4506
+ return;
4507
+ }
4508
+ setBusy(true);
4509
+ const ok = await (asking.kind === "publish" ? onPublish : onDelete)?.(asking.t);
4510
+ setBusy(false);
4511
+ if (ok) {
4512
+ back(asking.focus);
4513
+ }
3989
4514
  }
3990
- return;
3991
- }
3992
- if (onExport?.({ kind, fileName: file2, blob }) === false) {
3993
- return;
3994
- }
3995
- printing = true;
3996
- if (!slot || !await printHtml(
3997
- /** @type {string} */
3998
- rendered.text,
3999
- slot
4000
- )) {
4001
- announce(labels.toastPrintBlocked, { tone: "error" });
4002
- }
4003
- return;
4004
- } finally {
4005
- if (slot && !printing) {
4006
- dropPrintFrame(slot);
4007
4515
  }
4008
- }
4009
- }
4010
- const m = exporters ?? await loadExporters();
4011
- const grid = toGrid(result, { locale, labels: labels.core, limits });
4012
- if (kind === "copy-table" || kind === "copy-json") {
4013
- const json = kind === "copy-json";
4014
- const done = await copyOut(json ? m.toJson(grid) : m.toTsv(grid), { kind, fileName: `${base}.${json ? "json" : "tsv"}`, type: json ? "application/json" : "text/tab-separated-values", container: root.current, onExport });
4015
- if (done !== "kept") {
4016
- announce(done === "copied" ? json ? labels.toastDataCopied : labels.toastTableCopied : labels.toastCopyBlocked, done === "copied" ? void 0 : { tone: "error" });
4017
- }
4018
- return;
4019
- }
4020
- const file = `${base}.${kind}`;
4021
- const bytes = kind === "xlsx" ? m.toXlsx(grid, { sheetName: base, theme: xlsxTheme(root.current) }) : m.toCsvBytes(grid, { bom: true });
4022
- if (deliver(new Blob([
4023
- /** @type {BlobPart} */
4024
- bytes
4025
- ], { type: kind === "xlsx" ? XLSX_TYPE : "text/csv;charset=utf-8" }), { kind, fileName: file, doc, onExport })) {
4026
- announce(fill(labels.toastExported, { file }));
4516
+ );
4027
4517
  }
4028
- } catch (e) {
4029
- announce(fill(labels.toastExportFailed, { message: messageOf(e) }), { tone: "error" });
4030
- }
4518
+ return null;
4519
+ };
4520
+ return /* @__PURE__ */ React8.createElement(LevelMenu, { name: labels.views, labels, topics, close, onPick: runChoice(close), panel, focusAgain: templates.length });
4031
4521
  }
4032
- var clampSize = (px) => Math.max(100, Math.min(8e3, Math.round(Number(px) || 0)));
4522
+ function ExportOption({ icon, text, info, onSelect, testId, disabled, reason, onIntent }) {
4523
+ const option = /* @__PURE__ */ React8.createElement(Option, { icon, onSelect, disabled, reason, testId }, text);
4524
+ return info ? /* @__PURE__ */ React8.createElement("div", { className: "pk-setting-row", onPointerEnter: onIntent, onPointerDown: onIntent, onFocus: onIntent }, option, /* @__PURE__ */ React8.createElement(SettingInfo, { id: (
4525
+ /** @type {any} */
4526
+ info
4527
+ ), name: text })) : option;
4528
+ }
4529
+ function ExportPanel({ labels, onExport, chartReady, display, empty = false, dataExport, prepare, close }) {
4530
+ const source = dataExport ? dataExportFor(dataExport.exportData, dataExport.encoded).source : false;
4531
+ useEffect3(() => prepare("menu"), [prepare]);
4532
+ const run = (kind) => () => {
4533
+ close();
4534
+ onExport(kind);
4535
+ };
4536
+ const off = empty ? { disabled: true, reason: labels.exportNeedsField } : {};
4537
+ const noRows = (dataExport?.encoded?.length ?? 0) === 0 ? { disabled: true, reason: labels.exportNeedsRows } : {};
4538
+ return /* @__PURE__ */ React8.createElement(React8.Fragment, null, /* @__PURE__ */ React8.createElement(Section, { title: labels.exportDownload }, /* @__PURE__ */ React8.createElement(ExportOption, { icon: "file", text: labels.exportXlsx, info: "exportXlsx", onSelect: run("xlsx"), ...off, testId: "export-xlsx" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "file", text: labels.exportCsv, info: "exportCsv", onSelect: run("csv"), ...off, testId: "export-csv" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "file", text: labels.exportHtml, info: "exportHtml", onSelect: run("html"), ...off, testId: "export-html" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "image", text: labels.exportPng, disabled: empty || !chartReady, reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("png"), testId: "export-png" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "image", text: labels.exportSvg, disabled: empty || display !== "chart", reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("svg"), testId: "export-svg" })), /* @__PURE__ */ React8.createElement(Section, { title: labels.exportPrintGroup }, /* @__PURE__ */ React8.createElement(ExportOption, { icon: "print", text: labels.exportPrint, info: "exportPrint", onSelect: run("print"), ...off, testId: "export-print", onIntent: () => prepare("print") })), /* @__PURE__ */ React8.createElement(Section, { title: labels.exportCopy }, /* @__PURE__ */ React8.createElement(ExportOption, { icon: "copy", text: labels.copyTable, info: "copyTable", onSelect: run("copy-table"), ...off, testId: "export-copy-table" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "copy", text: labels.copyDataJson, info: "copyDataJson", onSelect: run("copy-json"), ...off, testId: "export-copy-json" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "image", text: labels.copyChart, disabled: empty || !chartReady, reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("copy-chart"), testId: "export-copy-chart" })), source ? /* @__PURE__ */ React8.createElement(Section, { title: labels.exportDataGroup }, /* @__PURE__ */ React8.createElement(ExportOption, { icon: "file", text: labels.exportDataCsv, info: "exportDataCsv", onSelect: run("data-csv"), ...noRows, testId: "export-data-csv" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "file", text: labels.exportDataJson, info: "exportDataJson", onSelect: run("data-json"), ...noRows, testId: "export-data-json" })) : null);
4539
+ }
4540
+
4541
+ // src/drill-panel.jsx
4542
+ import React9, { useContext as useContext4, useEffect as useEffect4, useId as useId6, useMemo as useMemo4, useRef as useRef4, useState as useState7 } from "react";
4033
4543
 
4034
4544
  // src/drill-export.js
4035
4545
  function pick(row, columns) {
@@ -4135,15 +4645,17 @@ function drillOf({ result, rowPath, colPath, count, indices, formatOf, nameOf, i
4135
4645
 
4136
4646
  // src/drill-panel.jsx
4137
4647
  function DrillPanel({ drill: source, onClose, labels, locale, exportContext: context }) {
4138
- const columns = context ? dataExportFor(context.exportData, context.encoded).columns : void 0;
4139
- const exportContext = context && columns?.length !== 0 ? context : void 0;
4648
+ const scope = context ? dataExportFor(context.exportData, context.encoded) : void 0;
4649
+ const columns = scope?.columns;
4650
+ const exportContext = context && scope && drillExportOn(scope, { drillDownExport: context.drillDownExport }) ? context : void 0;
4140
4651
  const id = useId6();
4141
4652
  const drill = useMemo4(() => source ? drillOf(source, labels) : null, [source, labels]);
4142
4653
  const panel = useRef4(
4143
4654
  /** @type {HTMLDivElement | null} */
4144
4655
  null
4145
4656
  );
4146
- const [big, setBig] = useState6(false);
4657
+ const [big, setBig] = useState7(false);
4658
+ const pressed = useRef4(false);
4147
4659
  const narrow = useContext4(LayerContext).size === "narrow";
4148
4660
  const { onKeyDown } = useModal(panel, Boolean(drill), big ? () => setBig(false) : onClose);
4149
4661
  useEffect4(() => {
@@ -4162,7 +4674,7 @@ function DrillPanel({ drill: source, onClose, labels, locale, exportContext: con
4162
4674
  void exportDrill(kind, { drill, labels, ...exportContext, columns, root: exportContext.root.current });
4163
4675
  }
4164
4676
  };
4165
- return /* @__PURE__ */ React8.createElement(React8.Fragment, null, /* @__PURE__ */ React8.createElement("div", { className: "pk-scrim pk-drill-scrim", onClick: onClose, "aria-hidden": "true" }), /* @__PURE__ */ React8.createElement(
4677
+ return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement("div", { className: "pk-scrim pk-drill-scrim", onPointerDown: (e) => pressed.current = e.target === e.currentTarget, onClick: () => pressed.current && onClose(), "aria-hidden": "true" }), /* @__PURE__ */ React9.createElement(
4166
4678
  "div",
4167
4679
  {
4168
4680
  className: `pk-drill${big && !narrow ? " pk-drill-big" : ""}`,
@@ -4179,22 +4691,22 @@ function DrillPanel({ drill: source, onClose, labels, locale, exportContext: con
4179
4691
  }
4180
4692
  }
4181
4693
  },
4182
- /* @__PURE__ */ React8.createElement("div", { className: "pk-drill-head" }, /* @__PURE__ */ React8.createElement("div", { className: "pk-drill-heading" }, /* @__PURE__ */ React8.createElement("h2", { id }, labels.drillTitle), /* @__PURE__ */ React8.createElement("p", { className: "pk-drill-path" }, drill.title), /* @__PURE__ */ React8.createElement("p", { className: "pk-muted", "data-testid": "drill-count" }, partial ? fill(labels.drillShown, { shown: drill.rows.length.toLocaleString(locale), count: n }) : plural(labels.drillCount, drill.count, { lang: labels.lang, locale }))), /* @__PURE__ */ React8.createElement("div", { className: "pk-drill-actions" }, exportContext ? /* @__PURE__ */ React8.createElement(MenuButton, { label: labels.exportLabel, icon: "download", text: labels.exportLabel, role: "dialog", align: "end", testId: "drill-export", className: "pk-btn pk-small-btn" }, (close) => /* @__PURE__ */ React8.createElement(React8.Fragment, null, partial ? /* @__PURE__ */ React8.createElement("p", { className: "pk-hint pk-menu-hint", "data-testid": "drill-export-note" }, fill(labels.drillExportNote, { shown: drill.rows.length.toLocaleString(locale), count: n })) : null, /* @__PURE__ */ React8.createElement(Section, { title: labels.exportDownload }, /* @__PURE__ */ React8.createElement(ExportOption, { icon: "file", text: labels.drillCsv, onSelect: run("drill-csv", close), testId: "drill-csv" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "file", text: labels.drillXlsx, onSelect: run("drill-xlsx", close), testId: "drill-xlsx" })), /* @__PURE__ */ React8.createElement(Section, { title: labels.exportCopy }, /* @__PURE__ */ React8.createElement(ExportOption, { icon: "copy", text: labels.drillCopy, info: "drillCopy", onSelect: run("drill-copy", close), testId: "drill-copy" }), /* @__PURE__ */ React8.createElement(ExportOption, { icon: "copy", text: labels.drillJson, info: "drillJson", onSelect: run("drill-json", close), testId: "drill-json" })))) : null, narrow ? null : /* @__PURE__ */ React8.createElement("button", { type: "button", className: "pk-btn pk-pressable pk-small-btn", "data-pk-on": big ? "" : void 0, onClick: () => setBig((on) => !on), "data-testid": "drill-enlarge" }, /* @__PURE__ */ React8.createElement(Icon, { name: "enlarge", size: 14 }), /* @__PURE__ */ React8.createElement("span", { className: "pk-btn-text" }, big ? labels.reduce : labels.enlarge)), /* @__PURE__ */ React8.createElement("button", { type: "button", className: "pk-icon-btn", onClick: onClose, "data-autofocus": "", "aria-label": labels.close, title: labels.close }, /* @__PURE__ */ React8.createElement(Icon, { name: "x" })))),
4183
- /* @__PURE__ */ React8.createElement("div", { className: "pk-drill-body", tabIndex: 0, "aria-label": drill.title }, /* @__PURE__ */ React8.createElement("table", { className: "pk-drill-table" }, /* @__PURE__ */ React8.createElement("thead", null, /* @__PURE__ */ React8.createElement("tr", null, drill.columns.map((c) => /* @__PURE__ */ React8.createElement("th", { key: c.name, scope: "col", className: c.numeric ? "pk-num" : void 0, title: c.description, "aria-description": c.description }, c.label ?? c.name)))), /* @__PURE__ */ React8.createElement("tbody", null, drill.rows.map((row, i) => /* @__PURE__ */ React8.createElement("tr", { key: i }, drill.columns.map((c, k) => /* @__PURE__ */ React8.createElement("td", { key: c.name, className: c.numeric ? "pk-num" : void 0 }, c.numeric || row[k].length < 24 ? row[k] : /* @__PURE__ */ React8.createElement("div", { className: "pk-drill-text" }, row[k]))))))))
4694
+ /* @__PURE__ */ React9.createElement("div", { className: "pk-drill-head" }, /* @__PURE__ */ React9.createElement("div", { className: "pk-drill-heading" }, /* @__PURE__ */ React9.createElement("h2", { id }, labels.drillTitle), /* @__PURE__ */ React9.createElement("p", { className: "pk-drill-path" }, drill.title), /* @__PURE__ */ React9.createElement("p", { className: "pk-muted", "data-testid": "drill-count" }, partial ? fill(labels.drillShown, { shown: drill.rows.length.toLocaleString(locale), count: n }) : plural(labels.drillCount, drill.count, { lang: labels.lang, locale }))), /* @__PURE__ */ React9.createElement("div", { className: "pk-drill-actions" }, exportContext ? /* @__PURE__ */ React9.createElement(MenuButton, { label: labels.exportLabel, icon: "download", text: labels.exportLabel, role: "dialog", align: "end", testId: "drill-export", className: "pk-btn pk-small-btn" }, (close) => /* @__PURE__ */ React9.createElement(React9.Fragment, null, partial ? /* @__PURE__ */ React9.createElement("p", { className: "pk-hint pk-menu-hint", "data-testid": "drill-export-note" }, fill(labels.drillExportNote, { shown: drill.rows.length.toLocaleString(locale), count: n })) : null, /* @__PURE__ */ React9.createElement(Section, { title: labels.exportDownload }, /* @__PURE__ */ React9.createElement(ExportOption, { icon: "file", text: labels.drillCsv, onSelect: run("drill-csv", close), testId: "drill-csv" }), /* @__PURE__ */ React9.createElement(ExportOption, { icon: "file", text: labels.drillXlsx, onSelect: run("drill-xlsx", close), testId: "drill-xlsx" })), /* @__PURE__ */ React9.createElement(Section, { title: labels.exportCopy }, /* @__PURE__ */ React9.createElement(ExportOption, { icon: "copy", text: labels.drillCopy, info: "drillCopy", onSelect: run("drill-copy", close), testId: "drill-copy" }), /* @__PURE__ */ React9.createElement(ExportOption, { icon: "copy", text: labels.drillJson, info: "drillJson", onSelect: run("drill-json", close), testId: "drill-json" })))) : null, narrow ? null : /* @__PURE__ */ React9.createElement("button", { type: "button", className: "pk-btn pk-pressable pk-small-btn", "data-pk-on": big ? "" : void 0, onClick: () => setBig((on) => !on), "data-testid": "drill-enlarge" }, /* @__PURE__ */ React9.createElement(Icon, { name: "enlarge", size: 14 }), /* @__PURE__ */ React9.createElement("span", { className: "pk-btn-text" }, big ? labels.reduce : labels.enlarge)), /* @__PURE__ */ React9.createElement("button", { type: "button", className: "pk-icon-btn", onClick: onClose, "data-autofocus": "", "aria-label": labels.close, title: labels.close }, /* @__PURE__ */ React9.createElement(Icon, { name: "x" })))),
4695
+ /* @__PURE__ */ React9.createElement("div", { className: "pk-drill-body", tabIndex: 0, "aria-label": drill.title }, /* @__PURE__ */ React9.createElement("table", { className: "pk-drill-table" }, /* @__PURE__ */ React9.createElement("thead", null, /* @__PURE__ */ React9.createElement("tr", null, drill.columns.map((c) => /* @__PURE__ */ React9.createElement("th", { key: c.name, scope: "col", className: c.numeric ? "pk-num" : void 0, title: c.description, "aria-description": c.description }, c.label ?? c.name)))), /* @__PURE__ */ React9.createElement("tbody", null, drill.rows.map((row, i) => /* @__PURE__ */ React9.createElement("tr", { key: i }, drill.columns.map((c, k) => /* @__PURE__ */ React9.createElement("td", { key: c.name, className: c.numeric ? "pk-num" : void 0 }, c.numeric || row[k].length < 24 ? row[k] : /* @__PURE__ */ React9.createElement("div", { className: "pk-drill-text" }, row[k]))))))))
4184
4696
  ));
4185
4697
  }
4186
4698
 
4187
4699
  // src/data-menu.jsx
4188
- import React9, { useEffect as useEffect5, useRef as useRef5, useState as useState7 } from "react";
4700
+ import React10, { useEffect as useEffect5, useRef as useRef5, useState as useState8 } from "react";
4189
4701
  function DataMenu({ api, close, labels }) {
4190
4702
  const mod = importNow();
4191
- const [failed, setFailed] = useState7(false);
4192
- const [attempt, setAttempt] = useState7(0);
4703
+ const [failed, setFailed] = useState8(false);
4704
+ const [attempt, setAttempt] = useState8(0);
4193
4705
  const box = useRef5(
4194
4706
  /** @type {HTMLDivElement | null} */
4195
4707
  null
4196
4708
  );
4197
- const [late] = useState7(() => !mod);
4709
+ const [late] = useState8(() => !mod);
4198
4710
  const load = useRef5(api.load);
4199
4711
  useEffect5(() => {
4200
4712
  load.current = api.load;
@@ -4216,21 +4728,23 @@ function DataMenu({ api, close, labels }) {
4216
4728
  popover.querySelector("[data-pk-option], [data-autofocus]")?.focus({ preventScroll: true });
4217
4729
  }
4218
4730
  }, [late, mod, failed]);
4219
- return /* @__PURE__ */ React9.createElement("div", { ref: box }, mod ? /* @__PURE__ */ React9.createElement(mod.DataMenuPanel, { api, close }) : failed ? /* @__PURE__ */ React9.createElement("div", { className: "pk-menu-failed", role: "alert", "data-testid": "menu-failed" }, /* @__PURE__ */ React9.createElement("p", null, labels.menuFailed), /* @__PURE__ */ React9.createElement("button", { type: "button", className: "pk-btn pk-small-btn", "data-autofocus": "", onClick: () => {
4731
+ return /* @__PURE__ */ React10.createElement("div", { ref: box }, mod ? /* @__PURE__ */ React10.createElement(mod.DataMenuPanel, { api, close }) : failed ? /* @__PURE__ */ React10.createElement("div", { className: "pk-menu-failed", role: "alert", "data-testid": "menu-failed" }, /* @__PURE__ */ React10.createElement("p", null, labels.menuFailed), /* @__PURE__ */ React10.createElement("button", { type: "button", className: "pk-btn pk-small-btn", "data-autofocus": "", onClick: () => {
4220
4732
  setFailed(false);
4221
4733
  setAttempt((n) => n + 1);
4222
- } }, labels.tryAgain)) : /* @__PURE__ */ React9.createElement("p", { className: "pk-hint pk-menu-loading", role: "status" }, labels.loadingMenu));
4734
+ } }, labels.tryAgain)) : /* @__PURE__ */ React10.createElement("p", { className: "pk-hint pk-menu-loading", role: "status" }, labels.loadingMenu));
4223
4735
  }
4224
4736
  export {
4737
+ AddMenu,
4225
4738
  AxisMenu,
4226
- ChartTypePanel,
4739
+ ChartSettingsPanel,
4227
4740
  DataMenu,
4228
4741
  DrillPanel,
4229
4742
  ExportPanel,
4230
4743
  FilterMenu,
4231
4744
  FilterPopover,
4232
4745
  LoadCheck,
4233
- OptionsPanel,
4746
+ MorePanel,
4747
+ TableSettingsPanel,
4234
4748
  ValueMenu,
4235
4749
  ViewsPanel,
4236
4750
  addMenuTexts,