pivotkit-react 0.2.0 → 0.4.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 (64) hide show
  1. package/CHANGELOG.md +284 -1
  2. package/README.md +1 -1
  3. package/dist/chunks/{chunk-F6MVUAQD.js → chunk-6MDAL3IO.js} +51 -3
  4. package/dist/chunks/{chunk-53ZMK4BH.js → chunk-EM23V5GH.js} +6 -0
  5. package/dist/chunks/{chunk-LQCWFJBS.js → chunk-LEN5RPBM.js} +147 -26
  6. package/dist/chunks/{chunk-OYY4BKIL.js → chunk-RWYHJRQO.js} +6 -0
  7. package/dist/chunks/{chunk-QBD4FOBB.js → chunk-WB4GKWFQ.js} +124 -18
  8. package/dist/chunks/chunk-XN55BQ4M.js +618 -0
  9. package/dist/chunks/{chunk-X7H7BAVT.js → chunk-YITKWZ4L.js} +312 -628
  10. package/dist/chunks/chunk-ZYEYZSYL.js +187 -0
  11. package/dist/chunks/{unused-texts-YTNJCFFC.js → unused-texts-K3VFH65P.js} +1 -1
  12. package/dist/chunks/{unused-texts-de-SGOHV4N7.js → unused-texts-de-OW4TGIVX.js} +1 -1
  13. package/dist/import-ui.js +769 -0
  14. package/dist/import-worker.js +20 -0
  15. package/dist/index.js +653 -227
  16. package/dist/labels.js +14 -10
  17. package/dist/menu-texts-de.js +1 -1
  18. package/dist/menus.js +2499 -676
  19. package/dist/styles.css +673 -125
  20. package/package.json +3 -2
  21. package/types/chip-menus.d.ts +20 -4
  22. package/types/data-history.d.ts +85 -0
  23. package/types/data-keep.d.ts +51 -0
  24. package/types/data-menu.d.ts +11 -0
  25. package/types/dnd.d.ts +8 -4
  26. package/types/dom.d.ts +40 -7
  27. package/types/field-info.d.ts +32 -0
  28. package/types/filter-level.d.ts +16 -0
  29. package/types/filter.d.ts +31 -0
  30. package/types/help.d.ts +0 -7
  31. package/types/import-host.d.ts +53 -0
  32. package/types/import-labels.d.ts +360 -0
  33. package/types/import-module.d.ts +2 -0
  34. package/types/import-run.d.ts +73 -0
  35. package/types/import-source.d.ts +32 -0
  36. package/types/import-steps.d.ts +121 -0
  37. package/types/import-ui.d.ts +108 -0
  38. package/types/import-worker.d.ts +1 -0
  39. package/types/index.d.ts +56 -4
  40. package/types/labels.d.ts +97 -2
  41. package/types/lazy-import.d.ts +4 -0
  42. package/types/lazy-menus.d.ts +2 -2
  43. package/types/levels.d.ts +106 -0
  44. package/types/menu-fields.d.ts +80 -0
  45. package/types/menu-labels.d.ts +214 -22
  46. package/types/menu-ops.d.ts +150 -9
  47. package/types/menu-topics.d.ts +291 -0
  48. package/types/menus.d.ts +2 -1
  49. package/types/names.d.ts +141 -1
  50. package/types/overflow.d.ts +29 -17
  51. package/types/place.d.ts +44 -0
  52. package/types/popover.d.ts +47 -5
  53. package/types/section.d.ts +8 -11
  54. package/types/tips.d.ts +1 -36
  55. package/types/toasts.d.ts +1 -1
  56. package/types/toolbar-panels.d.ts +17 -9
  57. package/types/unused-keep.d.ts +20 -0
  58. package/types/unused-texts.d.ts +6 -0
  59. package/types/unused.d.ts +1 -0
  60. package/types/use-view-history.d.ts +13 -4
  61. package/types/view-ops.d.ts +12 -0
  62. package/types/virtual.d.ts +15 -0
  63. package/types/zones.d.ts +5 -4
  64. package/types/sections.d.ts +0 -2
package/dist/menus.js CHANGED
@@ -3,33 +3,35 @@ import {
3
3
  CHART_TYPE_NAMES,
4
4
  ClearInput,
5
5
  HelpContext,
6
- Icon,
7
6
  InfoButton,
8
- LayerContext,
9
- MenuButton,
10
- Option,
11
- Popover,
12
7
  SHORTCUTS,
13
8
  SLICE_TYPES,
14
9
  ZONES,
15
- ZONE_ICON,
16
10
  axisOf,
17
11
  chartTypeOf,
18
12
  clone,
13
+ dateSpan,
14
+ dayText,
19
15
  decodeRow,
20
16
  filterZoneFields,
21
17
  filtersOf,
22
18
  groupField,
23
19
  groupingName,
24
20
  groupingOf,
25
- isSection,
21
+ importNow,
22
+ isoDay,
23
+ itemRuleText,
26
24
  linkNow,
27
25
  loadCheck,
28
26
  loadLink,
29
27
  moveField,
30
28
  numericResult,
29
+ periodText,
30
+ rangeShare,
31
31
  readLinkParam,
32
32
  refLabel,
33
+ relativeDays,
34
+ relativeText,
33
35
  reorder,
34
36
  same,
35
37
  sameRef,
@@ -40,110 +42,52 @@ import {
40
42
  sortOf,
41
43
  sortText,
42
44
  sourceOf,
43
- useModal,
44
45
  valueConditionText,
45
46
  valueLabel,
46
47
  viewFromObject,
47
48
  viewFromText,
49
+ wholeYears,
48
50
  withLinkParam
49
- } from "./chunks/chunk-X7H7BAVT.js";
51
+ } from "./chunks/chunk-YITKWZ4L.js";
50
52
  import {
51
53
  addMenuTexts,
52
54
  hasMenuTexts,
53
55
  menuLabels
54
- } from "./chunks/chunk-LQCWFJBS.js";
56
+ } from "./chunks/chunk-LEN5RPBM.js";
57
+ import {
58
+ Group,
59
+ Icon,
60
+ LayerContext,
61
+ MenuButton,
62
+ Option,
63
+ Popover,
64
+ activeIn,
65
+ rootOf,
66
+ stopAfter,
67
+ useFormName,
68
+ useModal
69
+ } from "./chunks/chunk-XN55BQ4M.js";
55
70
  import {
56
71
  fill,
57
72
  hostFailure,
58
73
  messageOf,
59
74
  plural
60
- } from "./chunks/chunk-F6MVUAQD.js";
75
+ } from "./chunks/chunk-6MDAL3IO.js";
61
76
 
62
77
  // src/chip-menus.jsx
63
- import React2, { useContext as useContext2, useEffect, useId as useId2, useRef, useState } from "react";
64
- import { CATALOG, aggregatorsFor, fieldLabel, isFormat as isFormat2 } from "pivotkit-core";
78
+ import React6, { useId as useId4, useState as useState4 } from "react";
79
+ import { fieldLabel as fieldLabel4 } from "pivotkit-core";
65
80
 
66
- // src/numbers.js
67
- var cache = /* @__PURE__ */ new Map();
68
- function marks(locale) {
69
- let m = cache.get(locale);
70
- if (!m) {
71
- let parts;
72
- try {
73
- parts = new Intl.NumberFormat(locale).formatToParts(12345.6);
74
- } catch {
75
- parts = new Intl.NumberFormat("en-US").formatToParts(12345.6);
76
- }
77
- m = {
78
- decimal: parts.find((p) => p.type === "decimal")?.value ?? ".",
79
- group: parts.find((p) => p.type === "group")?.value ?? ","
80
- };
81
- cache.set(locale, m);
82
- }
83
- return m;
84
- }
85
- var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
86
- var PLAIN = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
87
- function parseNumber(text, locale) {
88
- const t = String(text ?? "").replace(/[\s\u00a0\u202f]/g, "").replace(/\u2212/g, "-");
89
- if (t === "") {
90
- return null;
91
- }
92
- const { decimal, group } = marks(locale);
93
- const g = /[\s\u00a0\u202f]/.test(group) ? "" : escape(group);
94
- const d = escape(decimal);
95
- const grouped = g ? `\\d{1,3}(?:${g}\\d{3})+` : "(?!)";
96
- const local = new RegExp(`^([+-]?)(${grouped}|\\d+)?(?:${d}(\\d+))?$`);
97
- const match = local.exec(t);
98
- if (match && (match[2] !== void 0 || match[3] !== void 0)) {
99
- const whole = (match[2] ?? "0").split(group).join("");
100
- const n = Number(`${match[1]}${whole}${match[3] !== void 0 ? `.${match[3]}` : ""}`);
101
- return Number.isFinite(n) ? n : null;
102
- }
103
- if (PLAIN.test(t)) {
104
- const n = Number(t);
105
- return Number.isFinite(n) ? n : null;
106
- }
107
- return null;
108
- }
109
- function numberText(n, locale) {
110
- if (typeof n !== "number" || !Number.isFinite(n)) {
111
- return "";
112
- }
113
- try {
114
- return n.toLocaleString(locale, { useGrouping: false, maximumFractionDigits: 20 });
115
- } catch {
116
- return String(n);
117
- }
118
- }
81
+ // src/filter-level.jsx
82
+ import React5, { useContext as useContext3, useEffect as useEffect2, useId as useId3, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
83
+ import { CATALOG as CATALOG4, LIMITS, fieldItems as fieldItems2, fieldLabel as fieldLabel3, formatter as formatter2 } from "pivotkit-core";
119
84
 
120
- // src/section.jsx
121
- import React, { useContext, useId } from "react";
122
- function SettingInfo({ id, name }) {
123
- const { explain, labels } = useContext(HelpContext);
124
- const text = labels && labels.settingInfo && Object.hasOwn(labels.settingInfo, id) ? labels.settingInfo[id] : null;
125
- if (!explain || !labels || !text) {
126
- return null;
127
- }
128
- return /* @__PURE__ */ React.createElement(InfoButton, { info: { description: text }, name, label: fill(labels.aboutSetting, { setting: name }), labels, className: "pk-setting-info", testId: `setting-info-${id}` });
129
- }
130
- function Section({ title, children, id, info, state, changed }) {
131
- const titleId = useId();
132
- const bodyId = useId();
133
- const { isOpen, setOpen, labels } = useContext(HelpContext);
134
- const name = typeof title === "string" ? title : "";
135
- const head = info ? /* @__PURE__ */ React.createElement(SettingInfo, { id: info, name }) : null;
136
- if (!id) {
137
- return /* @__PURE__ */ React.createElement("div", { className: "pk-section", role: "group", "aria-labelledby": titleId }, /* @__PURE__ */ React.createElement("div", { className: "pk-section-head" }, /* @__PURE__ */ React.createElement("div", { className: "pk-section-title", id: titleId }, title), head), children);
138
- }
139
- const open = isOpen(id);
140
- const shown = !open && state;
141
- const label = shown && name ? `${name}, ${state}${changed && labels?.sectionChanged ? labels.sectionChanged : ""}` : void 0;
142
- return /* @__PURE__ */ React.createElement("div", { className: `pk-section${open ? "" : " pk-folded"}`, role: "group", "aria-labelledby": titleId, "data-section": id }, /* @__PURE__ */ React.createElement("div", { className: "pk-section-head" }, /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-section-title pk-section-toggle", id: titleId, "aria-expanded": open, "aria-controls": bodyId, "aria-label": label, onClick: () => setOpen(id, !open), "data-testid": `section-${id}` }, /* @__PURE__ */ React.createElement(Icon, { name: open ? "chevronDown" : "chevronRight", size: 18 }), /* @__PURE__ */ React.createElement("span", { className: "pk-section-name" }, title), shown ? /* @__PURE__ */ React.createElement("span", { className: "pk-section-state pk-badge-cut", "data-testid": `section-state-${id}` }, changed ? /* @__PURE__ */ React.createElement("span", { className: "pk-section-mark", "aria-hidden": "true" }, "\u25CF ") : null, state) : null), head), /* @__PURE__ */ React.createElement("div", { id: bodyId, className: "pk-section-body", hidden: !open }, children));
143
- }
85
+ // src/filter.jsx
86
+ import React, { useMemo, useState } from "react";
87
+ import { CATALOG as CATALOG2, fieldItems, fieldLabel } from "pivotkit-core";
144
88
 
145
89
  // src/menu-ops.js
146
- import { isFormat } from "pivotkit-core";
90
+ import { CATALOG, computePivot, isFormat } from "pivotkit-core";
147
91
  var COUNTING = /* @__PURE__ */ new Set(["count", "countUnique", "listUnique"]);
148
92
  var unitOf = (agg) => COUNTING.has(agg) ? "count" : "field";
149
93
  function updateValue(view, index, patch, options = {}) {
@@ -232,17 +176,98 @@ function setTopFilter(view, field, top, previous) {
232
176
  }
233
177
  return replaceFilters(view, field, ["top"], entry ? [entry] : []);
234
178
  }
235
- function setValueFilter(view, field, condition, previous) {
236
- let entry = null;
237
- if (condition) {
238
- const { by, op, value, value2 } = condition;
239
- const between = op === "between" || op === "notBetween";
240
- entry = { field, type: "value", by: { field: by.field, agg: by.agg }, op, value, ...between ? { value2 } : {} };
179
+ var RULE_TYPES = Object.freeze(["relative", "compare", "value", "label"]);
180
+ var RULES_MAX = 10;
181
+ var setRule = (view, field, previous, entry) => replaceFilter(view, field, previous, entry);
182
+ var COARSE = Object.freeze(["year", "yearQuarter"]);
183
+ function ruleKind(encoded, view, field) {
184
+ const grouping = groupingOf(view, field);
185
+ const source = encoded.column(sourceOf(view, field))?.type ?? "string";
186
+ const dates = source === "date";
187
+ const item = grouping ? grouping.by === "day" ? "date" : "group" : source === "number" || source === "date" ? source : null;
188
+ const cyclic = dates && Boolean(grouping) && CATALOG.cyclicUnits.includes(grouping.by);
189
+ const quick = dates && !cyclic;
190
+ return { item, dates, cyclic, quick, months: quick && !COARSE.includes(grouping?.by), days: quick && item === "date", unit: grouping?.by ?? null };
191
+ }
192
+ function ruleText(view, f, { labels, locale, timeZone, date, labelOf, span }) {
193
+ return f.type === "value" ? valueConditionText(view, f, labels, locale) : itemRuleText(f, labels, locale, { timeZone, date, labelOf, span });
194
+ }
195
+ function quickChoice(view, field, fk, all = []) {
196
+ const ranges = filtersOf(view, field, ["relative"]);
197
+ const compared = filtersOf(view, field, ["compare"]);
198
+ if (fk.cyclic) {
199
+ const whole = compared.filter(isWholeYear);
200
+ const years = whole.length ? yearsCombined(whole, all) : null;
201
+ return years ? { id: "yearsCombined", years, filters: whole } : { id: "all", filters: [] };
241
202
  }
242
- if (previous) {
243
- return replaceFilter(view, field, previous, entry);
203
+ const offered = { year: true, month: fk.months, day: fk.days };
204
+ const r = ranges.find((f) => offered[f.unit]);
205
+ if (!r) {
206
+ return { id: "all", filters: [] };
207
+ }
208
+ const id = (
209
+ /** @type {"thisYear" | "years" | "months" | "days"} */
210
+ r.unit === "year" ? r.count === 1 ? "thisYear" : "years" : `${r.unit}s`
211
+ );
212
+ return { id, count: r.count, anchor: r.anchor ?? "today", filters: [r] };
213
+ }
214
+ function yearsCombined(compared, all) {
215
+ let kept = new Set(all);
216
+ for (const f of compared) {
217
+ const [a, b] = (
218
+ /** @type {[string, string]} */
219
+ wholeYears(f.value, f.value2).map(Number)
220
+ );
221
+ kept = new Set([...kept].filter((y) => (a <= y && y <= b) === (f.op === "between")));
222
+ }
223
+ return kept.size ? [...kept].sort((x, y) => x - y) : null;
224
+ }
225
+ var isWholeYear = (f) => f.type === "compare" && (f.op === "between" || f.op === "notBetween") && wholeYears(f.value, f.value2) !== null;
226
+ function yearRules(field, years, all) {
227
+ if (!years.length || years.length === all.length) {
228
+ return [];
229
+ }
230
+ const day = (y, last) => `${String(y).padStart(4, "0")}-${last ? "12-31" : "01-01"}`;
231
+ const rule = (op, from, to) => ({ field, type: "compare", op, value: day(from, false), value2: day(to, true) });
232
+ const rules = [rule("between", years[0], years[years.length - 1])];
233
+ for (let i = 1; i < years.length; i++) {
234
+ if (all.some((y) => years[i - 1] < y && y < years[i])) {
235
+ rules.push(rule("notBetween", years[i - 1] + 1, years[i] - 1));
236
+ }
237
+ }
238
+ return rules;
239
+ }
240
+ function setYearsCombined(view, field, years, all) {
241
+ const cleared = filtersOf(view, field, ["compare"]).filter(isWholeYear).reduce((v, f) => setRule(v, field, f, null), view);
242
+ return yearRules(field, years, all).reduce((v, r) => setRule(v, field, null, r), cleared);
243
+ }
244
+ function setQuickRange(view, field, range) {
245
+ return replaceFilters(view, field, ["relative"], range ? [{ field, type: "relative", unit: range.unit, count: range.count, ...range.anchor === "latest" ? { anchor: "latest" } : {} }] : []);
246
+ }
247
+ function setAnchor(view, field, anchor) {
248
+ const next = clone(view);
249
+ for (const f of next.filters) {
250
+ if (same(f.field, field) && f.type === "relative") {
251
+ delete f.anchor;
252
+ if (anchor === "latest") {
253
+ f.anchor = "latest";
254
+ }
255
+ }
256
+ }
257
+ return next;
258
+ }
259
+ var resetFilter = (view, field) => replaceFilters(view, field, ["include", "exclude", ...RULE_TYPES], []);
260
+ function itemTotals(encoded, view, field, by, filters) {
261
+ const result = computePivot(encoded, { ...view, rows: [field], cols: [], values: [{ ...by.field ? { field: by.field } : {}, agg: by.agg }], filters, sort: [] });
262
+ const totals = /* @__PURE__ */ new Map();
263
+ if (!result.values.length) {
264
+ return { totals, rows: result.rows.length };
265
+ }
266
+ for (const node of result.rowRoot.children) {
267
+ const v = result.value(node, result.colRoot, 0);
268
+ totals.set(JSON.stringify(node.key), typeof v === "number" && Number.isFinite(v) ? v : null);
244
269
  }
245
- return replaceFilters(view, field, ["value"], entry ? [entry] : []);
270
+ return { totals, rows: result.rows.length };
246
271
  }
247
272
  function withMeasure(choices, ref) {
248
273
  return ref && !choices.some((c) => sameRef(c, ref)) ? [...choices, { field: ref.field ?? null, agg: ref.agg }] : choices;
@@ -257,11 +282,9 @@ function measureChoices(view, typeOf) {
257
282
  }
258
283
  return out.length ? out : [{ field: null, agg: "count" }];
259
284
  }
260
- function removeFilters(view, field) {
261
- return replaceFilters(view, field, ["include", "exclude", "label", "value"], []);
262
- }
263
- function hasFilter(view, field) {
264
- return filtersOf(view, field, ["include", "exclude", "label", "value"]).some((f) => f.type !== "exclude" || f.items.length > 0);
285
+ function removeRules(view, field, keep = []) {
286
+ const kept = new Set(keep.map((f) => JSON.stringify(f)));
287
+ return filtersOf(view, field, RULE_TYPES).filter((f) => !kept.has(JSON.stringify(f))).reduce((v, f) => setRule(v, field, f, null), view);
265
288
  }
266
289
  var TOTALS = Object.freeze(["grandTotalRow", "grandTotalColumn", "rowSubtotals", "colSubtotals"]);
267
290
  function totalNoEffect(view, key) {
@@ -280,319 +303,2168 @@ function conditionKind(encoded, view, field) {
280
303
  const type = encoded.column(sourceOf(view, field))?.type ?? "string";
281
304
  return type === "date" || type === "boolean" ? null : type === "number" ? "number" : "text";
282
305
  }
283
- function filterText(view, field, state, labels, locale) {
306
+ function filterState(view, field, state, labels, locale) {
284
307
  const same2 = (f) => typeof f.field === "string" && f.field.toLowerCase() === field.toLowerCase();
285
308
  const parts = [];
286
309
  if (state && state.summary) {
287
310
  parts.push(fill(labels.filterSummary, { shown: state.summary.shown.toLocaleString(locale), total: state.summary.total.toLocaleString(locale) }));
288
311
  }
312
+ parts.push(...state?.rules ?? []);
289
313
  for (const f of view.filters.filter(same2)) {
290
- if (f.type === "label") {
291
- const op = Object.hasOwn(labels.labelOps, f.op) ? labels.labelOps[f.op] : f.op;
292
- parts.push(`${op} \u201C${f.value}\u201D`);
293
- } else if (f.type === "value") {
294
- parts.push(valueConditionText(view, f, labels, locale));
314
+ if (f.type === "value" || f.type === "label" && !state?.rules) {
315
+ parts.push(ruleText(view, f, { labels, locale, timeZone: "UTC", date: false }));
295
316
  }
296
317
  }
297
- return parts.length ? fill(labels.filterIs, { filter: parts.join(", ") }) : null;
318
+ return parts.length ? parts.join(", ") : null;
298
319
  }
299
320
 
300
- // src/chip-menus.jsx
301
- var FORMAT_CHOICES = ["number", "number:0", "number:2", "currency", "percent"].filter(isFormat2);
302
- var MORE_FORMATS = ["integer", "compact", "bytes", "duration:h", "duration:s"].filter(isFormat2);
303
- var COMMON_SHOW_AS = CATALOG.showAs.filter((s) => ["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal"].includes(s));
304
- function More({ title, open, children }) {
305
- return /* @__PURE__ */ React2.createElement("details", { className: "pk-more", open }, /* @__PURE__ */ React2.createElement("summary", { className: "pk-more-title" }, title), children);
306
- }
307
- function readNumber(text, { kind = "number", required = true, tried = false, labels, locale }) {
308
- const value = parseNumber(text, locale);
309
- const ok = value !== null && (kind === "number" || (kind === "size" ? value > 0 : Number.isInteger(value) && value >= 1));
310
- const say = () => kind === "count" ? labels.countInvalid : fill(kind === "size" ? labels.sizeInvalid : labels.numberInvalid, { example: (kind === "size" ? 0.5 : 1234.5).toLocaleString(locale) });
311
- if (text.trim() === "") {
312
- return { value: null, problem: required && tried ? say() : null };
313
- }
314
- return ok ? { value, problem: null } : { value: null, problem: say() };
315
- }
316
- function NumberField({ value, onChange, problem, label, testId, className = "pk-field-label", shown, shownClass }) {
317
- const id = useId2();
318
- return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("label", { className }, shown ? /* @__PURE__ */ React2.createElement("span", { className: shownClass }, shown) : /* @__PURE__ */ React2.createElement("span", { className: "pk-sr" }, label), /* @__PURE__ */ React2.createElement(
319
- "input",
320
- {
321
- type: "text",
322
- inputMode: "decimal",
323
- autoComplete: "off",
324
- spellCheck: false,
325
- value,
326
- onChange: (e) => onChange(e.target.value),
327
- "aria-label": label,
328
- "aria-invalid": problem ? true : void 0,
329
- "aria-describedby": problem ? id : void 0,
330
- "data-testid": testId
321
+ // src/filter.jsx
322
+ var FILTER_LIST_MAX = 300;
323
+ var keyOf = (v) => JSON.stringify(v);
324
+ function ValueList({ items, selected, onChange, labels, locale, autoFocus = false, tail, children }) {
325
+ const [query, setQuery] = useState("");
326
+ const name = useFormName();
327
+ const q = query.trim().toLocaleLowerCase();
328
+ const matching = q ? items.filter((i) => i.label.toLocaleLowerCase().includes(q)) : items;
329
+ const inList = tail ? matching.filter((i) => !tail.isOut(i)) : matching;
330
+ const out = tail ? matching.filter((i) => tail.isOut(i)) : [];
331
+ const shown = inList.slice(0, FILTER_LIST_MAX);
332
+ const setAll = (on) => {
333
+ const next = new Set(selected);
334
+ for (const i of matching) {
335
+ if (on) {
336
+ next.add(keyOf(i.value));
337
+ } else {
338
+ next.delete(keyOf(i.value));
339
+ }
340
+ }
341
+ onChange(next);
342
+ };
343
+ const toggle = (v) => {
344
+ const next = new Set(selected);
345
+ const k = keyOf(v);
346
+ if (next.has(k)) {
347
+ next.delete(k);
348
+ } else {
349
+ next.add(k);
331
350
  }
332
- )), problem ? /* @__PURE__ */ React2.createElement("p", { id, className: "pk-form-problem", "data-testid": `${testId}-problem` }, problem) : null);
351
+ onChange(next);
352
+ };
353
+ const row = (i, muted) => {
354
+ const k = keyOf(i.value);
355
+ return /* @__PURE__ */ React.createElement("li", { key: k, className: `pk-value${muted ? " pk-value-out" : ""}` }, /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("input", { type: "checkbox", name, checked: selected.has(k), onChange: () => toggle(i.value) }), /* @__PURE__ */ React.createElement("span", { className: "pk-value-label" }, i.label), /* @__PURE__ */ React.createElement("span", { className: "pk-count" }, i.count.toLocaleString(locale))), /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-link pk-only", onClick: () => onChange(/* @__PURE__ */ new Set([k])), "aria-label": `${labels.onlyThis}: ${i.label}` }, labels.onlyThis));
356
+ };
357
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("label", { className: "pk-search" }, /* @__PURE__ */ React.createElement(Icon, { name: "search" }), /* @__PURE__ */ React.createElement("span", { className: "pk-sr" }, labels.searchValues), /* @__PURE__ */ React.createElement(ClearInput, { type: "search", value: query, placeholder: labels.searchValues, onChange: setQuery, clearLabel: labels.clearText, "data-autofocus": autoFocus ? "" : void 0, "data-testid": "filter-search" })), /* @__PURE__ */ React.createElement("div", { className: "pk-filter-actions" }, /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-action", onClick: () => setAll(true), "data-testid": "select-all" }, labels.selectAll), /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-action", onClick: () => setAll(false), "data-testid": "select-none" }, labels.selectNone)), /* @__PURE__ */ React.createElement("div", { className: "pk-filter-body" }, /* @__PURE__ */ React.createElement("ul", { className: "pk-values", role: "list" }, shown.map((i) => row(i, false)), inList.length > shown.length ? /* @__PURE__ */ React.createElement("li", { className: "pk-hint pk-values-more" }, fill(labels.valuesShown, { shown: shown.length, total: inList.length.toLocaleString(locale) })) : null, out.length && tail ? tail.render(out, (i) => row(i, true), q !== "") : null), children));
333
358
  }
334
- function BinForm({ grouping, labels, onApply, onClear, onCancel, range, locale }) {
335
- const [size, setSize] = useState(numberText(grouping?.size, locale));
336
- const [start, setStart] = useState(numberText(grouping?.origin, locale));
337
- const [tried, setTried] = useState(false);
338
- const problemId = useId2();
339
- const sized = readNumber(size, { kind: "size", tried, labels, locale });
340
- const started = readNumber(start, { required: false, labels, locale });
341
- const n = sized.value;
342
- const s = start.trim() === "" ? 0 : started.value;
343
- const far = n !== null && s !== null && binProblem(n, s, range) === "far";
344
- const number = (x) => x.toLocaleString(locale, { maximumFractionDigits: 6 });
345
- return /* @__PURE__ */ React2.createElement(
359
+ function FilterBody({ view: current, base, field, encoded, locale, labels, commit, close }) {
360
+ const view = base ?? current;
361
+ const formName = useFormName();
362
+ const info = useMemo(() => fieldItems(encoded, field, { view, locale, labels: labels.core }), [encoded, field, view, locale, labels]);
363
+ const all = useMemo(() => info ? info.items.map((i) => i.value) : [], [info]);
364
+ const [selected, setSelected] = useState(() => new Set(selectedItems(view, field, all).map(keyOf)));
365
+ const label = filtersOf(view, field, ["label"])[0];
366
+ const [op, setOp] = useState(label?.op ?? "");
367
+ const [text, setText] = useState(label?.value ?? "");
368
+ if (!info) {
369
+ return null;
370
+ }
371
+ const name = fieldLabel(field, labels.core);
372
+ const apply = () => {
373
+ let next = setItemFilter(view, field, all.filter((v) => selected.has(keyOf(v))), all);
374
+ next = setLabelFilter(next, field, op ? { op, value: text } : null);
375
+ close();
376
+ commit(next, { step: "filter", field: name });
377
+ };
378
+ const kind = conditionKind(encoded, view, field) ?? (label ? "text" : null);
379
+ return /* @__PURE__ */ React.createElement(
346
380
  "form",
347
381
  {
348
- className: "pk-inline-form pk-bin-form",
382
+ className: "pk-filter",
349
383
  onSubmit: (e) => {
350
384
  e.preventDefault();
351
- if (onClear && size.trim() === "") {
352
- onClear();
353
- return;
354
- }
355
- setTried(true);
356
- if (n !== null && s !== null && !far) {
357
- onApply(n, s);
358
- }
385
+ apply();
359
386
  }
360
387
  },
361
- /* @__PURE__ */ React2.createElement(NumberField, { value: size, onChange: setSize, problem: sized.problem, label: labels.binSize, shown: labels.binSize, testId: "bin-size" }),
362
- /* @__PURE__ */ React2.createElement("label", { className: "pk-field-label" }, /* @__PURE__ */ React2.createElement("span", null, labels.binStart), /* @__PURE__ */ React2.createElement(ClearInput, { type: "text", inputMode: "decimal", autoComplete: "off", spellCheck: false, value: start, placeholder: "0", onChange: setStart, clearLabel: labels.clearText, "data-testid": "bin-start", "aria-invalid": far || started.problem ? true : void 0, "aria-describedby": far || started.problem ? problemId : void 0 })),
363
- started.problem ? /* @__PURE__ */ React2.createElement("p", { id: problemId, className: "pk-form-problem", "data-testid": "bin-start-problem" }, started.problem) : far && range && s !== null && n !== null ? /* @__PURE__ */ React2.createElement("p", { id: problemId, className: "pk-form-problem", "data-testid": "bin-problem" }, fill(labels.binStartFar, { start: number(s), min: number(range.min), max: number(range.max) })) : null,
364
- /* @__PURE__ */ React2.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: far }, labels.apply),
365
- /* @__PURE__ */ React2.createElement(CancelButton, { labels, onCancel, testId: "bin-cancel" })
388
+ /* @__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) }))),
389
+ /* @__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), CATALOG2.labelOps.map((o) => /* @__PURE__ */ React.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))), op ? /* @__PURE__ */ React.createElement(
390
+ ClearInput,
391
+ {
392
+ type: "text",
393
+ value: text,
394
+ onChange: setText,
395
+ onClear: () => {
396
+ if (!base && filtersOf(view, field, ["label"]).length) {
397
+ commit(setLabelFilter(view, field, null), { step: "filter", field: name });
398
+ }
399
+ },
400
+ clearLabel: labels.clearText,
401
+ "aria-label": labels.conditionValue,
402
+ placeholder: labels.conditionValue,
403
+ maxLength: 1e3,
404
+ "data-testid": "filter-condition-text"
405
+ }
406
+ ) : null) : null),
407
+ /* @__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))
366
408
  );
367
409
  }
368
- function MeasurePick({ choices, names, index, onChange, label, prefix, testId }) {
369
- if (choices.length < 2) {
370
- return /* @__PURE__ */ React2.createElement("span", { className: "pk-muted pk-by" }, prefix ? `${prefix} ${names[0]}` : names[0]);
410
+ function FilterPopover({ target, onClose, view, encoded, locale, labels, commit }) {
411
+ const anchor = useMemo(() => ({ current: target ? target.anchor : null }), [target]);
412
+ return /* @__PURE__ */ React.createElement(Popover, { open: Boolean(target), anchor, onClose, label: target ? fill(labels.filterTitle, { field: fieldLabel(target.field, labels.core) }) : "", className: "pk-filter-popover", fill: true }, target ? /* @__PURE__ */ React.createElement(FilterBody, { key: target.field, view, base: target.base, field: target.field, encoded, locale, labels, commit, close: onClose }) : null);
413
+ }
414
+
415
+ // src/levels.jsx
416
+ import React3, { useContext as useContext2, useEffect, useId, useLayoutEffect, useRef, useState as useState2 } from "react";
417
+
418
+ // src/section.jsx
419
+ import React2, { useContext } from "react";
420
+ function SettingInfo({ id, name, tabIndex }) {
421
+ const { explain, labels } = useContext(HelpContext);
422
+ const text = labels && labels.settingInfo && Object.hasOwn(labels.settingInfo, id) ? labels.settingInfo[id] : null;
423
+ if (!explain || !labels || !text) {
424
+ return null;
371
425
  }
372
- return /* @__PURE__ */ React2.createElement("label", { className: "pk-field-label pk-by-pick" }, prefix ? /* @__PURE__ */ React2.createElement("span", { className: "pk-muted" }, prefix) : /* @__PURE__ */ React2.createElement("span", { className: "pk-sr" }, label), /* @__PURE__ */ React2.createElement("select", { value: index, onChange: (e) => onChange(Number(e.target.value)), "aria-label": label, "data-testid": testId }, choices.map((c, i) => /* @__PURE__ */ React2.createElement("option", { key: `${c.field}:${c.agg}`, value: i }, names[i]))));
426
+ return /* @__PURE__ */ React2.createElement(InfoButton, { info: { description: text }, name, label: fill(labels.aboutSetting, { setting: name }), labels, className: "pk-setting-info", testId: `setting-info-${id}`, tabIndex });
373
427
  }
374
- var choiceIndex = (choices, ref) => Math.max(0, choices.findIndex((c) => sameRef(c, ref)));
375
- function TopForm({ top, labels, choices, names, onApply, onCancel, locale }) {
376
- const [count, setCount] = useState(numberText(top?.count ?? 10, locale));
377
- const [bottom, setBottom] = useState(Boolean(top?.bottom));
378
- const [by, setBy] = useState(() => choiceIndex(choices, top?.by));
379
- const [tried, setTried] = useState(false);
380
- const counted = readNumber(count, { kind: "count", tried, labels, locale });
381
- return /* @__PURE__ */ React2.createElement(
382
- "form",
428
+ function Section({ title, children, info }) {
429
+ const name = typeof title === "string" ? title : "";
430
+ return /* @__PURE__ */ React2.createElement(Group, { title, head: info ? /* @__PURE__ */ React2.createElement(SettingInfo, { id: info, name }) : null }, children);
431
+ }
432
+
433
+ // src/menu-topics.js
434
+ import { CATALOG as CATALOG3, aggregatorsFor, fieldLabel as fieldLabel2, formatter, isFormat as isFormat2 } from "pivotkit-core";
435
+ var FORMAT_CHOICES = Object.freeze(["number", "number:0", "number:2", "currency", "percent"].filter(isFormat2));
436
+ var MORE_FORMATS = Object.freeze(["integer", "compact", "bytes", "duration:h", "duration:s"].filter(isFormat2));
437
+ var COMMON_SHOW_AS = CATALOG3.showAs.filter((s) => ["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal"].includes(s));
438
+ var EXAMPLE = Object.freeze({ percent: 0.256, bytes: 1536e3, "duration:h": 1.5, "duration:s": 3725 });
439
+ var TOP_COUNTS = Object.freeze([3, 5, 10]);
440
+ function moveTopic(view, zone, index, count, labels, name, type, defaults) {
441
+ const note = (z) => ({ step: "moved", field: name, zone: z });
442
+ const choices = ZONES.filter((z) => z !== zone).map((z) => ({ id: `move-${z}`, text: fill(labels.moveTo, { zone: labels.zones[z] }), icon: "chevronRight", closes: true, change: () => ({ view: moveField(view, zone, index, z, void 0, { type, defaults: z === "values" ? defaults : void 0 }), note: note(z) }) }));
443
+ if (zone !== "filters" && index > 0) {
444
+ choices.push({ id: "move-left", text: labels.moveLeft, icon: "chevronRight", closes: true, change: () => ({ view: reorder(view, zone, index, index - 1), note: { step: "reordered", zone } }) });
445
+ }
446
+ if (zone !== "filters" && index < count - 1) {
447
+ choices.push({ id: "move-right", text: labels.moveRight, icon: "chevronRight", closes: true, change: () => ({ view: reorder(view, zone, index, index + 1), note: { step: "reordered", zone } }) });
448
+ }
449
+ return { id: "move", title: labels.moveToTitle, kind: "menu", icon: "swap", groups: [{ choices }] };
450
+ }
451
+ function axisTopics({ view, zone, index, field, types, labels, locale, state, defaultsOf, encoded }) {
452
+ const source = sourceOf(view, field);
453
+ const name = fieldLabel2(field, labels.core);
454
+ const sourceType = types.get(source.toLowerCase());
455
+ const date = sourceType === "date";
456
+ const grouping = groupingOf(view, field);
457
+ const sort = sortOf(view, field);
458
+ const number = (x) => x.toLocaleString(locale, { maximumFractionDigits: 6 });
459
+ const measures = withMeasure(measureChoices(view, (f) => types.get(f.toLowerCase())), sort?.by === "value" ? sort.value : null);
460
+ const hostOrder = source === field ? defaultsOf?.(source)?.order : void 0;
461
+ const hosted = Array.isArray(hostOrder) && hostOrder.length > 0;
462
+ const customItems = sort?.by === "custom" ? sort.items : hosted ? hostOrder : null;
463
+ const isSort = (by, order, ref) => sort ? sort.by === by && sort.order === order && (by !== "value" || sameRef(sort.value, ref)) : by === "label" && order === "asc";
464
+ const sortChoice = (id, text, by, order, ref, icon) => ({
465
+ id: `sort-${id}`,
466
+ text,
467
+ icon,
468
+ checked: isSort(by, order, ref),
469
+ change: () => {
470
+ const spec = by === "value" ? { by, order, value: ref } : by === "custom" ? { by, order, items: [...customItems] } : { by, order };
471
+ return { view: setSort(view, field, sortEntry(spec, hosted)), note: { step: "sort", field: name } };
472
+ }
473
+ });
474
+ const byValue = measures.flatMap((m, i) => {
475
+ const value = refLabel(view, m, labels);
476
+ return [sortChoice(`value-desc-${i}`, fill(labels.sortValueDesc, { value }), "value", "desc", m, "sortDesc"), sortChoice(`value-asc-${i}`, fill(labels.sortValueAsc, { value }), "value", "asc", m, "sortAsc")];
477
+ });
478
+ if (customItems) {
479
+ byValue.push(sortChoice("custom", labels.sortCustom, "custom", "asc", null, "sortAsc"), sortChoice("custom-desc", labels.sortCustomDesc, "custom", "desc", null, "sortDesc"));
480
+ }
481
+ const otherSort = sort && sort.by !== "label" ? sortText(view, sort, labels) : null;
482
+ const topics = [
383
483
  {
384
- className: "pk-inline-form",
385
- onSubmit: (e) => {
386
- e.preventDefault();
387
- if (top && count.trim() === "") {
388
- onApply(null);
389
- return;
390
- }
391
- setTried(true);
392
- if (counted.value !== null) {
393
- onApply({ count: counted.value, bottom, by: choices[by] });
484
+ id: "sort",
485
+ title: labels.sort,
486
+ kind: "segmented",
487
+ icon: "sortAsc",
488
+ // a sort by a value (or a custom order) is said here too: the segments then show none
489
+ state: otherSort,
490
+ changed: Boolean(otherSort),
491
+ groups: [{ choices: [sortChoice("label-asc", date ? labels.sortOldestShort : labels.sortLabelAsc, "label", "asc", null), sortChoice("label-desc", date ? labels.sortNewestShort : labels.sortLabelDesc, "label", "desc", null)] }]
492
+ },
493
+ // one value: largest and smallest first right here; more: a level of their own
494
+ { id: "sortValue", title: labels.sortByValue, kind: byValue.length <= 2 ? "inline" : "menu", icon: "sortDesc", state: otherSort, changed: Boolean(otherSort), groups: [{ choices: byValue }] },
495
+ filterTopic({ view, field, labels, locale, state, encoded })
496
+ ];
497
+ if (date) {
498
+ const regroup = (unit2) => () => {
499
+ const sourceName = fieldLabel2(source, labels.core);
500
+ const grouped = unit2 ? groupingName(sourceName, unit2, labels) : null;
501
+ return { view: groupField(view, field, unit2, { name: grouped ?? void 0 }).view, note: { step: "group", field: sourceName } };
502
+ };
503
+ 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) });
504
+ topics.push({
505
+ id: "group",
506
+ title: labels.groupTopic,
507
+ kind: "menu",
508
+ icon: "date",
509
+ state: grouping ? labels.units[grouping.by] ?? grouping.by : labels.groupNoneShort,
510
+ changed: Boolean(grouping),
511
+ groups: [
512
+ { title: labels.groupTimeline, choices: CATALOG3.timelineUnits.map(unit) },
513
+ { title: labels.groupCyclic, choices: CATALOG3.cyclicUnits.map(unit) },
514
+ { choices: [{ id: "group-none", text: labels.groupNone, checked: !grouping, closes: true, change: regroup(null) }] }
515
+ ]
516
+ });
517
+ } else if (sourceType === "number") {
518
+ const bins = grouping?.by === "bin" ? grouping : null;
519
+ topics.push({ id: "bins", title: labels.bins, kind: "panel", icon: "number", state: bins ? fill(labels.binsState, { size: number(bins.size), start: number(bins.origin ?? 0) }) : labels.off, changed: Boolean(bins) });
520
+ }
521
+ const top = filtersOf(view, field, ["top"])[0];
522
+ const topBy = top?.by ?? measureChoices(view, (f) => types.get(f.toLowerCase()))[0];
523
+ topics.push({
524
+ id: "top",
525
+ title: labels.topN,
526
+ kind: "panel",
527
+ icon: "top",
528
+ state: top ? topText(view, top, labels, locale) : labels.off,
529
+ changed: Boolean(top),
530
+ // Top 3, Top 5, Top 10 are found ("top 5", "5") and apply at once from the search
531
+ searchExtra: TOP_COUNTS.map((n) => ({
532
+ id: `top-${n}`,
533
+ text: fill(labels.topBadge, { count: n.toLocaleString(locale) }),
534
+ choice: { id: `top-${n}`, text: fill(labels.topBadge, { count: n.toLocaleString(locale) }), checked: Boolean(top && !top.bottom && top.count === n), change: () => ({ view: setTopFilter(view, field, { count: n, bottom: false, by: topBy }, top), note: { step: "top", field: name } }) }
535
+ }))
536
+ });
537
+ topics.push(moveTopic(view, zone, index, view[zone].length, labels, name, sourceType, defaultsOf?.(field)));
538
+ return topics;
539
+ }
540
+ var NUMBER_TYPED = /\d+/;
541
+ function filterTopic({ view, field, labels, locale, state, encoded }) {
542
+ const name = fieldLabel2(field, labels.core);
543
+ const note = { step: "filter", field: name };
544
+ const filtered = filterState(view, field, state, labels, locale);
545
+ const fk = encoded ? ruleKind(encoded, view, field) : null;
546
+ const timeZone = encoded?.timeZone ?? "UTC";
547
+ const capital2 = (text) => text.charAt(0).toLocaleUpperCase(locale) + text.slice(1);
548
+ const searchFor = fk?.quick ? (query) => {
549
+ const n = Number(NUMBER_TYPED.exec(query)?.[0]);
550
+ if (!Number.isSafeInteger(n) || n < 1) {
551
+ return [];
552
+ }
553
+ const units = n > CATALOG3.relativeMaxCount ? [] : fk.months ? ["year", "month"] : ["year"];
554
+ const anchor = filtersOf(view, field, ["relative"])[0]?.anchor;
555
+ const span = dateSpan(encoded, sourceOf(view, field));
556
+ const ranges = units.map((unit) => {
557
+ const text = capital2(relativeText({ unit, count: n, anchor }, labels, locale, timeZone, void 0, span));
558
+ return { id: `quick-${unit}-${n}`, text, choice: { id: `quick-${unit}-${n}`, text, change: () => ({ view: setQuickRange(view, field, { unit, count: n, anchor }), note }) } };
559
+ });
560
+ const keyed = fk.item === "group" && n >= 1e3 && n <= 9999 && view.derived.some((d) => d.name.toLowerCase() === field.toLowerCase() && d.by === "year");
561
+ if (!keyed) {
562
+ return ranges;
563
+ }
564
+ const compares = [">=", "<=", "<", ">"].map((op) => {
565
+ const entry = { field, type: "compare", op, value: n };
566
+ const text = capital2(fill(labels.compareShort[op], { value: String(n) }));
567
+ return { id: `compare-${op}-${n}`, text, choice: { id: `compare-${op}-${n}`, text, change: () => ({ view: setRule(view, field, null, entry), note }) } };
568
+ });
569
+ return [...compares, ...ranges];
570
+ } : void 0;
571
+ return {
572
+ id: "filter",
573
+ title: labels.filterTopic,
574
+ kind: "panel",
575
+ icon: "filter",
576
+ state: filtered ?? labels.filterAll,
577
+ changed: filtered !== null,
578
+ keywords: labels.filterKeywords,
579
+ // the rules are found by their names, and open the level on them
580
+ searchExtra: [
581
+ { id: "open-filter-rules", text: labels.rulesTitle, focus: "conditions" },
582
+ { id: "open-filter-text", text: labels.addRuleName, focus: "conditions" },
583
+ { id: "open-filter-value", text: labels.addRuleTotal, focus: "conditions" }
584
+ ],
585
+ searchFor
586
+ };
587
+ }
588
+ function filterZoneTopics({ view, index, field, types, labels, locale, state, encoded }) {
589
+ const type = types.get(sourceOf(view, field).toLowerCase());
590
+ return [filterTopic({ view, field, labels, locale, state, encoded }), moveTopic(view, "filters", index, filterZoneFields(view).length, labels, fieldLabel2(field, labels.core), type)];
591
+ }
592
+ function topText(view, top, labels, locale) {
593
+ const by = top.by ?? (view.values?.[0] ? { field: view.values[0].field ?? null, agg: view.values[0].agg } : null);
594
+ return `${fill(top.bottom ? labels.bottomBadge : labels.topBadge, { count: top.count.toLocaleString(locale) })} ${fill(labels.by, { value: refLabel(view, by, labels) })}`;
595
+ }
596
+ function formatLabel(format, labels, locale) {
597
+ if (Object.hasOwn(labels.formats, format)) {
598
+ return labels.formats[format];
599
+ }
600
+ const decimals = /^number:(\d+)$/.exec(format);
601
+ if (decimals) {
602
+ return plural(labels.formatDecimals, Number(decimals[1]), { lang: labels.lang, locale });
603
+ }
604
+ const kind = format.split(":")[0];
605
+ return Object.hasOwn(labels.formats, kind) ? labels.formats[kind] : format;
606
+ }
607
+ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }) {
608
+ const spec = view.values[index];
609
+ const type = spec.field ? types.get(spec.field.toLowerCase()) ?? "string" : "number";
610
+ const defaults = spec.field ? defaultsOf?.(spec.field) : void 0;
611
+ const name = valueLabel(spec, labels);
612
+ const set = (patch) => () => ({ view: updateValue(view, index, patch, { defaults }), note: { step: "value", field: name } });
613
+ const aggs = spec.field ? aggregatorsFor(type) : ["count"];
614
+ const agg = (a) => ({ id: `agg-${a}`, text: labels.core.aggregators[a] ?? a, checked: spec.agg === a, closes: true, change: set({ agg: a }) });
615
+ const rare = aggs.filter((a) => !CATALOG3.commonAggregators.includes(a));
616
+ const topics = [
617
+ {
618
+ id: "summarize",
619
+ title: labels.aggregation,
620
+ kind: "menu",
621
+ icon: "sigma",
622
+ state: labels.core.aggregators[spec.agg] ?? spec.agg,
623
+ groups: [{ choices: CATALOG3.commonAggregators.filter((a) => aggs.includes(a)).map(agg) }, ...rare.length ? [{ title: labels.moreStatistics, choices: rare.map(agg) }] : []]
624
+ }
625
+ ];
626
+ if (numericResult(spec, type)) {
627
+ const showAs = (s) => {
628
+ const text = labels.showAsNames[s] ?? s;
629
+ 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" } }) };
630
+ };
631
+ const along = spec.showAs && CATALOG3.showAsAlongAxis.includes(spec.showAs.type) ? spec.showAs : null;
632
+ topics.push({
633
+ id: "showAs",
634
+ title: labels.showAs,
635
+ kind: "menu",
636
+ info: "showAs",
637
+ icon: "table",
638
+ state: spec.showAs ? labels.showAsNames[spec.showAs.type] ?? spec.showAs.type : labels.showAsNone,
639
+ changed: Boolean(spec.showAs),
640
+ groups: [
641
+ { choices: [{ id: "showas-none", text: labels.showAsNone, checked: !spec.showAs, change: set({ showAs: null }) }, ...COMMON_SHOW_AS.map(showAs)] },
642
+ { title: labels.moreCalculations, choices: CATALOG3.showAs.filter((s) => !COMMON_SHOW_AS.includes(s)).map(showAs) },
643
+ ...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 } }) })) }] : []
644
+ ]
645
+ });
646
+ const example = (f) => formatter(f, { locale })(Object.hasOwn(EXAMPLE, f) ? EXAMPLE[f] : 1234.5);
647
+ const format = (f) => ({ id: `format-${f}`, text: labels.formats[f] ?? f, hint: example(f), checked: spec.format === f, change: set({ format: f }) });
648
+ const formatName = spec.format ? formatLabel(spec.format, labels, locale) : labels.formatAuto;
649
+ const offered = !spec.format || FORMAT_CHOICES.includes(spec.format) || MORE_FORMATS.includes(spec.format);
650
+ topics.push({
651
+ id: "format",
652
+ title: labels.format,
653
+ kind: "menu",
654
+ icon: "number",
655
+ state: formatName,
656
+ changed: Boolean(spec.format) && spec.format !== defaults?.format,
657
+ groups: [
658
+ {
659
+ choices: [
660
+ ...offered ? [] : [{ id: "format-current", text: formatName, checked: true, change: set({ format: spec.format }) }],
661
+ { id: "format-auto", text: labels.formatAuto, checked: !spec.format, change: set({ format: null }) },
662
+ ...FORMAT_CHOICES.map(format)
663
+ ]
664
+ },
665
+ { title: labels.moreFormats, choices: MORE_FORMATS.map(format) }
666
+ ]
667
+ });
668
+ const ownOf = (type2) => {
669
+ const same2 = (v) => v.agg === spec.agg && (v.field ?? null) === (spec.field ?? null);
670
+ for (const v of [view, ...[...earlier?.() ?? []].reverse()]) {
671
+ const c = (v.values ?? []).find(same2)?.conditional;
672
+ if (c?.type === type2) {
673
+ return c;
394
674
  }
395
675
  }
676
+ return type2 === "colorScale" ? { type: type2 } : { type: type2, color: null };
677
+ };
678
+ const highlight = (id, text, type2) => {
679
+ const checked = (spec.conditional?.type ?? null) === type2;
680
+ return { id, text, checked, change: checked ? () => null : set({ conditional: type2 ? ownOf(type2) : null }) };
681
+ };
682
+ topics.push({
683
+ id: "highlight",
684
+ title: labels.conditional,
685
+ kind: "segmented",
686
+ icon: "sparkle",
687
+ changed: Boolean(spec.conditional),
688
+ groups: [
689
+ {
690
+ // the one checked changes nothing; another brings back the value's own colours of that kind
691
+ choices: [
692
+ highlight("cond-none", labels.conditionalNone, null),
693
+ highlight("cond-colorScale", labels.colorScale, "colorScale"),
694
+ highlight("cond-dataBar", labels.dataBar, "dataBar")
695
+ ]
696
+ }
697
+ ]
698
+ });
699
+ }
700
+ topics.push({ id: "name", title: labels.rename, kind: "panel", icon: "text", state: name, changed: Boolean(spec.label), keywords: labels.nameKeywords });
701
+ topics.push(moveTopic(view, "values", index, view.values.length, labels, name, type));
702
+ return topics;
703
+ }
704
+ function optionTopics({ view, labels, folding, tips, explanations, act }) {
705
+ const help = [];
706
+ if (tips.controls) {
707
+ help.push({ id: "show-tips", text: labels.showTips, checkbox: true, checked: tips.on, run: () => act.tipsOn(!tips.on) });
708
+ }
709
+ if (explanations) {
710
+ help.push({ id: "show-explanations", text: labels.showSettingInfo, checkbox: true, checked: explanations.on, run: () => act.explain(!explanations.on) });
711
+ }
712
+ if (tips.controls) {
713
+ help.push({ id: "reset-tips", text: labels.resetTips, icon: "reset", disabled: !tips.canReset, run: act.resetTips });
714
+ }
715
+ return [
716
+ {
717
+ id: "totals",
718
+ title: labels.totals,
719
+ kind: "inline",
720
+ titled: true,
721
+ groups: [
722
+ {
723
+ choices: TOTALS.map((key) => {
724
+ const why = totalNoEffect(view, key);
725
+ return { id: `total-${key}`, text: labels[key], checkbox: true, checked: view.totals[key], disabled: why !== null, reason: why ? labels[why] : void 0, info: key, run: () => act.total(key, !view.totals[key]) };
726
+ })
727
+ }
728
+ ]
729
+ },
730
+ {
731
+ id: "rows",
732
+ title: labels.zones.rows,
733
+ kind: "inline",
734
+ titled: true,
735
+ groups: [
736
+ {
737
+ choices: [
738
+ { 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 },
739
+ { 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 }
740
+ ]
741
+ }
742
+ ]
743
+ },
744
+ { id: "help", title: labels.help, kind: "inline", titled: true, groups: [{ choices: help }] },
745
+ { id: "shortcuts", title: labels.shortcutsTitle, kind: "panel", icon: "info" }
746
+ ];
747
+ }
748
+ function entryIds(templates) {
749
+ const seen = /* @__PURE__ */ new Map();
750
+ return templates.map((t) => {
751
+ const key = `${t.scope}:${t.name}`;
752
+ seen.set(key, (seen.get(key) ?? 0) + 1);
753
+ return `entry:${key}:${seen.get(key)}`;
754
+ });
755
+ }
756
+ var afterDelete = (list, place) => list[place + 1] ?? list[place - 1];
757
+ function searchEntries(topics, query = "") {
758
+ return topics.flatMap((topic) => {
759
+ if (topic.hidden) {
760
+ return [];
761
+ }
762
+ const typed = query && topic.searchFor ? topic.searchFor(query) : [];
763
+ const extra = [...typed, ...topic.searchExtra ?? []].map((x) => ({ id: x.id, text: x.text, path: topic.title, topic, choice: x.choice, focus: x.focus }));
764
+ return topic.kind === "panel" ? [{ id: `open-${topic.id}`, text: topic.title, path: "", topic }, ...extra] : (topic.groups ?? []).flatMap((g) => g.choices.map((choice) => ({ id: choice.id, text: choice.text, path: [topic.title, g.title].filter(Boolean).join(" \u203A "), topic, choice })));
765
+ });
766
+ }
767
+ var SEARCH_HITS = 8;
768
+ function searchHits(entries, query, locale) {
769
+ const lower = (s) => s.toLocaleLowerCase(locale);
770
+ const words = lower(query).split(/\s+/).filter(Boolean);
771
+ if (!words.length) {
772
+ return [];
773
+ }
774
+ const found = entries.filter((e) => {
775
+ const text = lower(`${e.text} ${e.path} ${e.topic.keywords ?? ""} ${e.choice?.keywords ?? ""}`);
776
+ return words.every((w) => text.includes(w));
777
+ });
778
+ const own = (e) => lower(e.choice?.keywords ?? "").split(/\s+/).includes(words[0]);
779
+ const rank = (e) => own(e) ? 0 : lower(e.text).startsWith(words[0]) ? 1 : 2;
780
+ return [0, 1, 2].flatMap((r) => found.filter((e) => rank(e) === r)).slice(0, SEARCH_HITS);
781
+ }
782
+ var rowName = (title, state, changed, changedWord) => `${title}${state ? `, ${state}` : ""}${changed ? changedWord : ""}`;
783
+ function stepIndex(key, at, count) {
784
+ if (count === 0) {
785
+ return null;
786
+ }
787
+ switch (key) {
788
+ case "ArrowDown":
789
+ return (at + 1) % count;
790
+ case "ArrowUp":
791
+ return at <= 0 ? count - 1 : at - 1;
792
+ case "Home":
793
+ return 0;
794
+ case "End":
795
+ return count - 1;
796
+ default:
797
+ return null;
798
+ }
799
+ }
800
+ function typeAheadIndex(texts, at, typed, locale) {
801
+ const want = typed.toLocaleLowerCase(locale);
802
+ const from = typed.length > 1 ? at : at + 1;
803
+ for (let i = 0; i < texts.length; i++) {
804
+ const k = (Math.max(0, from) + i) % texts.length;
805
+ if (texts[k].trim().toLocaleLowerCase(locale).startsWith(want)) {
806
+ return k;
807
+ }
808
+ }
809
+ return null;
810
+ }
811
+
812
+ // src/levels.jsx
813
+ var ITEM = '[role="menuitem"], [role="menuitemradio"], [role="menuitemcheckbox"]';
814
+ function itemsOf(menu) {
815
+ return (
816
+ /** @type {HTMLElement[]} */
817
+ [...menu.querySelectorAll(ITEM)].filter((el) => el.closest('[role="menu"]') === menu && el.getClientRects().length > 0)
818
+ );
819
+ }
820
+ function openerOf(el) {
821
+ const id = el.closest(".pk-popover")?.id;
822
+ return id ? (
823
+ /** @type {HTMLElement | null} */
824
+ rootOf(el)?.querySelector(`[aria-controls="${CSS.escape(id)}"]`) ?? null
825
+ ) : null;
826
+ }
827
+ function tabLeaves(e, close) {
828
+ if (e.key !== "Tab" || e.shiftKey) {
829
+ return false;
830
+ }
831
+ const opener = openerOf(
832
+ /** @type {Element} */
833
+ e.target
834
+ );
835
+ const next = opener ? stopAfter(opener) : null;
836
+ e.preventDefault();
837
+ next?.focus();
838
+ if (opener && (!next || activeIn(next) !== next)) {
839
+ opener.focus({ preventScroll: true });
840
+ }
841
+ close();
842
+ return true;
843
+ }
844
+ function MenuList({ label, labelledBy, className, close, children, testId }) {
845
+ const ref = useRef(
846
+ /** @type {HTMLDivElement | null} */
847
+ null
848
+ );
849
+ const last = useRef(
850
+ /** @type {string | null} */
851
+ null
852
+ );
853
+ const typed = useRef({ text: "", at: 0 });
854
+ useLayoutEffect(() => {
855
+ const menu = ref.current;
856
+ if (!menu) {
857
+ return;
858
+ }
859
+ const items = itemsOf(menu);
860
+ const keep = items.find((el) => el.dataset.pkItem === last.current) ?? items.find((el) => el.hasAttribute("data-pk-start")) ?? items[0];
861
+ for (const el of items) {
862
+ el.tabIndex = el === keep ? 0 : -1;
863
+ }
864
+ });
865
+ const onFocus = (e) => {
866
+ const item = (
867
+ /** @type {HTMLElement} */
868
+ e.target.closest?.(ITEM)
869
+ );
870
+ if (item && ref.current && item.closest('[role="menu"]') === ref.current) {
871
+ last.current = /** @type {HTMLElement} */
872
+ item.dataset.pkItem ?? null;
873
+ for (const el of itemsOf(ref.current)) {
874
+ el.tabIndex = el === item ? 0 : -1;
875
+ }
876
+ }
877
+ };
878
+ const onKeyDown = (e) => {
879
+ const menu = ref.current;
880
+ if (!menu || e.target.closest('[role="menu"]') !== menu || e.altKey || e.ctrlKey || e.metaKey) {
881
+ return;
882
+ }
883
+ if (tabLeaves(e, close)) {
884
+ return;
885
+ }
886
+ const items = itemsOf(menu);
887
+ const at = items.indexOf(
888
+ /** @type {HTMLElement} */
889
+ activeIn(menu)
890
+ );
891
+ const go = (i) => {
892
+ if (i !== null && items[i]) {
893
+ e.preventDefault();
894
+ e.stopPropagation();
895
+ items[i].focus();
896
+ }
897
+ };
898
+ const seg = (
899
+ /** @type {HTMLElement} */
900
+ e.target.closest("[data-pk-seg]")
901
+ );
902
+ if (seg && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {
903
+ const own = itemsOf(menu).filter((el) => seg.contains(el));
904
+ const i = own.indexOf(
905
+ /** @type {HTMLElement} */
906
+ e.target
907
+ ) + (e.key === "ArrowRight" ? 1 : -1);
908
+ if (i >= 0 && i < own.length) {
909
+ e.preventDefault();
910
+ e.stopPropagation();
911
+ own[i].focus();
912
+ } else if (e.key === "ArrowRight") {
913
+ e.preventDefault();
914
+ e.stopPropagation();
915
+ }
916
+ return;
917
+ }
918
+ const opens = (
919
+ /** @type {HTMLElement} */
920
+ e.target.closest("[data-pk-level]")
921
+ );
922
+ if (opens && (e.key === "ArrowRight" || e.key === "Enter" || e.key === " ")) {
923
+ e.preventDefault();
924
+ e.stopPropagation();
925
+ opens.click();
926
+ return;
927
+ }
928
+ const step = stepIndex(e.key, at, items.length);
929
+ if (step !== null) {
930
+ go(step);
931
+ return;
932
+ }
933
+ if (e.key.length === 1 && e.key !== " ") {
934
+ const now = Date.now();
935
+ typed.current = { text: now - typed.current.at < 600 ? typed.current.text + e.key : e.key, at: now };
936
+ go(typeAheadIndex(items.map((el) => el.dataset.pkText ?? el.textContent ?? ""), at, typed.current.text));
937
+ }
938
+ };
939
+ 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);
940
+ }
941
+ function MenuItem({ id, text, onSelect, checked, checkbox, hint, icon, danger, testId, start, plain, label, className, disabled, reason, haspopup, level, description, current, children }) {
942
+ const role = checked === void 0 ? "menuitem" : checkbox ? "menuitemcheckbox" : "menuitemradio";
943
+ const reasonId = useId();
944
+ const describedBy = [disabled && reason ? reasonId : null, description ? `${reasonId}-d` : null].filter(Boolean).join(" ") || void 0;
945
+ return /* @__PURE__ */ React3.createElement(
946
+ "button",
947
+ {
948
+ type: "button",
949
+ role,
950
+ "aria-checked": checked === void 0 ? void 0 : checked,
951
+ "aria-label": label,
952
+ "aria-haspopup": haspopup,
953
+ "aria-disabled": disabled || void 0,
954
+ "aria-describedby": describedBy,
955
+ "aria-current": current ? "true" : void 0,
956
+ tabIndex: -1,
957
+ className: `pk-option${checked ? " pk-checked" : ""}${danger ? " pk-danger" : ""}${disabled ? " pk-disabled" : ""}${className ? ` ${className}` : ""}`,
958
+ "data-pk-option": "",
959
+ "data-pk-item": id,
960
+ "data-pk-text": plain ?? (typeof text === "string" ? text : void 0),
961
+ "data-pk-start": start ? "" : void 0,
962
+ "data-pk-level": level,
963
+ "data-testid": testId ?? id,
964
+ onClick: disabled ? void 0 : onSelect
965
+ },
966
+ /* @__PURE__ */ React3.createElement("span", { className: "pk-option-icon" }, checked || current ? /* @__PURE__ */ React3.createElement(Icon, { name: "check" }) : icon ? /* @__PURE__ */ React3.createElement(Icon, { name: (
967
+ /** @type {any} */
968
+ icon
969
+ ) }) : null),
970
+ /* @__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),
971
+ hint ? /* @__PURE__ */ React3.createElement("span", { className: "pk-item-hint" }, hint) : null,
972
+ description ? /* @__PURE__ */ React3.createElement("span", { id: `${reasonId}-d`, hidden: true }, description) : null,
973
+ children
974
+ );
975
+ }
976
+ function ChoiceItem({ choice: c, onPick, start }) {
977
+ const { explain, labels } = useContext2(HelpContext);
978
+ const text = c.info && explain && labels?.settingInfo && Object.hasOwn(labels.settingInfo, c.info) ? labels.settingInfo[c.info] : null;
979
+ 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);
980
+ if (!text && !c.actions?.length) {
981
+ return item;
982
+ }
983
+ 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: (
984
+ /** @type {any} */
985
+ a.icon
986
+ ) }))), text ? /* @__PURE__ */ React3.createElement("span", { "aria-hidden": "true" }, /* @__PURE__ */ React3.createElement(SettingInfo, { id: (
987
+ /** @type {string} */
988
+ c.info
989
+ ), name: c.text, tabIndex: -1 })) : null);
990
+ }
991
+ function TopicRow({ topic, labels, onOpen }) {
992
+ return /* @__PURE__ */ React3.createElement(
993
+ MenuItem,
994
+ {
995
+ id: `topic-${topic.id}`,
996
+ level: topic.id,
997
+ text: topic.title,
998
+ plain: topic.title,
999
+ icon: topic.icon,
1000
+ label: rowName(topic.title, topic.state, topic.changed, labels.sectionChanged),
1001
+ haspopup: topic.kind === "menu" ? "menu" : "dialog",
1002
+ className: "pk-topic-row",
1003
+ onSelect: onOpen
1004
+ },
1005
+ topic.state ? /* @__PURE__ */ React3.createElement("span", { className: "pk-topic-state", "data-testid": `topic-state-${topic.id}` }, topic.changed ? /* @__PURE__ */ React3.createElement("span", { className: "pk-section-mark", "aria-hidden": "true" }, "\u25CF ") : null, /* @__PURE__ */ React3.createElement("span", { className: "pk-badge-cut" }, topic.state)) : null,
1006
+ /* @__PURE__ */ React3.createElement(Icon, { name: "chevronRight", size: 16, className: "pk-topic-chevron" })
1007
+ );
1008
+ }
1009
+ function Groups({ topic, onPick }) {
1010
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null, (topic.groups ?? []).map((g, i) => /* @__PURE__ */ React3.createElement(Group, { key: i, menu: true, title: g.title, label: g.title ? void 0 : topic.title }, g.choices.map((c) => /* @__PURE__ */ React3.createElement(ChoiceItem, { key: c.id, choice: c, start: c.checked, onPick })))), /* @__PURE__ */ React3.createElement(TopicNote, { topic }));
1011
+ }
1012
+ function TopicNote({ topic }) {
1013
+ return topic.note ? /* @__PURE__ */ React3.createElement("p", { className: "pk-hint pk-menu-hint", role: "none", "data-testid": topic.noteId }, topic.note) : null;
1014
+ }
1015
+ function TopicFirst({ topic, labels, onPick, onOpen }) {
1016
+ if (topic.hidden) {
1017
+ return null;
1018
+ }
1019
+ if (topic.kind === "menu" || topic.kind === "panel") {
1020
+ return /* @__PURE__ */ React3.createElement(TopicRow, { topic, labels, onOpen });
1021
+ }
1022
+ const choices = topic.groups?.[0]?.choices ?? [];
1023
+ if (topic.kind === "segmented") {
1024
+ return (
1025
+ // a setting that is not the default says so in words too ("Highlight, changed")
1026
+ /* @__PURE__ */ React3.createElement("div", { role: "group", "aria-label": rowName(topic.title, topic.state, topic.changed, labels.sectionChanged), className: "pk-topic-seg", "data-pk-seg": "", "data-testid": `topic-${topic.id}` }, /* @__PURE__ */ React3.createElement("span", { className: "pk-topic-seg-title", "aria-hidden": "true" }, /* @__PURE__ */ React3.createElement("span", { className: "pk-option-icon" }, topic.icon ? /* @__PURE__ */ React3.createElement(Icon, { name: (
1027
+ /** @type {any} */
1028
+ topic.icon
1029
+ ) }) : null), topic.title, topic.changed && !topic.state ? /* @__PURE__ */ React3.createElement("span", { className: "pk-section-mark" }, " \u25CF") : null), topic.state ? /* @__PURE__ */ React3.createElement("span", { className: "pk-topic-state pk-topic-seg-state", "data-testid": `topic-state-${topic.id}` }, topic.changed ? /* @__PURE__ */ React3.createElement("span", { className: "pk-section-mark", "aria-hidden": "true" }, "\u25CF ") : null, /* @__PURE__ */ React3.createElement("span", { className: "pk-badge-cut" }, topic.state)) : null, /* @__PURE__ */ React3.createElement("span", { className: "pk-segmented pk-small" }, choices.map((c) => /* @__PURE__ */ React3.createElement("button", { key: c.id, type: "button", role: "menuitemradio", "aria-checked": Boolean(c.checked), tabIndex: -1, "data-pk-option": "", "data-pk-item": c.id, "data-pk-text": c.text, "data-testid": c.id, onClick: () => onPick(c) }, c.text))))
1030
+ );
1031
+ }
1032
+ const items = choices.map((c) => /* @__PURE__ */ React3.createElement(ChoiceItem, { key: c.id, choice: c, onPick }));
1033
+ return topic.titled ? /* @__PURE__ */ React3.createElement(Group, { menu: true, title: topic.title, testId: `topic-${topic.id}`, titleTestId: `topic-title-${topic.id}`, after: /* @__PURE__ */ React3.createElement(TopicNote, { topic }) }, items) : /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { role: "group", "aria-label": topic.title, "data-testid": `topic-${topic.id}` }, items), /* @__PURE__ */ React3.createElement(TopicNote, { topic }));
1034
+ }
1035
+ function SearchHits({ hits, labels, onPick, onOpen, close }) {
1036
+ if (!hits.length) {
1037
+ return /* @__PURE__ */ React3.createElement("p", { className: "pk-hint pk-level-nothing", role: "status", "data-testid": "menu-search-nothing" }, labels.searchNothing);
1038
+ }
1039
+ 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) })));
1040
+ }
1041
+ function LevelMenu({ name, labels, topics, close, onPick, panel, head, foot, search = false, locale, focusAgain }) {
1042
+ const [nav, setNav] = useState2(
1043
+ /** @type {{ stack: Array<{ level: string, from: string, hint?: string }>, focus: string | null }} */
1044
+ { stack: [], focus: null }
1045
+ );
1046
+ const level = nav.stack.length ? nav.stack[nav.stack.length - 1].level : null;
1047
+ const [query, setQuery] = useState2("");
1048
+ const box = useRef(
1049
+ /** @type {HTMLDivElement | null} */
1050
+ null
1051
+ );
1052
+ const titleId = useId();
1053
+ const topic = level ? topics.find((t) => t.id === level) ?? null : null;
1054
+ useLayoutEffect(() => {
1055
+ const el = box.current;
1056
+ const want = nav.focus;
1057
+ if (!el || !want) {
1058
+ return;
1059
+ }
1060
+ const at = want.indexOf(":");
1061
+ const [kind, id] = [want.slice(0, at), want.slice(at + 1)];
1062
+ const target = want === "level" ? el.querySelector(".pk-level-body [data-autofocus]") ?? el.querySelector('.pk-level-body [role="menuitemradio"][aria-checked="true"]') ?? el.querySelector(".pk-level-body :is(button, input, select):not([disabled])") ?? el.querySelector(".pk-level-back") : want === "search" ? el.querySelector(".pk-level-search input") : el.querySelector(kind === "row" ? `[data-pk-level="${CSS.escape(id)}"]` : `[data-pk-item="${CSS.escape(id)}"]`) ?? el.querySelector(ITEM);
1063
+ target?.focus({ preventScroll: true });
1064
+ target?.scrollIntoView?.({ block: "nearest" });
1065
+ }, [nav, focusAgain]);
1066
+ const open = (id, from = `row:${id}`, hint = void 0) => {
1067
+ setQuery("");
1068
+ setNav({ stack: [...nav.stack, { level: id, from, hint }], focus: "level" });
1069
+ };
1070
+ const back = (focus = void 0) => {
1071
+ const top = nav.stack[nav.stack.length - 1];
1072
+ setNav({ stack: nav.stack.slice(0, -1), focus: focus ?? top?.from ?? null });
1073
+ };
1074
+ const pick = (choice) => {
1075
+ if (choice.open) {
1076
+ choice.run?.();
1077
+ open(choice.open, choice.backTo ?? `item:${choice.id}`);
1078
+ return;
1079
+ }
1080
+ if (!choice.closes) {
1081
+ setNav({ stack: [], focus: query ? "search" : nav.stack.length ? nav.stack[0].from : `item:${choice.id}` });
1082
+ setQuery("");
1083
+ }
1084
+ onPick(choice);
1085
+ };
1086
+ const onKeyDown = (e) => {
1087
+ if (e.defaultPrevented) {
1088
+ return;
1089
+ }
1090
+ const t = (
1091
+ /** @type {HTMLElement} */
1092
+ e.target
1093
+ );
1094
+ const typing = t.matches("input:not([type=checkbox], [type=radio]), textarea, select");
1095
+ if (e.key === "/" && search && !level && !typing) {
1096
+ e.preventDefault();
1097
+ box.current?.querySelector(".pk-level-search input")?.focus();
1098
+ return;
1099
+ }
1100
+ if (!level) {
1101
+ return;
1102
+ }
1103
+ if (e.key === "Escape" || e.key === "ArrowLeft" && !typing && !t.closest("[data-pk-seg], .pk-segmented")) {
1104
+ e.preventDefault();
1105
+ e.stopPropagation();
1106
+ back();
1107
+ }
1108
+ };
1109
+ const first = () => {
1110
+ const hits = search && query.trim() ? searchHits(searchEntries(topics, query), query, locale) : null;
1111
+ 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(
1112
+ ClearInput,
1113
+ {
1114
+ type: "search",
1115
+ value: query,
1116
+ placeholder: labels.searchMenuShort,
1117
+ onChange: setQuery,
1118
+ clearLabel: labels.clearText,
1119
+ "aria-label": fill(labels.searchMenu, { name }),
1120
+ autoComplete: "off",
1121
+ "data-testid": "menu-search",
1122
+ onKeyDown: (e) => {
1123
+ if (e.key === "ArrowDown") {
1124
+ e.preventDefault();
1125
+ box.current?.querySelector(`.pk-level-first ${ITEM}`)?.focus();
1126
+ } else if (e.key === "Enter") {
1127
+ e.preventDefault();
1128
+ }
1129
+ }
1130
+ }
1131
+ )) : null, /* @__PURE__ */ React3.createElement("div", { className: "pk-level-first" }, hits ? /* @__PURE__ */ React3.createElement(SearchHits, { hits, labels, onPick: pick, 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: pick, onOpen: () => open(t.id) })), foot ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { role: "separator", className: "pk-level-sep" }), foot) : null)));
1132
+ };
1133
+ 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: pick })) : /* @__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());
1134
+ }
1135
+ function useLater(wait = 450) {
1136
+ const timer = useRef(
1137
+ /** @type {ReturnType<typeof setTimeout> | null} */
1138
+ null
1139
+ );
1140
+ const job = useRef(
1141
+ /** @type {(() => void) | null} */
1142
+ null
1143
+ );
1144
+ const cancel = () => {
1145
+ if (timer.current) {
1146
+ clearTimeout(timer.current);
1147
+ }
1148
+ timer.current = null;
1149
+ job.current = null;
1150
+ };
1151
+ const now = () => {
1152
+ const run = job.current;
1153
+ cancel();
1154
+ run?.();
1155
+ };
1156
+ const latest = useRef(now);
1157
+ useEffect(() => {
1158
+ latest.current = now;
1159
+ });
1160
+ useEffect(() => () => latest.current(), []);
1161
+ return {
1162
+ later: (fn) => {
1163
+ cancel();
1164
+ job.current = fn;
1165
+ timer.current = setTimeout(now, wait);
1166
+ },
1167
+ now,
1168
+ cancel
1169
+ };
1170
+ }
1171
+ function useAppliedText(applied, apply, wait = 450) {
1172
+ const [text, setText] = useState2(applied);
1173
+ const [seen, setSeen] = useState2(applied);
1174
+ if (applied !== seen) {
1175
+ setSeen(applied);
1176
+ if (text === seen) {
1177
+ setText(applied);
1178
+ }
1179
+ }
1180
+ const live = useRef({ text, seen, apply });
1181
+ useEffect(() => {
1182
+ live.current = { ...live.current, seen, apply };
1183
+ });
1184
+ const later = useLater(wait);
1185
+ const flush = () => {
1186
+ later.cancel();
1187
+ if (live.current.text !== live.current.seen) {
1188
+ live.current.seen = live.current.text;
1189
+ live.current.apply(live.current.text);
1190
+ }
1191
+ };
1192
+ const flushLatest = useRef(flush);
1193
+ useEffect(() => {
1194
+ flushLatest.current = flush;
1195
+ });
1196
+ useEffect(() => () => flushLatest.current(), []);
1197
+ return {
1198
+ text,
1199
+ set: (value) => {
1200
+ live.current.text = value;
1201
+ setText(value);
1202
+ if (wait > 0) {
1203
+ later.later(flush);
1204
+ }
1205
+ },
1206
+ flush,
1207
+ /** Escape: back to the text that applies; true when there was something to give back. */
1208
+ restore: () => {
1209
+ later.cancel();
1210
+ if (live.current.text === live.current.seen) {
1211
+ return false;
1212
+ }
1213
+ live.current.text = live.current.seen;
1214
+ setText(live.current.seen);
1215
+ return true;
1216
+ }
1217
+ };
1218
+ }
1219
+
1220
+ // src/menu-fields.jsx
1221
+ import React4, { useId as useId2 } from "react";
1222
+
1223
+ // src/numbers.js
1224
+ var cache = /* @__PURE__ */ new Map();
1225
+ function marks(locale) {
1226
+ let m = cache.get(locale);
1227
+ if (!m) {
1228
+ let parts;
1229
+ try {
1230
+ parts = new Intl.NumberFormat(locale).formatToParts(12345.6);
1231
+ } catch {
1232
+ parts = new Intl.NumberFormat("en-US").formatToParts(12345.6);
1233
+ }
1234
+ m = {
1235
+ decimal: parts.find((p) => p.type === "decimal")?.value ?? ".",
1236
+ group: parts.find((p) => p.type === "group")?.value ?? ","
1237
+ };
1238
+ cache.set(locale, m);
1239
+ }
1240
+ return m;
1241
+ }
1242
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1243
+ var PLAIN = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
1244
+ function parseNumber(text, locale) {
1245
+ const t = String(text ?? "").replace(/[\s\u00a0\u202f]/g, "").replace(/\u2212/g, "-");
1246
+ if (t === "") {
1247
+ return null;
1248
+ }
1249
+ const { decimal, group } = marks(locale);
1250
+ const g = /[\s\u00a0\u202f]/.test(group) ? "" : escape(group);
1251
+ const d = escape(decimal);
1252
+ const grouped = g ? `\\d{1,3}(?:${g}\\d{3})+` : "(?!)";
1253
+ const local = new RegExp(`^([+-]?)(${grouped}|\\d+)?(?:${d}(\\d+))?$`);
1254
+ const match = local.exec(t);
1255
+ if (match && (match[2] !== void 0 || match[3] !== void 0)) {
1256
+ const whole = (match[2] ?? "0").split(group).join("");
1257
+ const n = Number(`${match[1]}${whole}${match[3] !== void 0 ? `.${match[3]}` : ""}`);
1258
+ return Number.isFinite(n) ? n : null;
1259
+ }
1260
+ if (PLAIN.test(t)) {
1261
+ const n = Number(t);
1262
+ return Number.isFinite(n) ? n : null;
1263
+ }
1264
+ return null;
1265
+ }
1266
+ function numberText(n, locale) {
1267
+ if (typeof n !== "number" || !Number.isFinite(n)) {
1268
+ return "";
1269
+ }
1270
+ try {
1271
+ return n.toLocaleString(locale, { useGrouping: false, maximumFractionDigits: 20 });
1272
+ } catch {
1273
+ return String(n);
1274
+ }
1275
+ }
1276
+
1277
+ // src/menu-fields.jsx
1278
+ function readNumber(text, { kind = "number", required = true, tried = false, max, labels, locale }) {
1279
+ const value = parseNumber(text, locale);
1280
+ if (max !== void 0 && value !== null && Number.isInteger(value) && value > max) {
1281
+ return { value: null, problem: fill(labels.countMax, { max: max.toLocaleString(locale) }) };
1282
+ }
1283
+ const ok = value !== null && (kind === "number" || (kind === "size" ? value > 0 : Number.isInteger(value) && value >= 1));
1284
+ const say = () => kind === "count" ? labels.countInvalid : fill(kind === "size" ? labels.sizeInvalid : labels.numberInvalid, { example: (kind === "size" ? 0.5 : 1234.5).toLocaleString(locale) });
1285
+ if (text.trim() === "") {
1286
+ return { value: null, problem: required && tried ? say() : null };
1287
+ }
1288
+ return ok ? { value, problem: null } : { value: null, problem: say() };
1289
+ }
1290
+ function NumberField({ value, onChange, problem, label, testId, className = "pk-field-label", shown, shownClass, onKeyDown, onBlur, onFocus, autoFocus }) {
1291
+ const id = useId2();
1292
+ const name = useFormName();
1293
+ return /* @__PURE__ */ React4.createElement(React4.Fragment, null, /* @__PURE__ */ React4.createElement("label", { className }, shown ? /* @__PURE__ */ React4.createElement("span", { className: shownClass }, shown) : /* @__PURE__ */ React4.createElement("span", { className: "pk-sr" }, label), /* @__PURE__ */ React4.createElement(
1294
+ "input",
1295
+ {
1296
+ type: "text",
1297
+ name,
1298
+ inputMode: "decimal",
1299
+ autoComplete: "off",
1300
+ spellCheck: false,
1301
+ value,
1302
+ onChange: (e) => onChange(e.target.value),
1303
+ onKeyDown,
1304
+ onBlur,
1305
+ onFocus,
1306
+ "aria-label": label,
1307
+ "aria-invalid": problem ? true : void 0,
1308
+ "aria-describedby": problem ? id : void 0,
1309
+ "data-autofocus": autoFocus ? "" : void 0,
1310
+ "data-testid": testId
1311
+ }
1312
+ )), problem ? /* @__PURE__ */ React4.createElement("p", { id, className: "pk-form-problem", "data-testid": `${testId}-problem` }, problem) : null);
1313
+ }
1314
+ var fieldKeys = ({ now, restore, back }) => (e) => {
1315
+ if (e.key === "Enter") {
1316
+ e.preventDefault();
1317
+ now();
1318
+ } else if (e.key === "Escape") {
1319
+ e.preventDefault();
1320
+ e.stopPropagation();
1321
+ if (!restore()) {
1322
+ back();
1323
+ }
1324
+ }
1325
+ };
1326
+ function MeasurePick({ choices, names, index, onChange, label, prefix, testId }) {
1327
+ const name = useFormName();
1328
+ if (choices.length < 2) {
1329
+ return /* @__PURE__ */ React4.createElement("span", { className: "pk-by", "data-testid": testId }, prefix ? `${prefix} ${names[0]}` : names[0]);
1330
+ }
1331
+ return /* @__PURE__ */ React4.createElement("label", { className: "pk-field-label pk-by-pick" }, prefix ? /* @__PURE__ */ React4.createElement("span", null, prefix) : /* @__PURE__ */ React4.createElement("span", { className: "pk-sr" }, label), /* @__PURE__ */ React4.createElement("select", { name, value: index, onChange: (e) => onChange(Number(e.target.value)), "aria-label": label, "data-testid": testId }, choices.map((c, i) => /* @__PURE__ */ React4.createElement("option", { key: `${c.field}:${c.agg}`, value: i }, names[i]))));
1332
+ }
1333
+ var choiceIndex = (choices, ref) => Math.max(0, choices.findIndex((c) => sameRef(c, ref)));
1334
+ function measuresOf(view, types, labels, ref) {
1335
+ const choices = withMeasure(measureChoices(view, (f) => types.get(f.toLowerCase())), ref);
1336
+ return { choices, names: choices.map((c) => refLabel(view, c, labels)) };
1337
+ }
1338
+
1339
+ // src/filter-level.jsx
1340
+ var twin = (op) => op === "between" || op === "notBetween";
1341
+ var capital = (text, locale) => text.charAt(0).toLocaleUpperCase(locale) + text.slice(1);
1342
+ var rulesKeyOf = (rules) => JSON.stringify(rules, (_k, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : 1)) : v);
1343
+ var rowKind = (f) => f.type === "value" ? "total" : f.type === "label" ? "name" : "item";
1344
+ var REACH = Object.freeze({ year: 10, month: 24, day: 90 });
1345
+ var PICKER_MIN = 13;
1346
+ var MS_PER_DAY = 864e5;
1347
+ function nounOf(fk, labels) {
1348
+ const unit = fk.unit;
1349
+ const key = unit === null ? fk.item === "number" ? "value" : fk.item === "date" ? "date" : "item" : unit === "bin" ? "range" : unit === "day" ? "day" : unit.replace(/^year(.)/, (_m, c) => c.toLowerCase());
1350
+ return Object.hasOwn(labels.nouns, key) ? labels.nouns[key] : labels.nouns.item;
1351
+ }
1352
+ function rowsIn(range, column, counts) {
1353
+ const from = Date.parse(`${range.from}T00:00Z`);
1354
+ const to = Date.parse(`${range.to}T00:00Z`) + MS_PER_DAY;
1355
+ let rows = 0;
1356
+ column.dict.forEach((v, code) => {
1357
+ if (typeof v === "number" && v >= from && v < to) {
1358
+ rows += counts[code];
1359
+ }
1360
+ });
1361
+ return rows;
1362
+ }
1363
+ function countsOf(column) {
1364
+ const counts = new Float64Array(column.dict.length);
1365
+ for (let i = 0; i < column.codes.length; i++) {
1366
+ if (column.codes[i] >= 0) {
1367
+ counts[column.codes[i]]++;
1368
+ }
1369
+ }
1370
+ return counts;
1371
+ }
1372
+ function yearsOf(column, counts) {
1373
+ const rows = /* @__PURE__ */ new Map();
1374
+ column.dict.forEach((v, code) => {
1375
+ if (typeof v === "number") {
1376
+ const y = new Date(v).getUTCFullYear();
1377
+ rows.set(y, (rows.get(y) ?? 0) + counts[code]);
1378
+ }
1379
+ });
1380
+ return [...rows.entries()].sort((a, b) => a[0] - b[0]).map(([year, n]) => ({ year, rows: n }));
1381
+ }
1382
+ function LeftOut({ out, row, searching, labels, locale }) {
1383
+ const [open, setOpen] = useState3(false);
1384
+ const id = useId3();
1385
+ const shown = open || searching;
1386
+ const list = useRef2(
1387
+ /** @type {HTMLUListElement | null} */
1388
+ null
1389
+ );
1390
+ useEffect2(() => {
1391
+ if (open) {
1392
+ list.current?.firstElementChild?.scrollIntoView?.({ block: "nearest" });
1393
+ }
1394
+ }, [open]);
1395
+ return /* @__PURE__ */ React5.createElement("li", { className: "pk-values-tail" }, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-tail-toggle", "aria-expanded": shown, "aria-controls": id, onClick: () => setOpen(!shown), "data-testid": "tail-toggle" }, /* @__PURE__ */ React5.createElement(Icon, { name: shown ? "chevronDown" : "chevronRight", size: 14 }), /* @__PURE__ */ React5.createElement("span", null, fill(plural(labels.tailOut, out.length, { lang: labels.lang, locale }), { count: out.length.toLocaleString(locale) }))), shown ? /* @__PURE__ */ React5.createElement("ul", { ref: list, id, role: "list", className: "pk-tail-list", "data-testid": "tail-list" }, out.slice(0, FILTER_LIST_MAX).map(row)) : null);
1396
+ }
1397
+ function Section2({ id, title, state, open, onToggle, action, children }) {
1398
+ const bodyId = useId3();
1399
+ return /* @__PURE__ */ React5.createElement("section", { className: "pk-fsection", "data-testid": `fsection-${id}` }, /* @__PURE__ */ React5.createElement("div", { className: "pk-fsection-head" }, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-fsection-toggle", "aria-expanded": open, "aria-controls": bodyId, onClick: onToggle, "data-testid": `section-${id}` }, /* @__PURE__ */ React5.createElement(Icon, { name: open ? "chevronDown" : "chevronRight", size: 16 }), /* @__PURE__ */ React5.createElement("span", { className: "pk-fsection-title" }, title), state ? /* @__PURE__ */ React5.createElement("span", { className: "pk-fsection-state" }, state) : null), action), open ? /* @__PURE__ */ React5.createElement("div", { className: "pk-fsection-body", id: bodyId, "data-testid": `${id}-body` }, children) : null);
1400
+ }
1401
+ function Summary({ ctx, state }) {
1402
+ const { labels, locale, view, field } = ctx;
1403
+ const { shown, total, noun, unpicked, byQuick, byRules, byTotals, rows, rowsAll, span, yearsText, empty, quickWords } = state;
1404
+ const number = (n) => n.toLocaleString(locale);
1405
+ const lang = { lang: labels.lang, locale };
1406
+ const head = shown === 0 ? labels.summaryNone : shown === total ? fill(labels.summaryAll, { total: number(total), noun: plural(noun, total, lang) }) : fill(labels.summarySome, { shown: number(shown), total: number(total), noun: plural(noun, total, lang) });
1407
+ const why = [];
1408
+ if (shown === 0 && empty) {
1409
+ why.push(empty);
1410
+ } else {
1411
+ if (unpicked) {
1412
+ why.push(fill(labels.summaryPicks, { count: number(unpicked) }));
1413
+ }
1414
+ if (byQuick) {
1415
+ why.push(fill(labels.summaryQuick, { count: number(byQuick), quick: quickWords }));
1416
+ }
1417
+ if (byRules) {
1418
+ why.push(fill(plural(labels.summaryRules, state.itemRules, lang), { items: number(byRules) }));
1419
+ }
1420
+ if (byTotals) {
1421
+ why.push(fill(plural(labels.summaryTotals, state.totalRules, lang), { items: number(byTotals) }));
1422
+ }
1423
+ }
1424
+ const meta = [fill(labels.summaryRows, { rows: number(rows), total: number(rowsAll) })];
1425
+ if (span) {
1426
+ meta.push(fill(labels.summaryData, { range: `${dayText(isoDay(span.min), locale)} \u2013 ${dayText(isoDay(span.max), locale)}` }));
1427
+ }
1428
+ if (yearsText) {
1429
+ meta.push(yearsText);
1430
+ }
1431
+ return /* @__PURE__ */ React5.createElement("div", { className: "pk-filter-summary" }, /* @__PURE__ */ React5.createElement("div", { className: `pk-summary-card${shown === 0 ? " pk-summary-empty" : ""}`, role: "status", "data-testid": "filter-summary" }, /* @__PURE__ */ React5.createElement("p", { className: "pk-summary-head", "data-testid": "filter-summary-head" }, head), /* @__PURE__ */ React5.createElement("p", { className: "pk-summary-why", "data-testid": "filter-summary-why" }, why.length ? why.join(" \xB7 ") : state.rules ? labels.summaryKept : quickWords ? fill(labels.summaryQuickOnly, { quick: quickWords }) : labels.summaryOk), /* @__PURE__ */ React5.createElement("p", { className: "pk-summary-meta", "data-testid": "filter-summary-meta" }, meta.join(" \xB7 ")), /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-action pk-summary-reset", disabled: !state.canReset, onClick: () => ctx.act(resetFilter(view, field), "section-picks"), "data-testid": "filter-reset" }, labels.resetFilter)));
1432
+ }
1433
+ function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts }) {
1434
+ const { view, field, labels, locale, fk, timeZone, commit, note, back } = ctx;
1435
+ const lang = { lang: labels.lang, locale };
1436
+ const latest = span.max;
1437
+ const latestDay = isoDay(latest);
1438
+ const [now] = useState3(() => Date.now());
1439
+ const days = (unit, count) => relativeDays({ unit, count, anchor }, timeZone, now, latest);
1440
+ const reach = (unit) => {
1441
+ for (let n = 1; n <= REACH[unit]; n++) {
1442
+ const r = days(unit, n);
1443
+ if (r && r.from <= latestDay) {
1444
+ return n;
1445
+ }
1446
+ }
1447
+ return null;
1448
+ };
1449
+ const defaults = useMemo2(() => ({ year: Math.max(2, reach("year") ?? REACH.year), month: reach("month") ?? REACH.month, day: reach("day") ?? REACH.day }), [anchor, latest, timeZone]);
1450
+ const counted = { year: quick.id === "years" ? quick.count : defaults.year, month: quick.id === "months" ? quick.count : defaults.month, day: quick.id === "days" ? quick.count : defaults.day };
1451
+ const [texts, setTexts] = useState3(() => Object.fromEntries(Object.entries(counted).map(([u, n]) => [u, numberText(n, locale)])));
1452
+ const [editing, setEditing] = useState3(
1453
+ /** @type {string | null} */
1454
+ null
1455
+ );
1456
+ const quickKey = `${quick.id}:${quick.count ?? ""}:${anchor}`;
1457
+ const [seen, setSeen] = useState3(quickKey);
1458
+ if (quickKey !== seen) {
1459
+ setSeen(quickKey);
1460
+ const synced = { ...texts };
1461
+ for (const unit of CATALOG4.relativeUnits) {
1462
+ if (unit !== editing) {
1463
+ synced[unit] = numberText(counted[unit], locale);
1464
+ }
1465
+ }
1466
+ setTexts(synced);
1467
+ }
1468
+ const later = useLater();
1469
+ const group = useId3();
1470
+ const groupName = useFormName();
1471
+ const set = (range) => commit(setQuickRange(view, field, range ? { ...range, anchor } : null), note);
1472
+ const sub = (range, unit, id) => {
1473
+ const share = rangeShare(range, unit, span, locale);
1474
+ if (share?.none) {
1475
+ return null;
1476
+ }
1477
+ const period = share ? `${share.data} ` : periodText(range, unit, locale);
1478
+ const missing = share ? fill(plural(labels.noData, share.count, lang), { range: share.missing.join(", ") }) : null;
1479
+ return /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-sub", id: subId(id) }, /* @__PURE__ */ React5.createElement("span", null, period, missing ? /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-missing" }, "(", missing, ")") : null), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-rows" }, fill(labels.quickRows, { rows: rowsIn(range, column, counts).toLocaleString(locale) })));
1480
+ };
1481
+ const subId = (id) => `${group}-${id}`;
1482
+ const radio = (id, checked, onPick, name, children, sub2, described = Boolean(sub2)) => /* @__PURE__ */ React5.createElement("label", { className: "pk-radio pk-quick", key: id }, /* @__PURE__ */ React5.createElement("input", { type: "radio", name: groupName, checked, onChange: onPick, "aria-label": name, "aria-describedby": described ? subId(id) : void 0, "data-autofocus": checked && ctx.hint !== "conditions" ? "" : void 0, "data-testid": `quick-${id}` }), children, sub2);
1483
+ const hidden = [];
1484
+ const rows = [radio("all", quick.id === "all" || quick.id === "custom", () => set(null), labels.filterAll, /* @__PURE__ */ React5.createElement("span", null, labels.filterAll), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-sub", id: subId("all") }, /* @__PURE__ */ React5.createElement("span", null, `${dayText(isoDay(span.min), locale)}\u2013${dayText(latestDay, locale)}`), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-rows" }, fill(labels.quickRows, { rows: column.codes.length.toLocaleString(locale) }))))];
1485
+ const thisYear = days("year", 1);
1486
+ const yearWords = capital(labels.relative.year, locale);
1487
+ if (thisYear && sub(thisYear, "year", "thisYear")) {
1488
+ rows.push(radio("thisYear", quick.id === "thisYear", () => set({ unit: "year", count: 1 }), yearWords, /* @__PURE__ */ React5.createElement("span", null, yearWords), sub(thisYear, "year", "thisYear")));
1489
+ } else if (thisYear) {
1490
+ hidden.push(`${yearWords} (${periodText(thisYear, "year", locale)})`);
1491
+ }
1492
+ for (
1493
+ const unit of
1494
+ /** @type {const} */
1495
+ ["year", "month", "day"]
1496
+ ) {
1497
+ if (unit === "month" && !fk.months || unit === "day" && !fk.days) {
1498
+ continue;
1499
+ }
1500
+ const read = readNumber(texts[unit], { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale });
1501
+ const n = read.value;
1502
+ const id = `${unit}s`;
1503
+ const shown = n ?? counted[unit];
1504
+ const forms = Object.fromEntries(Object.entries(labels.quickLast[unit]).map(([k, v]) => [k, String(v).replace("{count}", "{n}")]));
1505
+ const words = plural(forms, shown, lang);
1506
+ const [before, after] = words.split("{n}");
1507
+ const range = days(unit, shown);
1508
+ const line = range ? sub(range, unit, id) : null;
1509
+ if (!line) {
1510
+ if (quick.id !== id) {
1511
+ hidden.push(fill(words, { n: shown.toLocaleString(locale) }));
1512
+ continue;
1513
+ }
1514
+ }
1515
+ const pick = () => set({ unit, count: shown });
1516
+ rows.push(
1517
+ /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-row", key: unit }, radio(id, quick.id === id, pick, fill(words, { n: shown.toLocaleString(locale) }), /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, before), null, Boolean(line)), /* @__PURE__ */ React5.createElement(
1518
+ NumberField,
1519
+ {
1520
+ value: texts[unit],
1521
+ onChange: (t) => {
1522
+ setTexts({ ...texts, [unit]: t });
1523
+ later.later(() => {
1524
+ const v = readNumber(t, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale }).value;
1525
+ if (v !== null) {
1526
+ set({ unit, count: v });
1527
+ }
1528
+ });
1529
+ },
1530
+ onKeyDown: fieldKeys({
1531
+ now: later.now,
1532
+ restore: () => {
1533
+ later.cancel();
1534
+ const was = numberText(counted[unit], locale);
1535
+ if (texts[unit] === was) {
1536
+ return false;
1537
+ }
1538
+ setTexts({ ...texts, [unit]: was });
1539
+ return true;
1540
+ },
1541
+ back
1542
+ }),
1543
+ onBlur: () => {
1544
+ setEditing(null);
1545
+ later.now();
1546
+ },
1547
+ onFocus: () => setEditing(unit),
1548
+ problem: read.problem,
1549
+ label: labels.quickCount[unit],
1550
+ testId: `quick-${id}-count`,
1551
+ className: "pk-field-label pk-count-input"
1552
+ }
1553
+ ), /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, after), line)
1554
+ );
1555
+ }
1556
+ const today = new Date(relativeDays({ unit: "day", count: 1 }, timeZone, now)?.from ?? isoDay(now));
1557
+ const periodStart = fk.months ? Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1) : Date.UTC(today.getUTCFullYear(), 0, 1);
1558
+ const showAnchor = latest < periodStart;
1559
+ const anchorId = useId3();
1560
+ const anchorName = useFormName();
1561
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("div", { role: "radiogroup", "aria-label": labels.quickTitle, className: "pk-radios pk-quick-choices", "data-testid": "quick-choices" }, rows), showAnchor ? /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-anchor" }, /* @__PURE__ */ React5.createElement("label", { htmlFor: anchorId }, labels.anchorLabel), /* @__PURE__ */ React5.createElement(
1562
+ "select",
1563
+ {
1564
+ id: anchorId,
1565
+ name: anchorName,
1566
+ value: anchor,
1567
+ onChange: (e) => {
1568
+ const next = (
1569
+ /** @type {"today" | "latest"} */
1570
+ e.target.value
1571
+ );
1572
+ setAnchorLocal(next);
1573
+ if (quick.filters.length) {
1574
+ commit(setAnchor(view, field, next), note);
1575
+ }
1576
+ },
1577
+ "data-testid": "quick-anchor"
1578
+ },
1579
+ /* @__PURE__ */ React5.createElement("option", { value: "today" }, fill(labels.anchorToday, { date: dayText(isoDay(today.getTime()), locale) })),
1580
+ /* @__PURE__ */ React5.createElement("option", { value: "latest" }, fill(labels.anchorLatest, { date: dayText(latestDay, locale) }))
1581
+ )) : null, hidden.length ? /* @__PURE__ */ React5.createElement("p", { className: "pk-hint pk-quick-hidden", "data-testid": "quick-hidden" }, fill(plural(labels.quickHidden, hidden.length, lang), { choices: hidden.join(", "), latest: dayText(latestDay, locale) })) : null);
1582
+ }
1583
+ function YearsCombined({ ctx, years, on }) {
1584
+ const { view, field, labels, locale, commit, note, noun } = ctx;
1585
+ const all = years.map((y) => y.year);
1586
+ const toggle = (year) => {
1587
+ const next = on.includes(year) ? on.filter((y) => y !== year) : [...on, year].sort((a, b) => a - b);
1588
+ commit(setYearsCombined(view, field, next, all), note);
1589
+ };
1590
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("p", { className: "pk-hint pk-years-hint" }, fill(labels.yearsCombinedHint, { noun: plural(noun, 1, { lang: labels.lang, locale }) })), /* @__PURE__ */ React5.createElement("div", { className: "pk-years", role: "group", "aria-label": labels.yearsCombined, "data-testid": "years-combined" }, years.map((y) => {
1591
+ const pressed = on.includes(y.year);
1592
+ return /* @__PURE__ */ React5.createElement("button", { key: y.year, type: "button", className: "pk-year-chip", "aria-pressed": pressed, disabled: pressed && on.length === 1, onClick: () => toggle(y.year), "data-testid": `year-${y.year}` }, pressed ? /* @__PURE__ */ React5.createElement(Icon, { name: "check", size: 12 }) : null, /* @__PURE__ */ React5.createElement("span", null, String(y.year)), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-rows" }, fill(labels.quickRows, { rows: y.rows.toLocaleString(locale) })));
1593
+ })), on.length === 1 ? /* @__PURE__ */ React5.createElement("p", { className: "pk-hint" }, fill(labels.yearsCombinedOne, { year: String(on[0]) })) : null);
1594
+ }
1595
+ function ItemPicker({ items, value, onChange, label, testId, labels, locale }) {
1596
+ const [open, setOpen] = useState3(false);
1597
+ const [query, setQuery] = useState3("");
1598
+ const [active, setActive] = useState3(0);
1599
+ const anchor = useRef2(
1600
+ /** @type {HTMLButtonElement | null} */
1601
+ null
1602
+ );
1603
+ const listId = useId3();
1604
+ const searchName = useFormName();
1605
+ const q = query.trim().toLocaleLowerCase();
1606
+ const found = q ? items.filter((i) => i.label.toLocaleLowerCase().includes(q)) : items;
1607
+ const matching = found.slice(0, FILTER_LIST_MAX);
1608
+ const current = items.find((i) => String(i.value) === value);
1609
+ const show = () => {
1610
+ setQuery("");
1611
+ setActive(Math.max(0, items.findIndex((i) => String(i.value) === value)));
1612
+ setOpen(true);
1613
+ };
1614
+ const close = () => setOpen(false);
1615
+ const pick = (item) => {
1616
+ close();
1617
+ onChange(String(item.value));
1618
+ };
1619
+ const optionId = (i) => `${listId}-${i}`;
1620
+ const onKeyDown = (e) => {
1621
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1622
+ e.preventDefault();
1623
+ setActive((a) => Math.min(matching.length - 1, Math.max(0, a + (e.key === "ArrowDown" ? 1 : -1))));
1624
+ } else if (e.key === "Enter") {
1625
+ e.preventDefault();
1626
+ if (matching[active]) {
1627
+ pick(matching[active]);
1628
+ }
1629
+ } else if (e.key === "Escape") {
1630
+ e.preventDefault();
1631
+ e.stopPropagation();
1632
+ close();
1633
+ }
1634
+ };
1635
+ return /* @__PURE__ */ React5.createElement("span", { className: "pk-picker" }, /* @__PURE__ */ React5.createElement(
1636
+ "button",
1637
+ {
1638
+ ref: anchor,
1639
+ type: "button",
1640
+ className: "pk-picker-button",
1641
+ "aria-haspopup": "listbox",
1642
+ "aria-expanded": open,
1643
+ "aria-label": label,
1644
+ onClick: () => open ? close() : show(),
1645
+ onKeyDown: (e) => {
1646
+ if (!open && (e.key === "ArrowDown" || e.key === "ArrowUp")) {
1647
+ e.preventDefault();
1648
+ show();
1649
+ }
1650
+ },
1651
+ "data-testid": testId
1652
+ },
1653
+ current ? current.label : value || labels.ruleValue
1654
+ ), /* @__PURE__ */ React5.createElement(Popover, { open, anchor, onClose: close, label, className: "pk-picker-pop" }, /* @__PURE__ */ React5.createElement(
1655
+ "input",
1656
+ {
1657
+ type: "search",
1658
+ name: searchName,
1659
+ role: "combobox",
1660
+ className: "pk-picker-search",
1661
+ value: query,
1662
+ onChange: (e) => {
1663
+ setQuery(e.target.value);
1664
+ setActive(0);
1665
+ },
1666
+ onKeyDown,
1667
+ "aria-label": labels.pickerSearch,
1668
+ "aria-expanded": "true",
1669
+ "aria-controls": listId,
1670
+ "aria-activedescendant": matching[active] ? optionId(active) : void 0,
1671
+ "aria-autocomplete": "list",
1672
+ autoComplete: "off",
1673
+ placeholder: labels.pickerSearch,
1674
+ "data-autofocus": "",
1675
+ "data-testid": "picker-search"
1676
+ }
1677
+ ), /* @__PURE__ */ React5.createElement("ul", { role: "listbox", id: listId, className: "pk-picker-list", "aria-label": label, "data-testid": "picker-list" }, matching.map((item, i) => /* @__PURE__ */ React5.createElement(
1678
+ "li",
1679
+ {
1680
+ key: String(item.value),
1681
+ id: optionId(i),
1682
+ role: "option",
1683
+ "aria-selected": String(item.value) === value,
1684
+ className: `pk-picker-option${i === active ? " pk-picker-active" : ""}`,
1685
+ onMouseMove: () => setActive(i),
1686
+ onClick: () => pick(item),
1687
+ "data-testid": "picker-option"
1688
+ },
1689
+ /* @__PURE__ */ React5.createElement("span", null, item.label),
1690
+ /* @__PURE__ */ React5.createElement("span", { className: "pk-count" }, item.count.toLocaleString(locale))
1691
+ )), matching.length ? null : /* @__PURE__ */ React5.createElement("li", { className: "pk-hint pk-picker-none" }, labels.pickerNone)), /* @__PURE__ */ React5.createElement("p", { className: "pk-hint pk-picker-count", "aria-live": "polite", "data-testid": "picker-count" }, fill(labels.pickerMatch, { count: found.length.toLocaleString(locale), total: items.length.toLocaleString(locale) }))));
1692
+ }
1693
+ function ItemRule({ rule, ctx, apply, first }) {
1694
+ const { field, labels, locale, fk, items } = ctx;
1695
+ const narrow = useContext3(LayerContext).size === "narrow";
1696
+ const words = fk.dates ? labels.dateOps : labels.valueOps;
1697
+ const ops = fk.dates ? [...CATALOG4.valueOps, "last"] : CATALOG4.valueOps;
1698
+ const textOf = (v) => v === void 0 ? "" : fk.item === "number" ? numberText(v, locale) : String(v);
1699
+ const compared = rule?.type === "compare" ? rule : null;
1700
+ const ranged = rule?.type === "relative" ? rule : null;
1701
+ const [s, setS] = useState3(() => ({
1702
+ op: ranged ? "last" : compared?.op ?? ">=",
1703
+ a: textOf(compared?.value),
1704
+ b: textOf(compared?.value2),
1705
+ count: numberText(ranged?.count ?? 5, locale),
1706
+ unit: ranged?.unit ?? "year"
1707
+ }));
1708
+ const later = useLater();
1709
+ const formName = useFormName();
1710
+ 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);
1711
+ const entryOf = (x) => {
1712
+ if (x.op === "last") {
1713
+ const n = readNumber(x.count, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale }).value;
1714
+ return n !== null ? { field, type: "relative", unit: x.unit, count: n, ...ranged?.anchor === "latest" ? { anchor: "latest" } : {} } : null;
1715
+ }
1716
+ const [a, b] = [read(x.a), read(x.b)];
1717
+ return a === null || twin(x.op) && b === null ? null : { field, type: "compare", op: x.op, value: a, ...twin(x.op) ? { value2: b } : {} };
1718
+ };
1719
+ const change = (patch, wait = false) => {
1720
+ const next = { ...s, ...patch };
1721
+ setS(next);
1722
+ const run = () => {
1723
+ const entry = entryOf(next);
1724
+ if (entry) {
1725
+ apply(entry);
1726
+ }
1727
+ };
1728
+ if (wait) {
1729
+ later.later(run);
1730
+ } else {
1731
+ later.cancel();
1732
+ run();
1733
+ }
1734
+ };
1735
+ const restore = () => {
1736
+ later.cancel();
1737
+ const was = { a: textOf(compared?.value), b: textOf(compared?.value2), count: numberText(ranged?.count ?? 5, locale) };
1738
+ if (s.a === was.a && s.b === was.b && s.count === was.count) {
1739
+ return false;
1740
+ }
1741
+ setS({ ...s, ...was });
1742
+ return true;
1743
+ };
1744
+ const keys = fieldKeys({ now: later.now, restore, back: ctx.back });
1745
+ const value = (key, label2, testId) => {
1746
+ if (fk.item === "number") {
1747
+ const problem = readNumber(s[key], { required: false, labels, locale }).problem;
1748
+ return /* @__PURE__ */ React5.createElement(NumberField, { value: s[key], onChange: (t) => change({ [key]: t }, true), onKeyDown: keys, onBlur: later.now, problem, label: label2, testId, className: "pk-field-label pk-narrow-input" });
1749
+ }
1750
+ if (fk.item === "date") {
1751
+ return /* @__PURE__ */ React5.createElement("input", { type: "date", name: `${formName}-${key}`, value: s[key], onChange: (e) => change({ [key]: e.target.value }), "aria-label": label2, "data-testid": testId });
1752
+ }
1753
+ const listed = items.filter((i) => typeof i.value === "number");
1754
+ const own = s[key] !== "" && !listed.some((i) => String(i.value) === s[key]);
1755
+ if (listed.length >= PICKER_MIN && !narrow) {
1756
+ return /* @__PURE__ */ React5.createElement(ItemPicker, { items: own ? [{ value: Number(s[key]), label: s[key], count: 0 }, ...listed] : listed, value: s[key], onChange: (v) => change({ [key]: v }), label: label2, testId, labels, locale });
1757
+ }
1758
+ return /* @__PURE__ */ React5.createElement("select", { name: `${formName}-${key}`, value: s[key], onChange: (e) => change({ [key]: e.target.value }), "aria-label": label2, "data-testid": testId }, /* @__PURE__ */ React5.createElement("option", { value: "", disabled: true }, labels.ruleValue), own ? /* @__PURE__ */ React5.createElement("option", { value: s[key] }, s[key]) : null, listed.map((i) => /* @__PURE__ */ React5.createElement("option", { key: String(i.value), value: String(i.value) }, i.label)));
1759
+ };
1760
+ const label = fk.item === "date" ? labels.ruleDate : labels.ruleValue;
1761
+ const lang = { lang: labels.lang, locale };
1762
+ const counted = readNumber(s.count, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale });
1763
+ const many = counted.value ?? 2;
1764
+ 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(
1765
+ NumberField,
1766
+ {
1767
+ value: s.count,
1768
+ onChange: (t) => change({ count: t }, true),
1769
+ onKeyDown: keys,
1770
+ onBlur: later.now,
1771
+ problem: counted.problem,
1772
+ label: labels.quickCount[s.unit],
1773
+ testId: "rule-last-count",
1774
+ className: "pk-field-label pk-count-input"
1775
+ }
1776
+ ), /* @__PURE__ */ React5.createElement("select", { name: `${formName}-unit`, value: s.unit, onChange: (e) => change({ unit: e.target.value }), "aria-label": labels.ruleUnit, "data-testid": "rule-last-unit" }, CATALOG4.relativeUnits.map((u) => /* @__PURE__ */ React5.createElement("option", { key: u, value: u }, plural(labels.ruleUnits[u], many, lang))))) : /* @__PURE__ */ React5.createElement(React5.Fragment, null, value("a", label, "rule-item-value"), twin(s.op) ? /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", null, labels.valueFilterTo), value("b", `${labels.valueFilterTo} ${label}`, "rule-item-value2")) : null, s.op === "!=" || s.op === "notBetween" ? /* @__PURE__ */ React5.createElement("span", { className: "pk-hint pk-rule-note", "data-testid": "rule-blanks" }, labels.blanksOut) : null));
1777
+ }
1778
+ function TotalRule({ rule, ctx, apply, first }) {
1779
+ const { view, types, labels, locale } = ctx;
1780
+ const { choices, names } = measuresOf(view, types, labels, rule?.by);
1781
+ const [s, setS] = useState3(() => ({ by: choiceIndex(choices, rule?.by), op: rule?.op ?? ">", a: numberText(rule?.value, locale), b: numberText(rule?.value2, locale) }));
1782
+ const later = useLater();
1783
+ const formName = useFormName();
1784
+ const change = (patch, wait = false) => {
1785
+ const next = { ...s, ...patch };
1786
+ setS(next);
1787
+ const run = () => {
1788
+ const [a, b] = [parseNumber(next.a, locale), parseNumber(next.b, locale)];
1789
+ if (a !== null && (!twin(next.op) || b !== null)) {
1790
+ const by = choices[next.by];
1791
+ apply({ field: ctx.field, type: "value", by: { field: by.field, agg: by.agg }, op: next.op, value: a, ...twin(next.op) ? { value2: b } : {} });
1792
+ }
1793
+ };
1794
+ if (wait) {
1795
+ later.later(run);
1796
+ } else {
1797
+ later.cancel();
1798
+ run();
1799
+ }
1800
+ };
1801
+ const restore = () => {
1802
+ later.cancel();
1803
+ const was = { a: numberText(rule?.value, locale), b: numberText(rule?.value2, locale) };
1804
+ if (s.a === was.a && s.b === was.b) {
1805
+ return false;
1806
+ }
1807
+ setS({ ...s, ...was });
1808
+ return true;
1809
+ };
1810
+ const keys = fieldKeys({ now: later.now, restore, back: ctx.back });
1811
+ const number = (key, label, testId, shown) => /* @__PURE__ */ React5.createElement(NumberField, { value: s[key], onChange: (t) => change({ [key]: t }, true), onKeyDown: keys, onBlur: later.now, problem: readNumber(s[key], { required: false, labels, locale }).problem, label, shown, testId, className: "pk-field-label pk-narrow-input" });
1812
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-subject pk-rule-lead" }, fill(labels.ruleWhose, { field: fieldLabel3(ctx.field, labels.core) })), /* @__PURE__ */ React5.createElement(MeasurePick, { choices, names, index: s.by, onChange: (i) => change({ by: i }), label: labels.valueFilterBy, testId: "value-filter-by" }), /* @__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": "value-filter-op" }, CATALOG4.valueOps.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, labels.valueOps[o] ?? o))), number("a", labels.valueFilterNumber, "value-filter-number"), twin(s.op) ? number("b", `${labels.valueFilterTo} ${labels.valueFilterNumber}`, "value-filter-number2", labels.valueFilterTo) : null);
1813
+ }
1814
+ function NameRule({ rule, ctx, apply, first }) {
1815
+ const { field, labels } = ctx;
1816
+ const [op, setOp] = useState3(rule?.op ?? "contains");
1817
+ const send = (o, value) => {
1818
+ if (value !== "") {
1819
+ apply({ field, type: "label", op: o, value });
1820
+ }
1821
+ };
1822
+ const text = useAppliedText(rule?.value ?? "", (value) => send(op, value));
1823
+ const opName = useFormName();
1824
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-subject" }, labels.ruleName), /* @__PURE__ */ React5.createElement(
1825
+ "select",
1826
+ {
1827
+ className: "pk-rule-op",
1828
+ name: opName,
1829
+ value: op,
1830
+ onChange: (e) => {
1831
+ setOp(e.target.value);
1832
+ send(e.target.value, text.text);
1833
+ },
1834
+ "aria-label": labels.condition,
1835
+ "data-autofocus": first ? "" : void 0,
1836
+ "data-testid": "filter-condition-op"
1837
+ },
1838
+ CATALOG4.labelOps.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))
1839
+ ), /* @__PURE__ */ React5.createElement(
1840
+ ClearInput,
1841
+ {
1842
+ type: "text",
1843
+ value: text.text,
1844
+ onChange: text.set,
1845
+ onBlur: text.flush,
1846
+ onKeyDown: fieldKeys({ now: text.flush, restore: text.restore, back: ctx.back }),
1847
+ onClear: () => text.set(""),
1848
+ clearLabel: labels.clearText,
1849
+ "aria-label": labels.conditionValue,
1850
+ placeholder: labels.conditionValue,
1851
+ maxLength: 1e3,
1852
+ "data-testid": "filter-condition-text"
1853
+ }
1854
+ ));
1855
+ }
1856
+ var ROWS = { item: ItemRule, total: TotalRule, name: NameRule };
1857
+ function RuleEditor({ ctx, rules, focusFirst, quickLine, results }) {
1858
+ const { view, field, labels, locale, commit, note, fk, nameKind, noun } = ctx;
1859
+ const { explain } = useContext3(HelpContext);
1860
+ const lang = { lang: labels.lang, locale };
1861
+ const [draft, setDraft] = useState3(
1862
+ /** @type {"item" | "total" | "name" | null} */
1863
+ null
1864
+ );
1865
+ const [info, setInfo] = useState3(
1866
+ /** @type {number | null} */
1867
+ null
1868
+ );
1869
+ const [gen, setGen] = useState3(0);
1870
+ const rulesKey = rulesKeyOf(rules);
1871
+ const [seen, setSeen] = useState3(rulesKey);
1872
+ const [own, setOwn] = useState3(
1873
+ /** @type {string | null} */
1874
+ null
1875
+ );
1876
+ if (rulesKey !== seen) {
1877
+ setSeen(rulesKey);
1878
+ if (rulesKey !== own) {
1879
+ setGen(gen + 1);
1880
+ setDraft(null);
1881
+ }
1882
+ }
1883
+ const box = useRef2(
1884
+ /** @type {HTMLFieldSetElement | null} */
1885
+ null
1886
+ );
1887
+ const focusAdd = useRef2(false);
1888
+ useEffect2(() => {
1889
+ if (focusAdd.current) {
1890
+ focusAdd.current = false;
1891
+ box.current?.querySelector(".pk-rule-adds button:not([disabled])")?.focus();
1892
+ }
1893
+ }, [gen]);
1894
+ useEffect2(() => {
1895
+ if (draft) {
1896
+ const row2 = (
1897
+ /** @type {HTMLElement | null | undefined} */
1898
+ box.current?.querySelector(".pk-rule:last-child")
1899
+ );
1900
+ row2?.querySelector("[data-autofocus]")?.focus({ preventScroll: true });
1901
+ row2?.scrollIntoView?.({ block: "nearest" });
1902
+ const scroller = row2?.closest(".pk-level-body");
1903
+ if (row2 && scroller) {
1904
+ const over = row2.getBoundingClientRect().bottom - scroller.getBoundingClientRect().bottom;
1905
+ if (over > 0) {
1906
+ scroller.scrollTop += Math.ceil(over);
1907
+ }
1908
+ }
1909
+ }
1910
+ }, [draft]);
1911
+ const kinds = (
1912
+ /** @type {Array<"item" | "total" | "name">} */
1913
+ ["item", "total", "name"].filter((k) => k === "item" ? Boolean(fk.item) : k === "name" ? Boolean(nameKind) : true)
1914
+ );
1915
+ const count = rules.length + (draft ? 1 : 0);
1916
+ const full = count >= RULES_MAX || view.filters.length >= LIMITS.filters;
1917
+ const addText = { item: fill(labels.addRuleItem, { field: fieldLabel3(field, labels.core) }), total: labels.addRuleTotal, name: labels.addRuleName };
1918
+ const infoText = (rule, kind) => {
1919
+ const one = plural(noun, 1, lang);
1920
+ if (kind === "total") {
1921
+ const by = rule?.by ?? measuresOf(view, ctx.types, labels, void 0).choices[0];
1922
+ return fill(labels.ruleInfo.total, { noun: one, nouns: plural(noun, 2, lang), measure: refLabel(view, by, labels), scope: ctx.scope });
1923
+ }
1924
+ if (kind === "name") {
1925
+ return fill(labels.ruleInfo.name, { noun: one });
1926
+ }
1927
+ return fill(labels.ruleInfo[fk.item === "group" ? fk.cyclic ? "cyclic" : "group" : fk.item ?? "group"], { noun: one });
1928
+ };
1929
+ const row = (rule, kind, i) => {
1930
+ const Row = ROWS[kind];
1931
+ const apply = (entry) => {
1932
+ const next = setRule(view, field, rule, entry);
1933
+ setOwn(rulesKeyOf(filtersOf(next, field, RULE_TYPES).filter((f) => !ctx.quickFilters.includes(f))));
1934
+ if (!rule) {
1935
+ setDraft(null);
1936
+ }
1937
+ commit(next, note);
1938
+ };
1939
+ const remove = () => {
1940
+ focusAdd.current = true;
1941
+ if (rule) {
1942
+ commit(setRule(view, field, rule, null), note);
1943
+ } else {
1944
+ setDraft(null);
1945
+ setGen(gen + 1);
1946
+ }
1947
+ };
1948
+ const result = rule ? results.get(rule) : null;
1949
+ const open = info === i;
1950
+ const infoId = `${gen}-${i}`;
1951
+ return /* @__PURE__ */ React5.createElement("li", { key: `${gen}:${i}`, className: "pk-rule", "data-testid": "rule", "data-kind": kind }, i > 0 || quickLine ? /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-and" }, labels.ruleAnd) : null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-body" }, /* @__PURE__ */ React5.createElement(Row, { rule, ctx, apply, first: focusFirst && i === 0 || !rule && draft !== null })), /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-tools" }, explain ? /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-icon-btn pk-rule-info", "aria-expanded": open, "aria-controls": open ? infoId : void 0, onClick: () => setInfo(open ? null : i), "aria-label": labels.explainRule, title: labels.explainRule, "data-testid": "rule-info" }, /* @__PURE__ */ React5.createElement(Icon, { name: "info", size: 14 })) : null, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-icon-btn pk-rule-remove", onClick: remove, "aria-label": labels.removeRule, title: labels.removeRule, "data-testid": "rule-remove" }, /* @__PURE__ */ React5.createElement(Icon, { name: "x", size: 14 }))), /* @__PURE__ */ React5.createElement("p", { className: `pk-hint pk-rule-result${result && result.kept === 0 ? " pk-rule-result-empty" : ""}`, "data-testid": "rule-result" }, result ? result.text : labels.ruleIncomplete), open ? /* @__PURE__ */ React5.createElement("p", { className: "pk-rule-info-text", id: infoId, "data-testid": "rule-info-text" }, infoText(rule, kind)) : null);
1952
+ };
1953
+ return /* @__PURE__ */ React5.createElement("fieldset", { ref: box, className: "pk-condition pk-rules", "data-testid": "rules" }, /* @__PURE__ */ React5.createElement("legend", { className: "pk-sr" }, labels.rulesTitle), /* @__PURE__ */ React5.createElement("p", { className: "pk-hint" }, fill(count || quickLine ? labels.rulesKeep : labels.rulesNone, { noun: plural(noun, 2, lang) })), count || quickLine ? /* @__PURE__ */ React5.createElement("ul", { className: "pk-rule-list", role: "list" }, quickLine ? /* @__PURE__ */ React5.createElement("li", { className: "pk-rule pk-rule-quick", "data-testid": "rule-quick" }, /* @__PURE__ */ React5.createElement("span", null, fill(labels.quickLine, { text: quickLine })), /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-action", onClick: ctx.focusQuick, "data-testid": "rule-quick-change" }, labels.changeAbove)) : null, [...rules.map((r, i) => row(r, rowKind(r), i)), ...draft ? [row(null, draft, rules.length)] : []]) : null, /* @__PURE__ */ React5.createElement("div", { className: "pk-rule-adds", role: "group", "aria-label": labels.addRule }, kinds.map((k, i) => /* @__PURE__ */ React5.createElement(
1954
+ "button",
1955
+ {
1956
+ key: k,
1957
+ type: "button",
1958
+ className: "pk-btn pk-small-btn",
1959
+ disabled: full,
1960
+ onClick: () => setDraft(k),
1961
+ "data-autofocus": focusFirst && !count && i === 0 ? "" : void 0,
1962
+ "data-testid": `rule-add-${k}`
1963
+ },
1964
+ /* @__PURE__ */ React5.createElement(Icon, { name: "plus", size: 14 }),
1965
+ /* @__PURE__ */ React5.createElement("span", { className: "pk-btn-text" }, addText[k])
1966
+ ))), full ? /* @__PURE__ */ React5.createElement("p", { className: "pk-hint" }, fill(labels.rulesFull, { max: RULES_MAX })) : null);
1967
+ }
1968
+ var without = (view, field, types) => view.filters.filter((f) => !(typeof f.field === "string" && f.field.toLowerCase() === field.toLowerCase() && types.includes(f.type)));
1969
+ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back, hint }) {
1970
+ const info = useMemo2(() => fieldItems2(encoded, field, { view, locale, labels: labels.core }), [encoded, field, view, locale, labels]);
1971
+ const narrow = useContext3(LayerContext).size === "narrow";
1972
+ const fk = useMemo2(() => ruleKind(encoded, view, field), [encoded, view, field]);
1973
+ const source = sourceOf(view, field);
1974
+ const column = fk.dates ? encoded.column(source) : null;
1975
+ const span = useMemo2(() => fk.dates ? dateSpan(encoded, source) : null, [encoded, fk.dates, source]);
1976
+ const counts = useMemo2(() => column ? countsOf(column) : null, [column]);
1977
+ const years = useMemo2(() => fk.cyclic && column && counts ? yearsOf(column, counts) : [], [fk.cyclic, column, counts]);
1978
+ const quick = quickChoice(view, field, fk, years.map((y) => y.year));
1979
+ const [anchorLocal, setAnchorLocal] = useState3(
1980
+ /** @type {"today" | "latest" | null} */
1981
+ null
1982
+ );
1983
+ const anchor = (
1984
+ /** @type {"today" | "latest"} */
1985
+ quick.anchor ?? anchorLocal ?? "today"
1986
+ );
1987
+ const [openQuick, setOpenQuick] = useState3(true);
1988
+ const [openPicks, setOpenPicks] = useState3(
1989
+ /** @type {boolean | null} */
1990
+ null
1991
+ );
1992
+ const [openRules, setOpenRules] = useState3(
1993
+ /** @type {boolean | null} */
1994
+ hint === "conditions" ? true : null
1995
+ );
1996
+ const box = useRef2(
1997
+ /** @type {HTMLDivElement | null} */
1998
+ null
1999
+ );
2000
+ const rulesAll = filtersOf(view, field, RULE_TYPES);
2001
+ const rules = rulesAll.filter((f) => !quick.filters.includes(f));
2002
+ const itemRules = rules.filter((f) => f.type !== "value");
2003
+ const totalRules = rules.filter((f) => f.type === "value");
2004
+ const anyRule = rules.length > 0 || quick.filters.length > 0;
2005
+ const hadRule = useRef2(anyRule);
2006
+ const byHand = useRef2(false);
2007
+ const lost = useRef2(false);
2008
+ const refocus = () => {
2009
+ if (!lost.current) {
2010
+ return;
2011
+ }
2012
+ const active = box.current ? activeIn(box.current) : null;
2013
+ if (!active || !active.isConnected || !box.current?.contains(active) || active instanceof HTMLButtonElement && active.disabled) {
2014
+ box.current?.querySelector('[data-testid="section-rules"]')?.focus();
2015
+ }
2016
+ lost.current = false;
2017
+ };
2018
+ useEffect2(refocus);
2019
+ useEffect2(() => {
2020
+ if (hadRule.current !== anyRule) {
2021
+ hadRule.current = anyRule;
2022
+ if (byHand.current) {
2023
+ byHand.current = false;
2024
+ } else {
2025
+ setOpenRules(anyRule);
2026
+ setOpenPicks(!anyRule);
2027
+ }
2028
+ lost.current = true;
2029
+ setTimeout(refocus, 100);
2030
+ }
2031
+ }, [anyRule]);
2032
+ const [goQuick, setGoQuick] = useState3(0);
2033
+ useEffect2(() => {
2034
+ if (goQuick) {
2035
+ const target = (
2036
+ /** @type {HTMLElement | null | undefined} */
2037
+ box.current?.querySelector('[data-testid="quick-choices"] input:checked, [data-testid="years-combined"] [aria-pressed="true"]:not(:disabled)') ?? box.current?.querySelector('[data-testid="years-combined"] button:not(:disabled)')
2038
+ );
2039
+ target?.scrollIntoView?.({ block: "center" });
2040
+ target?.focus({ preventScroll: true });
2041
+ }
2042
+ }, [goQuick]);
2043
+ const timeZone = encoded.timeZone;
2044
+ const noun = nounOf(fk, labels);
2045
+ const lang = { lang: labels.lang, locale };
2046
+ const keyOfView = JSON.stringify(view);
2047
+ const totals = useMemo2(() => {
2048
+ if (!info) {
2049
+ return null;
2050
+ }
2051
+ const base = without(view, field, ["value", "top"]);
2052
+ const by = totalRules[0]?.by ?? measuresOf(view, types, labels, void 0).choices[0];
2053
+ const all2 = itemTotals(encoded, view, field, by, [...base, ...totalRules]);
2054
+ const perRule = /* @__PURE__ */ new Map();
2055
+ for (const r of totalRules) {
2056
+ const plain = itemTotals(encoded, view, field, r.by, base);
2057
+ const kept2 = itemTotals(encoded, view, field, r.by, [...base, r]);
2058
+ perRule.set(r, { totals: plain.totals, kept: kept2.totals.size });
2059
+ }
2060
+ return { shown: all2.totals, rows: all2.rows, perRule, by };
2061
+ }, [encoded, keyOfView, field, info]);
2062
+ const itemResults = useMemo2(() => {
2063
+ const out = /* @__PURE__ */ new Map();
2064
+ for (const r of itemRules) {
2065
+ const kept2 = fieldItems2(encoded, field, { view: { ...view, filters: [r] }, locale, labels: labels.core });
2066
+ out.set(r, kept2 ? kept2.items.filter((i) => i.kept).length : 0);
2067
+ }
2068
+ if (quick.filters.length && itemRules.length) {
2069
+ const kept2 = fieldItems2(encoded, field, { view: { ...view, filters: quick.filters }, locale, labels: labels.core });
2070
+ out.set("quick", new Set(kept2 ? kept2.items.filter((i) => !i.kept).map((i) => keyOf(i.value)) : []));
2071
+ }
2072
+ return out;
2073
+ }, [encoded, keyOfView, field, locale, labels]);
2074
+ if (!info || !totals) {
2075
+ return null;
2076
+ }
2077
+ const name = fieldLabel3(field, labels.core);
2078
+ const note = { step: "filter", field: name };
2079
+ const all = info.items.map((i) => i.value);
2080
+ const picked = selectedItems(view, field, all);
2081
+ const selected = new Set(picked.map(keyOf));
2082
+ const nameKind = conditionKind(encoded, view, field) ?? (rules.some((r) => r.type === "label") ? "text" : null);
2083
+ const labelOf = (v) => info.items.find((i) => i.value === v)?.label;
2084
+ const say = (f) => ruleText(view, f, { labels, locale, timeZone, date: fk.dates, labelOf, span });
2085
+ const number = (n) => n.toLocaleString(locale);
2086
+ const yearsOn = quick.id === "yearsCombined" && quick.years ? quick.years : years.map((y) => y.year);
2087
+ const yearsText = fk.cyclic && years.length > 1 ? yearsOn.length === 1 ? fill(labels.yearsOne, { year: String(yearsOn[0]) }) : fill(labels.yearsAll, { years: yearsOn.length === years.length || yearsOn[yearsOn.length - 1] - yearsOn[0] === yearsOn.length - 1 ? `${yearsOn[0]}\u2013${yearsOn[yearsOn.length - 1]}` : yearsOn.join(", ") }) : null;
2088
+ const quickWords = quick.id === "yearsCombined" ? yearsText : quick.filters.length ? relativeText(quick.filters[0], labels, locale, timeZone, void 0, span) : null;
2089
+ const outByQuick = (
2090
+ /** @type {Set<string> | undefined} */
2091
+ itemResults.get("quick") ?? (quick.filters.length ? new Set(info.items.filter((i) => !i.kept).map((i) => keyOf(i.value))) : /* @__PURE__ */ new Set())
2092
+ );
2093
+ const kept = info.items.filter((i) => i.kept && selected.has(keyOf(i.value)));
2094
+ const shown = totalRules.length ? kept.filter((i) => totals.shown.has(keyOf(i.value))).length : kept.length;
2095
+ const unpicked = all.length - picked.length;
2096
+ const byQuick = info.items.filter((i) => selected.has(keyOf(i.value)) && outByQuick.has(keyOf(i.value))).length;
2097
+ const byRules = info.items.filter((i) => selected.has(keyOf(i.value)) && !i.kept).length - byQuick;
2098
+ const byTotals = kept.length - shown;
2099
+ const spread = (map, by) => {
2100
+ const entries = [...map.entries()].filter(([, v]) => v !== null);
2101
+ if (!entries.length) {
2102
+ return null;
2103
+ }
2104
+ const [lo, hi] = [entries.reduce((a, e) => e[1] < a[1] ? e : a), entries.reduce((a, e) => e[1] > a[1] ? e : a)];
2105
+ const spec = view.values.find((v) => sameRef({ field: v.field ?? null, agg: v.agg }, by));
2106
+ const text = formatter2(spec?.format ?? (by.agg === "count" || by.agg === "countUnique" ? "integer" : "number"), { locale });
2107
+ const item = (k) => labelOf(JSON.parse(k)) ?? k;
2108
+ return fill(labels.totalSpread, { low: text(lo[1]), lowItem: item(lo[0]), high: text(hi[1]), highItem: item(hi[0]) });
2109
+ };
2110
+ const totalWords = (r) => {
2111
+ const measure = refLabel(view, r.by, labels);
2112
+ const op = labels.valueOps[r.op] ?? r.op;
2113
+ const num = (x) => typeof x === "number" ? x.toLocaleString(locale, { maximumFractionDigits: 6 }) : "";
2114
+ return twin(r.op) ? fill(labels.totalWordsTwo, { measure, op, from: num(Math.min(r.value, r.value2)), to: num(Math.max(r.value, r.value2)) }) : fill(labels.totalWords, { measure, op, number: num(r.value) });
2115
+ };
2116
+ let empty = null;
2117
+ if (shown === 0) {
2118
+ const total = totalRules.find((r) => totals.perRule.get(r)?.kept === 0);
2119
+ if (total) {
2120
+ empty = fill(labels.emptyTotal, { noun: plural(noun, 1, lang), rule: totalWords(total), spread: spread(totals.perRule.get(total).totals, total.by) ?? "" });
2121
+ } else if (picked.length === 0) {
2122
+ empty = labels.emptyPicks;
2123
+ } else if (byQuick + byRules > 0) {
2124
+ empty = fill(labels.emptyRules, { noun: plural(noun, 1, lang), rules: [...quickWords ? [quickWords] : [], ...itemRules.map(say)].join(labels.listAnd) });
2125
+ }
2126
+ }
2127
+ const results = /* @__PURE__ */ new Map();
2128
+ for (const r of rules) {
2129
+ if (r.type === "value") {
2130
+ const own = totals.perRule.get(r);
2131
+ const text = own.kept === 0 ? fill(labels.ruleKeepsNone, { total: number(all.length), noun: plural(noun, all.length, lang), spread: spread(own.totals, r.by) ?? "" }) : fill(labels.ruleKeeps, { kept: number(own.kept), total: number(all.length), noun: plural(noun, all.length, lang) });
2132
+ results.set(r, { kept: own.kept, text });
2133
+ } else {
2134
+ const n = (
2135
+ /** @type {number} */
2136
+ itemResults.get(r) ?? 0
2137
+ );
2138
+ results.set(r, { kept: n, text: fill(labels.ruleKeeps, { kept: number(n), total: number(all.length), noun: plural(noun, all.length, lang) }) });
2139
+ }
2140
+ }
2141
+ const others = [...view.rows, ...view.cols].filter((f) => f.toLowerCase() !== field.toLowerCase());
2142
+ const scopeParts = others.map((f) => fill(labels.scopeItems, { count: number(fieldItems2(encoded, f, { view, locale, labels: labels.core })?.items.length ?? 0), field: fieldLabel3(f, labels.core) }));
2143
+ if (span) {
2144
+ scopeParts.push(fill(labels.scopeDates, { range: `${dayText(isoDay(span.min), locale)} \u2013 ${dayText(isoDay(span.max), locale)}` }));
2145
+ }
2146
+ const scope = scopeParts.length ? scopeParts.join(labels.listAnd) : labels.scopeRows;
2147
+ const focusQuick = () => {
2148
+ setOpenQuick(true);
2149
+ setGoQuick((n) => n + 1);
2150
+ };
2151
+ const act = (next, header) => {
2152
+ commit(next, note);
2153
+ requestAnimationFrame(() => {
2154
+ const active = box.current ? activeIn(box.current) : null;
2155
+ if (!active || !active.isConnected || !box.current?.contains(active) || active instanceof HTMLButtonElement && active.disabled) {
2156
+ box.current?.querySelector(`[data-testid="${header}"]`)?.focus();
2157
+ }
2158
+ });
2159
+ };
2160
+ const ctx = { view, field, types, labels, locale, commit, note, back, fk, nameKind, timeZone, hint, items: info.items, noun, scope, quickFilters: quick.filters, focusQuick, act };
2161
+ const picksOpen = openPicks ?? !anyRule;
2162
+ const rulesOpen = openRules ?? anyRule;
2163
+ const togglePicks = () => {
2164
+ byHand.current = true;
2165
+ setOpenPicks(!picksOpen);
2166
+ if (narrow && !picksOpen) {
2167
+ setOpenRules(false);
2168
+ }
2169
+ };
2170
+ const toggleRules = () => {
2171
+ byHand.current = true;
2172
+ setOpenRules(!rulesOpen);
2173
+ if (narrow && !rulesOpen) {
2174
+ setOpenPicks(false);
2175
+ }
2176
+ };
2177
+ const summary = { shown, total: all.length, noun, unpicked, byQuick, byRules, byTotals, itemRules: itemRules.length, totalRules: totalRules.length, rows: totals.rows, rowsAll: encoded.length, span, yearsText, empty, quickWords, rules: rules.length, canReset: unpicked > 0 || anyRule };
2178
+ const outOf = (i) => i.kept === false;
2179
+ const quickSection = fk.quick && span && column && counts ? { id: "quick", title: labels.quickTitle, body: /* @__PURE__ */ React5.createElement(QuickChoices, { ctx, quick, anchor, setAnchorLocal, span, column, counts }) } : fk.cyclic && years.length > 1 && years.length <= 12 ? { id: "years", title: labels.yearsCombined, body: /* @__PURE__ */ React5.createElement(YearsCombined, { ctx, years, on: yearsOn }) } : null;
2180
+ return /* @__PURE__ */ React5.createElement("div", { ref: box, className: "pk-filter pk-filter-level" }, /* @__PURE__ */ React5.createElement(Summary, { ctx, state: summary }), quickSection ? /* @__PURE__ */ React5.createElement(Section2, { id: quickSection.id, title: quickSection.title, state: quickWords && !openQuick ? quickWords : null, open: openQuick, onToggle: () => setOpenQuick(!openQuick) }, quickSection.body) : null, /* @__PURE__ */ React5.createElement(
2181
+ Section2,
2182
+ {
2183
+ id: "picks",
2184
+ title: labels.pickItems,
2185
+ state: unpicked ? fill(labels.picksState, { picked: number(picked.length), total: number(all.length) }) : fill(labels.picksAll, { total: number(all.length) }),
2186
+ open: picksOpen,
2187
+ onToggle: togglePicks,
2188
+ action: /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-action", disabled: !unpicked, "aria-label": labels.clearPicks, onClick: () => act(setItemFilter(view, field, all, all), "section-picks"), "data-testid": "filter-clear-picks" }, labels.clear)
2189
+ },
2190
+ /* @__PURE__ */ React5.createElement(
2191
+ ValueList,
2192
+ {
2193
+ items: info.items,
2194
+ selected,
2195
+ onChange: (next) => commit(setItemFilter(view, field, all.filter((v) => next.has(keyOf(v))), all), note),
2196
+ labels,
2197
+ locale,
2198
+ autoFocus: !anyRule && !fk.quick && hint !== "conditions",
2199
+ tail: anyRule ? { isOut: outOf, render: (out, row, searching) => /* @__PURE__ */ React5.createElement(LeftOut, { out, row, searching, labels, locale }) } : void 0
2200
+ }
2201
+ )
2202
+ ), /* @__PURE__ */ React5.createElement(
2203
+ Section2,
2204
+ {
2205
+ id: "rules",
2206
+ title: labels.rulesTitle,
2207
+ state: rules.length ? /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-section-mark" }, "\u25CF"), " ", fill(plural(labels.rulesState, rules.length, lang), { count: number(rules.length) })) : labels.rulesNoneState,
2208
+ open: rulesOpen,
2209
+ onToggle: toggleRules,
2210
+ action: /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-action", disabled: !rules.length, "aria-label": labels.removeRules, onClick: () => act(removeRules(view, field, quick.filters), "section-rules"), "data-testid": "filter-remove-rules" }, labels.removeAll)
2211
+ },
2212
+ /* @__PURE__ */ React5.createElement(RuleEditor, { ctx, rules, focusFirst: hint === "conditions", quickLine: quickWords, results })
2213
+ ));
2214
+ }
2215
+
2216
+ // src/chip-menus.jsx
2217
+ function TopLevel({ view, field, types, labels, locale, commit, back }) {
2218
+ const top = filtersOf(view, field, ["top"])[0];
2219
+ const { choices, names } = measuresOf(view, types, labels, top?.by);
2220
+ const [by, setBy] = useState4(() => choiceIndex(choices, top?.by));
2221
+ const quick = top && !top.bottom && TOP_COUNTS.includes(top.count) ? top.count : null;
2222
+ const [own, setOwn] = useState4(Boolean(top) && quick === null);
2223
+ const [bottom, setBottom] = useState4(Boolean(top?.bottom));
2224
+ const [count, setCount] = useState4(numberText(top?.count ?? 10, locale));
2225
+ const later = useLater();
2226
+ const counted = readNumber(count, { kind: "count", labels, locale });
2227
+ const name = fieldLabel4(field, labels.core);
2228
+ const set = (t) => commit(setTopFilter(view, field, t, top), { step: "top", field: name });
2229
+ const applyOwn = (next) => {
2230
+ const s = { bottom, count, by, ...next };
2231
+ const n = readNumber(s.count, { kind: "count", labels, locale }).value;
2232
+ if (n !== null) {
2233
+ set({ count: n, bottom: s.bottom, by: choices[s.by] });
2234
+ }
2235
+ };
2236
+ const groupName = useFormName();
2237
+ const radio = (id, text, checked, onPick) => /* @__PURE__ */ React6.createElement("label", { className: "pk-radio" }, /* @__PURE__ */ React6.createElement("input", { type: "radio", name: groupName, checked, onChange: onPick, "data-autofocus": checked ? "" : void 0, "data-testid": `top-${id}` }), /* @__PURE__ */ React6.createElement("span", null, text));
2238
+ return /* @__PURE__ */ React6.createElement("div", { className: "pk-level-form" }, /* @__PURE__ */ React6.createElement("div", { role: "radiogroup", "aria-label": labels.topN, className: "pk-radios" }, radio("off", labels.off, !top && !own, () => {
2239
+ setOwn(false);
2240
+ set(null);
2241
+ }), TOP_COUNTS.map((n) => /* @__PURE__ */ React6.createElement(React6.Fragment, { key: n }, radio(String(n), fill(labels.topBadge, { count: n.toLocaleString(locale) }), !own && quick === n, () => {
2242
+ setOwn(false);
2243
+ set({ count: n, bottom: false, by: choices[by] });
2244
+ }))), radio("own", labels.topOwn, own, () => {
2245
+ setOwn(true);
2246
+ applyOwn({});
2247
+ })), own ? /* @__PURE__ */ React6.createElement("div", { className: "pk-inline-form" }, /* @__PURE__ */ React6.createElement("div", { className: "pk-segmented pk-small", role: "group", "aria-label": labels.topN }, [false, true].map((b) => /* @__PURE__ */ React6.createElement(
2248
+ "button",
2249
+ {
2250
+ key: String(b),
2251
+ type: "button",
2252
+ "aria-pressed": bottom === b,
2253
+ onClick: () => {
2254
+ setBottom(b);
2255
+ applyOwn({ bottom: b });
2256
+ },
2257
+ "data-testid": b ? "top-bottom" : "top-top"
396
2258
  },
397
- /* @__PURE__ */ React2.createElement("div", { className: "pk-segmented pk-small", role: "group", "aria-label": labels.topN }, /* @__PURE__ */ React2.createElement("button", { type: "button", "aria-pressed": !bottom, onClick: () => setBottom(false) }, labels.top), /* @__PURE__ */ React2.createElement("button", { type: "button", "aria-pressed": bottom, onClick: () => setBottom(true) }, labels.bottom)),
398
- /* @__PURE__ */ React2.createElement(NumberField, { value: count, onChange: setCount, problem: counted.problem, label: labels.topCount, testId: "top-count", className: "pk-field-label pk-narrow-input" }),
399
- /* @__PURE__ */ React2.createElement(MeasurePick, { choices, names, index: by, onChange: setBy, label: labels.topBy, prefix: labels.topBy, testId: "top-by" }),
400
- /* @__PURE__ */ React2.createElement("button", { type: "submit", className: "pk-btn pk-primary" }, labels.apply),
401
- /* @__PURE__ */ React2.createElement(CancelButton, { labels, onCancel, testId: "top-cancel" })
402
- );
2259
+ b ? labels.bottom : labels.top
2260
+ ))), /* @__PURE__ */ React6.createElement(
2261
+ NumberField,
2262
+ {
2263
+ value: count,
2264
+ onChange: (t) => {
2265
+ setCount(t);
2266
+ later.later(() => applyOwn({ count: t }));
2267
+ },
2268
+ onKeyDown: fieldKeys({
2269
+ now: later.now,
2270
+ restore: () => {
2271
+ later.cancel();
2272
+ const was = numberText(top?.count ?? 10, locale);
2273
+ if (count === was) {
2274
+ return false;
2275
+ }
2276
+ setCount(was);
2277
+ return true;
2278
+ },
2279
+ back
2280
+ }),
2281
+ onBlur: later.now,
2282
+ problem: counted.problem,
2283
+ label: labels.topCount,
2284
+ testId: "top-count",
2285
+ className: "pk-field-label pk-narrow-input"
2286
+ }
2287
+ )) : null, /* @__PURE__ */ React6.createElement("div", { className: "pk-inline-form" }, /* @__PURE__ */ React6.createElement(MeasurePick, { choices, names, index: by, onChange: (i) => {
2288
+ setBy(i);
2289
+ if (top) {
2290
+ set({ count: top.count, bottom: Boolean(top.bottom), by: choices[i] });
2291
+ }
2292
+ }, label: labels.topBy, prefix: labels.topBy, testId: "top-by" })));
403
2293
  }
404
- function ValueFilterForm({ condition, labels, choices, names, onApply, onCancel, locale }) {
405
- const [by, setBy] = useState(() => choiceIndex(choices, condition?.by));
406
- const [op, setOp] = useState(condition?.op ?? ">");
407
- const [first, setFirst] = useState(numberText(condition?.value, locale));
408
- const [second, setSecond] = useState(numberText(condition?.value2, locale));
409
- const [tried, setTried] = useState(false);
410
- const between = op === "between" || op === "notBetween";
411
- const a = readNumber(first, { tried, labels, locale });
412
- const b = readNumber(second, { tried, labels, locale });
413
- const ok = a.value !== null && (!between || b.value !== null);
414
- return /* @__PURE__ */ React2.createElement(
2294
+ function BinsLevel({ view, field, labels, locale, range, regroup, back }) {
2295
+ const grouping = groupingOf(view, field);
2296
+ const bins = grouping?.by === "bin" ? grouping : null;
2297
+ const [size, setSize] = useState4(numberText(bins?.size, locale));
2298
+ const [start, setStart] = useState4(numberText(bins?.origin, locale));
2299
+ const [tried, setTried] = useState4(false);
2300
+ const problemId = useId4();
2301
+ const sized = readNumber(size, { kind: "size", tried, labels, locale });
2302
+ const started = readNumber(start, { required: false, labels, locale });
2303
+ const n = sized.value;
2304
+ const s = start.trim() === "" ? 0 : started.value;
2305
+ const far = n !== null && s !== null && binProblem(n, s, range) === "far";
2306
+ const number = (x) => x.toLocaleString(locale, { maximumFractionDigits: 6 });
2307
+ return /* @__PURE__ */ React6.createElement(
415
2308
  "form",
416
2309
  {
417
- className: "pk-inline-form pk-value-filter",
2310
+ className: "pk-inline-form pk-bin-form",
418
2311
  onSubmit: (e) => {
419
2312
  e.preventDefault();
420
- if (condition && first.trim() === "" && second.trim() === "") {
421
- onApply(null);
2313
+ if (bins && size.trim() === "") {
2314
+ regroup(null);
422
2315
  return;
423
2316
  }
424
2317
  setTried(true);
425
- if (ok) {
426
- onApply({ by: choices[by], op, value: (
427
- /** @type {number} */
428
- a.value
429
- ), ...between ? { value2: (
430
- /** @type {number} */
431
- b.value
432
- ) } : {} });
2318
+ if (n !== null && s !== null && !far) {
2319
+ regroup("bin", n, s);
2320
+ }
2321
+ },
2322
+ onKeyDown: (e) => {
2323
+ if (e.key === "Escape") {
2324
+ e.preventDefault();
2325
+ e.stopPropagation();
2326
+ back();
433
2327
  }
434
2328
  }
435
2329
  },
436
- /* @__PURE__ */ React2.createElement(MeasurePick, { choices, names, index: by, onChange: setBy, label: labels.valueFilterBy, testId: "value-filter-by" }),
437
- /* @__PURE__ */ React2.createElement("label", { className: "pk-field-label" }, /* @__PURE__ */ React2.createElement("span", { className: "pk-sr" }, labels.valueFilterOp), /* @__PURE__ */ React2.createElement("select", { value: op, onChange: (e) => setOp(e.target.value), "aria-label": labels.valueFilterOp, "data-testid": "value-filter-op" }, CATALOG.valueOps.map((o) => /* @__PURE__ */ React2.createElement("option", { key: o, value: o }, labels.valueOps[o] ?? o)))),
438
- /* @__PURE__ */ React2.createElement(NumberField, { value: first, onChange: setFirst, problem: a.problem, label: labels.valueFilterNumber, testId: "value-filter-number", className: "pk-field-label pk-narrow-input" }),
439
- between ? /* @__PURE__ */ React2.createElement(NumberField, { value: second, onChange: setSecond, problem: b.problem, label: `${labels.valueFilterTo} ${labels.valueFilterNumber}`, shown: labels.valueFilterTo, shownClass: "pk-muted", testId: "value-filter-number2", className: "pk-field-label pk-narrow-input" }) : null,
440
- /* @__PURE__ */ React2.createElement("button", { type: "submit", className: "pk-btn pk-primary", "data-testid": "value-filter-apply" }, labels.apply),
441
- /* @__PURE__ */ React2.createElement(CancelButton, { labels, onCancel, testId: "value-filter-cancel" })
2330
+ /* @__PURE__ */ React6.createElement(NumberField, { value: size, onChange: setSize, problem: sized.problem, label: labels.binSize, shown: labels.binSize, testId: "bin-size", autoFocus: true }),
2331
+ /* @__PURE__ */ React6.createElement("label", { className: "pk-field-label" }, /* @__PURE__ */ React6.createElement("span", null, labels.binStart), /* @__PURE__ */ React6.createElement(ClearInput, { type: "text", inputMode: "decimal", autoComplete: "off", spellCheck: false, value: start, placeholder: "0", onChange: setStart, clearLabel: labels.clearText, "data-testid": "bin-start", "aria-invalid": far || started.problem ? true : void 0, "aria-describedby": far || started.problem ? problemId : void 0 })),
2332
+ started.problem ? /* @__PURE__ */ React6.createElement("p", { id: problemId, className: "pk-form-problem", "data-testid": "bin-start-problem" }, started.problem) : far && range && s !== null && n !== null ? /* @__PURE__ */ React6.createElement("p", { id: problemId, className: "pk-form-problem", "data-testid": "bin-problem" }, fill(labels.binStartFar, { start: number(s), min: number(range.min), max: number(range.max) })) : null,
2333
+ /* @__PURE__ */ React6.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: far, "data-testid": "bin-apply" }, labels.apply),
2334
+ bins ? /* @__PURE__ */ React6.createElement("button", { type: "button", className: "pk-btn", onClick: () => regroup(null), "data-testid": "bin-off" }, labels.binsOff) : null
442
2335
  );
443
2336
  }
444
- function CancelButton({ labels, onCancel, testId }) {
445
- return /* @__PURE__ */ React2.createElement("button", { type: "button", className: "pk-btn", onClick: onCancel, "data-testid": testId }, labels.cancel);
446
- }
447
- function Editable({ text, start, icon, labels, onRemove, testId, form }) {
448
- const [editing, setEditing] = useState(false);
449
- const box = useRef(
450
- /** @type {HTMLDivElement | null} */
451
- null
452
- );
453
- const was = useRef(false);
454
- useEffect(() => {
455
- if (editing !== was.current) {
456
- was.current = editing;
457
- box.current?.querySelector(editing ? "input, select" : "button")?.focus({ preventScroll: true });
458
- box.current?.scrollIntoView({ block: "nearest" });
2337
+ function NameLevel({ view, index, labels, commit, back }) {
2338
+ const spec = view.values[index];
2339
+ const name = valueLabel(spec, labels);
2340
+ const note = { step: "value", field: name };
2341
+ const text = useAppliedText(spec.label ?? "", (t) => commit(updateValue(view, index, { label: t.trim() || null }), note), 0);
2342
+ return /* @__PURE__ */ React6.createElement("div", { className: "pk-inline-form pk-level-form" }, /* @__PURE__ */ React6.createElement(
2343
+ ClearInput,
2344
+ {
2345
+ type: "text",
2346
+ value: text.text,
2347
+ placeholder: valueLabel({ ...spec, label: null }, labels),
2348
+ onChange: text.set,
2349
+ onBlur: text.flush,
2350
+ onKeyDown: fieldKeys({
2351
+ now: () => {
2352
+ text.flush();
2353
+ back();
2354
+ },
2355
+ restore: text.restore,
2356
+ back
2357
+ }),
2358
+ onClear: () => spec.label ? commit(updateValue(view, index, { label: null }), note) : void 0,
2359
+ clearLabel: labels.defaultName,
2360
+ "aria-label": labels.rename,
2361
+ maxLength: 200,
2362
+ "data-autofocus": "",
2363
+ "data-testid": "value-name"
459
2364
  }
460
- }, [editing]);
461
- return /* @__PURE__ */ React2.createElement("div", { ref: box, className: "pk-editable" }, editing ? form(() => setEditing(false)) : text ? /* @__PURE__ */ React2.createElement("div", { className: "pk-inline-form pk-state-line", "data-testid": `${testId}-state` }, /* @__PURE__ */ React2.createElement("span", { className: "pk-state-text" }, text), /* @__PURE__ */ React2.createElement("button", { type: "button", className: "pk-link", onClick: () => setEditing(true), "data-testid": `${testId}-change` }, labels.change), /* @__PURE__ */ React2.createElement("button", { type: "button", className: "pk-link", onClick: onRemove, "data-testid": `${testId}-remove` }, labels.removeSetting)) : /* @__PURE__ */ React2.createElement(Option, { icon, onSelect: () => setEditing(true), testId: `${testId}-open` }, start));
2365
+ ), /* @__PURE__ */ React6.createElement("p", { className: "pk-hint" }, labels.nameHint));
462
2366
  }
463
2367
  function MenuHead({ name, info, extra, labels }) {
464
- if (!info?.description && !extra) {
465
- return null;
466
- }
467
- const text = /* @__PURE__ */ React2.createElement(React2.Fragment, null, info?.description, info?.href ? /* @__PURE__ */ React2.createElement(React2.Fragment, null, " ", /* @__PURE__ */ React2.createElement("a", { href: info.href, target: "_blank", rel: "noopener noreferrer", className: "pk-learn-more" }, labels.learnMore)) : null, info?.description && extra ? /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("br", null), /* @__PURE__ */ React2.createElement("br", null)) : null, extra);
468
- return /* @__PURE__ */ React2.createElement("div", { className: "pk-section" }, /* @__PURE__ */ React2.createElement("div", { className: "pk-section-head" }, /* @__PURE__ */ React2.createElement("div", { className: "pk-section-title", "data-testid": "menu-head" }, name), /* @__PURE__ */ React2.createElement(InfoButton, { info: { description: (
2368
+ const text = /* @__PURE__ */ React6.createElement(React6.Fragment, null, info?.description, info?.href ? /* @__PURE__ */ React6.createElement(React6.Fragment, null, " ", /* @__PURE__ */ React6.createElement("a", { href: info.href, target: "_blank", rel: "noopener noreferrer", className: "pk-learn-more" }, labels.learnMore)) : null, info?.description && extra ? /* @__PURE__ */ React6.createElement(React6.Fragment, null, /* @__PURE__ */ React6.createElement("br", null), /* @__PURE__ */ React6.createElement("br", null)) : null, extra);
2369
+ return /* @__PURE__ */ React6.createElement("div", { className: "pk-level-name" }, /* @__PURE__ */ React6.createElement("span", { className: "pk-level-name-text", "data-testid": "menu-head" }, name), info?.description || extra ? /* @__PURE__ */ React6.createElement(InfoButton, { info: { description: (
469
2370
  /** @type {any} */
470
2371
  text
471
- ) }, name, labels, className: "pk-menu-info", testId: "menu-info" })));
2372
+ ) }, name, labels, className: "pk-menu-info", testId: "menu-info" }) : null);
472
2373
  }
473
- function MoveSection({ view, zone, index, count, labels, commit, close, text, type }) {
474
- return /* @__PURE__ */ React2.createElement(Section, { title: labels.move, id: "move" }, ZONES.filter((z) => z !== zone).map((z) => /* @__PURE__ */ React2.createElement(Option, { key: z, icon: ZONE_ICON[z], onSelect: () => {
475
- close();
476
- commit(moveField(view, zone, index, z, void 0, { type }), { step: "moved", field: text, zone: z });
477
- }, testId: `move-${z}` }, fill(labels.moveTo, { zone: labels.zones[z] }))), zone !== "filters" && index > 0 ? /* @__PURE__ */ React2.createElement(Option, { icon: "chevronRight", onSelect: () => {
478
- close();
479
- commit(reorder(view, zone, index, index - 1), { step: "reordered", zone });
480
- } }, labels.moveLeft) : null, zone !== "filters" && index < count - 1 ? /* @__PURE__ */ React2.createElement(Option, { icon: "chevronRight", onSelect: () => {
481
- close();
482
- commit(reorder(view, zone, index, index + 1), { step: "reordered", zone });
483
- } }, labels.moveRight) : null);
2374
+ function RemoveItem({ labels, onRemove, close }) {
2375
+ return /* @__PURE__ */ React6.createElement(
2376
+ MenuItem,
2377
+ {
2378
+ id: "menu-remove",
2379
+ text: labels.remove,
2380
+ icon: "trash",
2381
+ danger: true,
2382
+ onSelect: () => {
2383
+ close();
2384
+ onRemove();
2385
+ }
2386
+ }
2387
+ );
484
2388
  }
485
- function RemoveFoot({ labels, onRemove, close }) {
486
- return /* @__PURE__ */ React2.createElement("div", { className: "pk-menu-foot" }, /* @__PURE__ */ React2.createElement(Option, { icon: "trash", danger: true, onSelect: () => {
2389
+ var picker = (commit, close) => (choice) => {
2390
+ const next = choice.change?.();
2391
+ if (choice.closes) {
487
2392
  close();
488
- onRemove();
489
- }, testId: "menu-remove" }, labels.remove));
490
- }
491
- function AxisMenu({ view, zone, index, field, types, labels, commit, close, openFilter, chipRef, onRemove, defaultsOf, rangeOf, locale, info, state }) {
2393
+ }
2394
+ if (next) {
2395
+ commit(next.view, next.note);
2396
+ }
2397
+ };
2398
+ function AxisMenu({ view, zone, index, field, types, labels, commit, close, onRemove, defaultsOf, rangeOf, locale, info, state, encoded }) {
492
2399
  const source = sourceOf(view, field);
493
- const name = fieldLabel(field, labels.core);
494
- const sourceType = types.get(source.toLowerCase());
495
- const grouping = groupingOf(view, field);
496
- const sort = sortOf(view, field);
497
- const shown = measureChoices(view, (f) => types.get(f.toLowerCase()));
498
- const top = filtersOf(view, field, ["top"])[0];
499
- const condition = filtersOf(view, field, ["value"])[0];
500
- const pick = (ref) => {
501
- const list = withMeasure(shown, ref);
502
- return { choices: list, names: list.map((c) => refLabel(view, c, labels)) };
503
- };
504
- const { choices, names } = pick(sort?.by === "value" ? sort.value : null);
505
- const topPick = pick(top?.by);
506
- const conditionPick = pick(condition?.by);
507
- const isSort = (by, order, ref) => sort ? sort.by === by && sort.order === order && (by !== "value" || sameRef(sort.value, ref)) : by === "label" && order === "asc";
508
- const hostOrder = source === field ? defaultsOf?.(source)?.order : void 0;
509
- const customItems = sort?.by === "custom" ? sort.items : Array.isArray(hostOrder) && hostOrder.length > 0 ? hostOrder : null;
510
- const doSort = (by, order, ref) => {
511
- close();
512
- const spec = by === "value" ? { by, order, value: ref } : by === "custom" ? { by, order, items: [...customItems] } : { by, order };
513
- commit(setSort(view, field, sortEntry(spec, Array.isArray(hostOrder) && hostOrder.length > 0)), { step: "sort", field: name });
514
- };
2400
+ const topics = axisTopics({ view, zone, index, field, types, labels, locale, state, defaultsOf, encoded });
515
2401
  const regroup = (unit, size, origin) => {
516
2402
  close();
517
- const sourceName = fieldLabel(source, labels.core);
2403
+ const sourceName = fieldLabel4(source, labels.core);
518
2404
  const grouped = unit ? groupingName(sourceName, unit, labels, size) : null;
519
2405
  commit(groupField(view, field, unit, { size, origin, name: grouped ?? void 0 }).view, { step: "group", field: sourceName });
520
2406
  };
521
- const number = (x) => x.toLocaleString(locale, { maximumFractionDigits: 6 });
522
- const topText = top ? `${fill(top.bottom ? labels.bottomBadge : labels.topBadge, { count: number(top.count) })} ${fill(labels.by, { value: topPick.names[choiceIndex(topPick.choices, top.by)] })}` : null;
523
- const binsText = grouping?.by === "bin" ? fill(labels.binsState, { size: number(grouping.size), start: number(grouping.origin ?? 0) }) : null;
524
- const unitOption = (u) => /* @__PURE__ */ React2.createElement(Option, { key: u, checked: grouping?.by === u, onSelect: () => regroup(u), testId: `group-${u}`, hint: labels.unitHints[u] || void 0 }, labels.units[u] ?? u);
525
- const bins = grouping?.by === "bin" ? grouping : null;
526
- const conditions = filtersOf(view, field, ["value"]);
527
- const itemsView = { ...view, filters: view.filters.filter((f) => !conditions.includes(f)) };
528
- const filtered = hasFilter(itemsView, field);
529
- const filterLine = filtered ? filterText(itemsView, field, state, labels, locale) : null;
530
- const prefix = labels.filterIs.split("{filter}")[0];
531
- const filterState = [filterLine?.startsWith(prefix) ? filterLine.slice(prefix.length) : filterLine, condition ? valueConditionText(view, condition, labels, locale) : null].filter(Boolean).join(", ");
532
- const removeItems = () => {
533
- close();
534
- const items = new Set(filtersOf(itemsView, field, ["include", "exclude", "label"]));
535
- commit({ ...view, filters: view.filters.filter((f) => !items.has(f)) }, { step: "filter", field: name });
536
- };
537
- const setTop = (t) => {
538
- close();
539
- commit(setTopFilter(view, field, t, top), { step: "top", field: name });
540
- };
541
- return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("div", { className: "pk-menu-body" }, /* @__PURE__ */ React2.createElement(MenuHead, { name: fieldLabel(source, labels.core), info, labels }), /* @__PURE__ */ React2.createElement(Section, { title: labels.sort, id: "sort", state: sort ? sortText(view, sort, labels) : null, changed: Boolean(sort) }, /* @__PURE__ */ React2.createElement(Option, { checked: isSort("label", "asc"), icon: "sortAsc", onSelect: () => doSort("label", "asc") }, sourceType === "date" ? labels.sortOldest : labels.sortLabelAsc), /* @__PURE__ */ React2.createElement(Option, { checked: isSort("label", "desc"), icon: "sortDesc", onSelect: () => doSort("label", "desc") }, sourceType === "date" ? labels.sortNewest : labels.sortLabelDesc), choices.map((c, i) => /* @__PURE__ */ React2.createElement(React2.Fragment, { key: `${c.field}:${c.agg}` }, /* @__PURE__ */ React2.createElement(Option, { checked: isSort("value", "desc", c), icon: "sortDesc", onSelect: () => doSort("value", "desc", c), testId: `sort-value-desc-${i}` }, fill(labels.sortValueDesc, { value: names[i] })), /* @__PURE__ */ React2.createElement(Option, { checked: isSort("value", "asc", c), icon: "sortAsc", onSelect: () => doSort("value", "asc", c), testId: `sort-value-asc-${i}` }, fill(labels.sortValueAsc, { value: names[i] })))), customItems ? /* @__PURE__ */ React2.createElement(Option, { checked: isSort("custom", "asc"), icon: "sortAsc", onSelect: () => doSort("custom", "asc"), testId: "sort-custom" }, labels.sortCustom) : null, customItems ? /* @__PURE__ */ React2.createElement(Option, { checked: isSort("custom", "desc"), icon: "sortDesc", onSelect: () => doSort("custom", "desc"), testId: "sort-custom-desc" }, labels.sortCustomDesc) : null), /* @__PURE__ */ React2.createElement(Section, { title: labels.zones.filters, id: "filters", state: filterState || null, changed: Boolean(filterState) }, filtered ? /* @__PURE__ */ React2.createElement("div", { className: "pk-inline-form pk-state-line", "data-testid": "filter-state" }, /* @__PURE__ */ React2.createElement("span", { className: "pk-state-text" }, filterLine), /* @__PURE__ */ React2.createElement("button", { type: "button", className: "pk-link", onClick: removeItems, "data-testid": "remove-filter" }, labels.removeSetting)) : null, /* @__PURE__ */ React2.createElement(Option, { icon: "filter", onSelect: () => {
542
- close();
543
- openFilter(field, chipRef.current);
544
- }, testId: "open-filter" }, labels.chooseValues), /* @__PURE__ */ React2.createElement(Editable, { text: condition ? valueConditionText(view, condition, labels, locale) : null, start: labels.valueFilter, icon: "sigma", labels, onRemove: () => {
545
- close();
546
- commit(setValueFilter(view, field, null, condition), { step: "filter", field: name });
547
- }, testId: "value-filter", form: (cancel) => /* @__PURE__ */ React2.createElement(ValueFilterForm, { condition, labels, choices: conditionPick.choices, names: conditionPick.names, locale, onCancel: cancel, onApply: (c) => {
548
- close();
549
- commit(setValueFilter(view, field, c, condition), { step: "filter", field: name });
550
- } }) })), /* @__PURE__ */ React2.createElement(Section, { title: labels.topN, id: "topN", state: top ? topText : null, changed: Boolean(top) }, /* @__PURE__ */ React2.createElement(Editable, { text: top ? topText : null, start: labels.topStart, icon: "top", labels, onRemove: () => setTop(null), testId: "top", form: (cancel) => /* @__PURE__ */ React2.createElement(TopForm, { top, labels, choices: topPick.choices, names: topPick.names, locale, onCancel: cancel, onApply: setTop }) })), sourceType === "date" ? /* @__PURE__ */ React2.createElement(Section, { title: labels.groupBy, id: "groupBy", state: grouping ? labels.units[grouping.by] ?? grouping.by : null, changed: Boolean(grouping) }, /* @__PURE__ */ React2.createElement("div", { className: "pk-subtitle" }, labels.groupTimeline), /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, CATALOG.timelineUnits.map(unitOption)), /* @__PURE__ */ React2.createElement("div", { className: "pk-subtitle" }, labels.groupCyclic), /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, CATALOG.cyclicUnits.map(unitOption)), /* @__PURE__ */ React2.createElement(Option, { checked: !grouping, onSelect: () => regroup(null), testId: "group-none" }, labels.groupNone)) : null, sourceType === "number" ? /* @__PURE__ */ React2.createElement(Section, { title: labels.bins, id: "bins", state: binsText, changed: Boolean(bins) }, /* @__PURE__ */ React2.createElement(Editable, { text: binsText, start: labels.binsStart, icon: "number", labels, onRemove: () => regroup(null), testId: "bin", form: (cancel) => /* @__PURE__ */ React2.createElement(BinForm, { grouping: bins, labels, range: rangeOf?.(source) ?? null, locale, onCancel: cancel, onApply: (size, origin) => regroup("bin", size, origin), onClear: bins ? () => regroup(null) : null }) })) : null, /* @__PURE__ */ React2.createElement(MoveSection, { view, zone, index, count: view[zone].length, labels, commit, close, text: name, type: sourceType })), /* @__PURE__ */ React2.createElement(RemoveFoot, { labels, onRemove, close }));
2407
+ const panel = (id, back, hint) => id === "filter" ? /* @__PURE__ */ React6.createElement(FilterLevel, { view, field, encoded, types, labels, locale, commit, back, hint }) : id === "top" ? /* @__PURE__ */ React6.createElement(TopLevel, { view, field, types, labels, locale, commit, back }) : id === "bins" ? /* @__PURE__ */ React6.createElement(BinsLevel, { view, field, labels, locale, range: rangeOf?.(source) ?? null, regroup, back }) : null;
2408
+ const name = fieldLabel4(field, labels.core);
2409
+ return /* @__PURE__ */ React6.createElement(
2410
+ LevelMenu,
2411
+ {
2412
+ name,
2413
+ labels,
2414
+ locale,
2415
+ topics,
2416
+ close,
2417
+ onPick: picker(commit, close),
2418
+ panel,
2419
+ search: true,
2420
+ head: /* @__PURE__ */ React6.createElement(MenuHead, { name, info, labels }),
2421
+ foot: /* @__PURE__ */ React6.createElement(RemoveItem, { labels, onRemove, close })
2422
+ }
2423
+ );
551
2424
  }
552
- function ValueMenu({ view, index, types, labels, commit, close, onRemove, defaultsOf, info }) {
553
- const spec = view.values[index];
554
- const type = spec.field ? types.get(spec.field.toLowerCase()) ?? "string" : "number";
555
- const aggs = spec.field ? aggregatorsFor(type) : ["count"];
556
- const common = CATALOG.commonAggregators.filter((a) => aggs.includes(a));
557
- const rare = aggs.filter((a) => !CATALOG.commonAggregators.includes(a));
558
- const otherShowAs = CATALOG.showAs.filter((s) => !COMMON_SHOW_AS.includes(s));
559
- const numeric = numericResult(spec, type);
560
- const name = valueLabel(spec, labels);
561
- const set = (patch) => {
562
- close();
563
- commit(updateValue(view, index, patch, { defaults: spec.field ? defaultsOf?.(spec.field) : void 0 }), { step: "value", field: name });
564
- };
565
- const [rename, setRename] = useState(spec.label ?? "");
566
- const { explain } = useContext2(HelpContext);
567
- const aggOption = (a) => /* @__PURE__ */ React2.createElement(Option, { key: a, checked: spec.agg === a, onSelect: () => set({ agg: a }), testId: `agg-${a}` }, labels.core.aggregators[a] ?? a);
568
- const formatOption = (f) => /* @__PURE__ */ React2.createElement(Option, { key: f, checked: spec.format === f, onSelect: () => set({ format: f }), testId: `format-${f}` }, labels.formats[f] ?? f);
569
- const showAsOption = (s) => /* @__PURE__ */ React2.createElement(Option, { key: s, checked: spec.showAs?.type === s, onSelect: () => set({ showAs: { type: s, axis: spec.showAs?.axis ?? "rows" } }), testId: `showas-${s}` }, labels.showAsNames[s] ?? s);
570
- return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("div", { className: "pk-menu-body" }, /* @__PURE__ */ React2.createElement(MenuHead, { name, info, extra: explain ? labels.settingInfo.valuesFilter : null, labels }), /* @__PURE__ */ React2.createElement(Section, { title: labels.aggregation, id: "summarize", state: labels.core.aggregators[spec.agg] ?? spec.agg }, /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, common.map(aggOption)), rare.length ? /* @__PURE__ */ React2.createElement(More, { title: labels.moreStatistics, open: rare.includes(spec.agg) }, /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, rare.map(aggOption))) : null), numeric ? /* @__PURE__ */ React2.createElement(Section, { title: labels.showAs, id: "showAs", info: "showAs", state: spec.showAs ? labels.showAsNames[spec.showAs.type] ?? spec.showAs.type : labels.showAsNone, changed: Boolean(spec.showAs) }, /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, /* @__PURE__ */ React2.createElement(Option, { checked: !spec.showAs, onSelect: () => set({ showAs: null }), testId: "showas-none" }, labels.showAsNone), COMMON_SHOW_AS.map(showAsOption)), /* @__PURE__ */ React2.createElement(More, { title: labels.moreCalculations, open: Boolean(spec.showAs && otherShowAs.includes(spec.showAs.type)) }, /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, otherShowAs.map(showAsOption))), spec.showAs && CATALOG.showAsAlongAxis.includes(spec.showAs.type) ? /* @__PURE__ */ React2.createElement("div", { className: "pk-setting-row" }, /* @__PURE__ */ React2.createElement("div", { className: "pk-segmented pk-small", role: "group", "aria-label": labels.along }, /* @__PURE__ */ React2.createElement("span", { className: "pk-muted" }, labels.along), ["rows", "cols"].map((axis) => /* @__PURE__ */ React2.createElement("button", { key: axis, type: "button", "aria-pressed": spec.showAs.axis === axis, onClick: () => set({ showAs: { ...spec.showAs, axis } }) }, labels.zones[axis]))), /* @__PURE__ */ React2.createElement(SettingInfo, { id: "along", name: labels.along })) : null) : null, numeric ? /* @__PURE__ */ React2.createElement(Section, { title: labels.format, id: "format", state: spec.format ? labels.formats[spec.format] ?? labels.formats[spec.format.split(":")[0]] ?? spec.format : labels.formatAuto, changed: Boolean(spec.format) && spec.format !== (spec.field ? defaultsOf?.(spec.field)?.format : void 0) }, /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, /* @__PURE__ */ React2.createElement(Option, { checked: !spec.format, onSelect: () => set({ format: null }) }, labels.formatAuto), FORMAT_CHOICES.map(formatOption)), /* @__PURE__ */ React2.createElement(More, { title: labels.moreFormats, open: MORE_FORMATS.includes(spec.format ?? "") }, /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, MORE_FORMATS.map(formatOption)))) : null, numeric ? /* @__PURE__ */ React2.createElement(Section, { title: labels.conditional, id: "highlight", state: spec.conditional ? spec.conditional.type === "dataBar" ? labels.dataBar : labels.colorScale : labels.conditionalNone, changed: Boolean(spec.conditional) }, /* @__PURE__ */ React2.createElement("div", { className: "pk-choice-grid" }, /* @__PURE__ */ React2.createElement(Option, { checked: !spec.conditional, onSelect: () => set({ conditional: null }) }, labels.conditionalNone), /* @__PURE__ */ React2.createElement(Option, { checked: spec.conditional?.type === "colorScale", onSelect: () => set({ conditional: { type: "colorScale" } }), testId: "cond-colorScale" }, labels.colorScale), /* @__PURE__ */ React2.createElement(Option, { checked: spec.conditional?.type === "dataBar", onSelect: () => set({ conditional: { type: "dataBar", color: null } }), testId: "cond-dataBar" }, labels.dataBar))) : null, /* @__PURE__ */ React2.createElement(Section, { title: labels.rename }, /* @__PURE__ */ React2.createElement("form", { className: "pk-inline-form", onSubmit: (e) => {
571
- e.preventDefault();
572
- set({ label: rename.trim() || null });
573
- } }, /* @__PURE__ */ React2.createElement(
574
- ClearInput,
2425
+ function FilterMenu({ view, index, field, types, labels, commit, close, onRemove, locale, info, state, encoded }) {
2426
+ const name = fieldLabel4(field, labels.core);
2427
+ return /* @__PURE__ */ React6.createElement(
2428
+ LevelMenu,
575
2429
  {
576
- type: "text",
577
- value: rename,
578
- placeholder: valueLabel({ ...spec, label: null }, labels),
579
- onChange: setRename,
580
- onClear: () => spec.label ? commit(updateValue(view, index, { label: null }), { step: "value", field: name }) : void 0,
581
- clearLabel: labels.defaultName,
582
- "aria-label": labels.rename,
583
- maxLength: 200,
584
- "data-testid": "value-name"
2430
+ name,
2431
+ labels,
2432
+ locale,
2433
+ topics: filterZoneTopics({ view, index, field, types, labels, locale, state, encoded }),
2434
+ close,
2435
+ onPick: picker(commit, close),
2436
+ panel: (id, back, hint) => id === "filter" ? /* @__PURE__ */ React6.createElement(FilterLevel, { view, field, encoded, types, labels, locale, commit, back, hint }) : null,
2437
+ search: true,
2438
+ head: /* @__PURE__ */ React6.createElement(MenuHead, { name, info, labels }),
2439
+ foot: /* @__PURE__ */ React6.createElement(RemoveItem, { labels, onRemove, close })
585
2440
  }
586
- ), /* @__PURE__ */ React2.createElement("button", { type: "submit", className: "pk-btn pk-primary" }, labels.apply))), /* @__PURE__ */ React2.createElement(MoveSection, { view, zone: "values", index, count: view.values.length, labels, commit, close, text: name, type })), /* @__PURE__ */ React2.createElement(RemoveFoot, { labels, onRemove, close }));
2441
+ );
2442
+ }
2443
+ function ValueMenu({ view, index, types, labels, commit, close, onRemove, defaultsOf, info, earlier, locale = "en-US" }) {
2444
+ const { explain } = React6.useContext(HelpContext);
2445
+ const name = valueLabel(view.values[index], labels);
2446
+ const topics = valueTopics({ view, index, types, labels, locale, defaultsOf, earlier });
2447
+ return /* @__PURE__ */ React6.createElement(
2448
+ LevelMenu,
2449
+ {
2450
+ name,
2451
+ labels,
2452
+ locale,
2453
+ topics,
2454
+ close,
2455
+ onPick: picker(commit, close),
2456
+ panel: (id, back) => id === "name" ? /* @__PURE__ */ React6.createElement(NameLevel, { view, index, labels, commit, back }) : null,
2457
+ search: true,
2458
+ head: /* @__PURE__ */ React6.createElement(MenuHead, { name, info, extra: explain ? labels.settingInfo.valuesFilter : null, labels }),
2459
+ foot: /* @__PURE__ */ React6.createElement(RemoveItem, { labels, onRemove, close })
2460
+ }
2461
+ );
587
2462
  }
588
2463
 
589
2464
  // src/toolbar-panels.jsx
590
- import React3, { useEffect as useEffect2, useId as useId3, useRef as useRef2, useState as useState2 } from "react";
2465
+ import React7, { useEffect as useEffect3, useId as useId5, useRef as useRef3, useState as useState5 } from "react";
591
2466
  import { VIEW_FILE_LIMITS } from "pivotkit-core";
592
2467
 
593
- // src/sections.js
594
- var withoutSections = (dismissed) => dismissed.filter((id) => !isSection(id));
595
-
596
2468
  // src/share-actions.js
597
2469
  import { toViewFile, viewFileName, viewFileText } from "pivotkit-core";
598
2470
 
@@ -675,7 +2547,7 @@ async function copyText(text, container) {
675
2547
  }
676
2548
 
677
2549
  // src/version.js
678
- var VERSION = true ? "0.2.0" : "0.0.0-source";
2550
+ var VERSION = true ? "0.4.0" : "0.0.0-source";
679
2551
 
680
2552
  // src/share-actions.js
681
2553
  var here = () => typeof location !== "undefined" ? location.href : void 0;
@@ -862,7 +2734,7 @@ function storeViews(raw, change, labels, locale, keep) {
862
2734
  // src/toolbar-panels.jsx
863
2735
  function ChartTypeOptions({ view, plan, labels, onChart, close }) {
864
2736
  const current = chartTypeOf(view.chart);
865
- return CHART_TYPE_NAMES.map((p) => /* @__PURE__ */ React3.createElement(
2737
+ return CHART_TYPE_NAMES.map((p) => /* @__PURE__ */ React7.createElement(
866
2738
  Option,
867
2739
  {
868
2740
  key: p,
@@ -884,13 +2756,13 @@ var LEGENDS = ["auto", "bottom", "right", "off"];
884
2756
  var AXIS_LABELS = ["auto", "all", "nth"];
885
2757
  var GROUP_LABELS = ["auto", "on", "off"];
886
2758
  function ChartTitle({ title, labels, onDisplay }) {
887
- const [text, setText] = useState2(title ?? "");
888
- const [last, setLast] = useState2(title);
2759
+ const [text, setText] = useState5(title ?? "");
2760
+ const [last, setLast] = useState5(title);
889
2761
  if (title !== last) {
890
2762
  setLast(title);
891
2763
  setText(title ?? "");
892
2764
  }
893
- return /* @__PURE__ */ React3.createElement(
2765
+ return /* @__PURE__ */ React7.createElement(
894
2766
  "form",
895
2767
  {
896
2768
  className: "pk-inline-form",
@@ -899,7 +2771,7 @@ function ChartTitle({ title, labels, onDisplay }) {
899
2771
  onDisplay({ title: text.trim() || null });
900
2772
  }
901
2773
  },
902
- /* @__PURE__ */ React3.createElement(
2774
+ /* @__PURE__ */ React7.createElement(
903
2775
  ClearInput,
904
2776
  {
905
2777
  type: "text",
@@ -913,9 +2785,13 @@ function ChartTitle({ title, labels, onDisplay }) {
913
2785
  "data-testid": "chart-title"
914
2786
  }
915
2787
  ),
916
- /* @__PURE__ */ React3.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: (text.trim() || null) === (title ?? null) }, labels.apply)
2788
+ /* @__PURE__ */ React7.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: (text.trim() || null) === (title ?? null) }, labels.apply)
917
2789
  );
918
2790
  }
2791
+ function Sub({ title, info, children }) {
2792
+ const titleId = useId5();
2793
+ 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);
2794
+ }
919
2795
  function ChartDisplay({ view, plan, labels, onDisplay }) {
920
2796
  const chart = view.chart;
921
2797
  const drawn = plan ? plan.name : chartTypeOf(chart);
@@ -923,88 +2799,69 @@ function ChartDisplay({ view, plan, labels, onDisplay }) {
923
2799
  const axis = CHART_TYPES[drawn].axis;
924
2800
  const choices = pie ? VALUE_LABELS.slices : VALUE_LABELS.other;
925
2801
  const valueLabels = !pie && (chart.valueLabels === "percent" || chart.valueLabels === "both") ? "value" : chart.valueLabels;
926
- const changed = [
927
- [valueLabels !== "auto", labels.valueLabels],
928
- [pie && (chart.labelPosition ?? "outside") !== "outside", labels.labelPosition],
929
- [chart.legend !== "auto", labels.legend],
930
- [Boolean(chart.title), labels.chartTitle],
931
- [axis && chart.axisLabels !== "auto", labels.axisLabels],
932
- [axis && view.rows.length >= 2 && chart.groupLabels !== "auto", labels.groupLabels],
933
- [(drawn === "line" || drawn === "area") && chart.smooth, labels.smoothLines]
934
- ].flatMap(([on, name]) => on ? [name] : []);
935
- return /* @__PURE__ */ React3.createElement(Section, { title: labels.chartDisplay, id: "chartDisplay", state: changed.join(", ") || labels.formatAuto, changed: changed.length > 0 }, /* @__PURE__ */ React3.createElement("div", { className: "pk-subtitle" }, labels.valueLabels), /* @__PURE__ */ React3.createElement("div", { className: "pk-choice-grid" }, choices.map((v) => /* @__PURE__ */ React3.createElement(Option, { key: v, checked: valueLabels === v, onSelect: () => onDisplay({ valueLabels: v }), testId: `labels-${v}` }, labels.valueLabelNames[v]))), pie ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { className: "pk-subtitle pk-setting-row" }, /* @__PURE__ */ React3.createElement("span", null, labels.labelPosition), /* @__PURE__ */ React3.createElement(SettingInfo, { id: "labelPosition", name: labels.labelPosition })), /* @__PURE__ */ React3.createElement("div", { className: "pk-choice-grid" }, LABEL_POSITIONS.map((v) => /* @__PURE__ */ React3.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__ */ React3.createElement("div", { className: "pk-subtitle" }, labels.legend), /* @__PURE__ */ React3.createElement("div", { className: "pk-choice-grid" }, LEGENDS.map((v) => /* @__PURE__ */ React3.createElement(Option, { key: v, checked: chart.legend === v, onSelect: () => onDisplay({ legend: v }), testId: `legend-${v}` }, labels.legendNames[v]))), /* @__PURE__ */ React3.createElement("div", { className: "pk-subtitle" }, labels.chartTitle), /* @__PURE__ */ React3.createElement(ChartTitle, { title: chart.title, labels, onDisplay }), axis ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { className: "pk-subtitle" }, labels.axisLabels), /* @__PURE__ */ React3.createElement("div", { className: "pk-choice-grid" }, AXIS_LABELS.map((v) => /* @__PURE__ */ React3.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__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { className: "pk-subtitle pk-setting-row" }, /* @__PURE__ */ React3.createElement("span", null, labels.groupLabels), /* @__PURE__ */ React3.createElement(SettingInfo, { id: "groupLabels", name: labels.groupLabels })), /* @__PURE__ */ React3.createElement("div", { className: "pk-choice-grid" }, GROUP_LABELS.map((v) => /* @__PURE__ */ React3.createElement(Option, { key: v, checked: chart.groupLabels === v, onSelect: () => onDisplay({ groupLabels: v }), testId: `groups-${v}` }, labels.groupLabelNames[v])))) : null, drawn === "line" || drawn === "area" ? /* @__PURE__ */ React3.createElement(Switch, { checked: chart.smooth, onChange: (on) => onDisplay({ smooth: on }), testId: "chart-smooth" }, labels.smoothLines) : null);
2802
+ 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);
936
2803
  }
937
2804
  function ChartTypePanel({ view, plan, labels, onChart, onDisplay, close }) {
938
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(Section, { title: labels.chartType, id: "chartType" }, /* @__PURE__ */ React3.createElement("div", { className: "pk-choice-grid" }, /* @__PURE__ */ React3.createElement(ChartTypeOptions, { view, plan, labels, onChart, close }))), /* @__PURE__ */ React3.createElement(ChartDisplay, { view, plan, labels, onDisplay }));
2805
+ 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 }));
939
2806
  }
940
2807
  function Shortcuts({ labels, mod }) {
941
2808
  const key = (k) => k === "Mod" ? mod === "\u2318" ? "\u2318" : labels.keys.Mod : Object.hasOwn(labels.keys, k) ? labels.keys[k] : k;
942
- return /* @__PURE__ */ React3.createElement("dl", { className: "pk-shortcuts", "data-testid": "shortcuts" }, SHORTCUTS.map((s) => /* @__PURE__ */ React3.createElement("div", { key: s.text, className: "pk-shortcut" }, /* @__PURE__ */ React3.createElement("dt", null, s.keys.map((k, i) => /* @__PURE__ */ React3.createElement(React3.Fragment, { key: k }, i ? " + " : null, /* @__PURE__ */ React3.createElement("kbd", null, key(k))))), /* @__PURE__ */ React3.createElement("dd", null, labels.shortcuts[s.text]))));
2809
+ 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]))));
943
2810
  }
944
- function Switch({ checked, onChange, testId, children, disabled, reason, info, name }) {
945
- const reasonId = useId3();
946
- return /* @__PURE__ */ React3.createElement("div", { className: "pk-setting-row" }, /* @__PURE__ */ React3.createElement("label", { className: `pk-switch${disabled ? " pk-disabled" : ""}` }, /* @__PURE__ */ React3.createElement("input", { type: "checkbox", checked, disabled, onChange: (e) => onChange(e.target.checked), "aria-describedby": disabled && reason ? reasonId : void 0, "data-testid": testId }), /* @__PURE__ */ React3.createElement("span", { className: "pk-switch-track", "aria-hidden": "true" }), /* @__PURE__ */ React3.createElement("span", { className: "pk-switch-text" }, children, disabled && reason ? /* @__PURE__ */ React3.createElement("span", { id: reasonId, className: "pk-option-hint", "data-testid": testId ? `${testId}-reason` : void 0 }, reason) : null)), info ? /* @__PURE__ */ React3.createElement(SettingInfo, { id: info, name: name ?? "" }) : null);
947
- }
948
- function ResetSections({ list, change, labels }) {
949
- const rest = withoutSections(list);
950
- const [done, setDone] = useState2(false);
951
- const status = useRef2(
952
- /** @type {HTMLSpanElement | null} */
953
- null
954
- );
955
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(
956
- Option,
957
- {
958
- icon: "reset",
959
- onSelect: () => {
960
- const title = (
961
- /** @type {HTMLElement | null | undefined} */
962
- status.current?.closest(".pk-section")?.querySelector(".pk-section-toggle")
963
- );
964
- change(rest, null);
965
- title?.focus();
966
- setDone(true);
967
- },
968
- disabled: rest.length === list.length,
969
- testId: "reset-sections"
970
- },
971
- labels.resetSections
972
- ), /* @__PURE__ */ React3.createElement("span", { ref: status, className: "pk-sr", role: "status", "data-testid": "reset-sections-status" }, done ? labels.resetSectionsDone : ""));
2811
+ function Switch({ checked, onChange, testId, children }) {
2812
+ const name = useFormName();
2813
+ 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));
973
2814
  }
974
2815
  function OptionsPanel({ view, labels, onTotal, onExpand, onCollapse, close, tips, mod, folding, help }) {
975
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(Section, { title: labels.totals, id: "totals" }, TOTALS.map((key) => {
976
- const why = totalNoEffect(view, key);
977
- return /* @__PURE__ */ React3.createElement(Switch, { key, checked: view.totals[key], onChange: (on) => onTotal(key, on), disabled: why !== null, reason: why ? labels[why] : null, info: key, name: labels[key], testId: `total-${key}` }, labels[key]);
978
- })), /* @__PURE__ */ React3.createElement(Section, { title: labels.zones.rows }, /* @__PURE__ */ React3.createElement(Option, { icon: "chevronDown", onSelect: () => {
979
- close();
980
- onExpand(labels);
981
- }, disabled: !folding.canExpand, reason: folding.why.expand ? labels[folding.why.expand] : void 0, testId: "expand-all" }, labels.expandAll), /* @__PURE__ */ React3.createElement(Option, { icon: "chevronRight", onSelect: () => {
982
- close();
983
- onCollapse(labels);
984
- }, disabled: !folding.canCollapse, reason: folding.why.collapse ? labels[folding.why.collapse] : void 0, testId: "collapse-all" }, labels.collapseAll)), /* @__PURE__ */ React3.createElement(Section, { title: labels.help, id: "help" }, tips.controls ? /* @__PURE__ */ React3.createElement(Switch, { checked: tips.on, onChange: tips.onOn, testId: "show-tips" }, labels.showTips) : null, help?.explanations ? /* @__PURE__ */ React3.createElement(Switch, { checked: help.explanations.on, onChange: help.explanations.set, testId: "show-explanations" }, labels.showSettingInfo) : null, tips.controls ? /* @__PURE__ */ React3.createElement(Option, { icon: "reset", onSelect: () => tips.onReset(), disabled: !tips.canReset, testId: "reset-tips" }, labels.resetTips) : null, help?.sections ? /* @__PURE__ */ React3.createElement(ResetSections, { list: help.sections[0], change: help.sections[1], labels }) : null, /* @__PURE__ */ React3.createElement("details", { className: "pk-more" }, /* @__PURE__ */ React3.createElement("summary", { className: "pk-more-title", "data-testid": "shortcuts-title" }, labels.shortcutsTitle), /* @__PURE__ */ React3.createElement(Shortcuts, { labels, mod }))));
2816
+ const topics = optionTopics({
2817
+ view,
2818
+ labels,
2819
+ folding,
2820
+ tips,
2821
+ explanations: help?.explanations ?? null,
2822
+ act: {
2823
+ total: onTotal,
2824
+ expand: () => onExpand(labels),
2825
+ collapse: () => onCollapse(labels),
2826
+ tipsOn: (on) => tips.onOn(on),
2827
+ resetTips: () => tips.onReset(),
2828
+ explain: (on) => help?.explanations?.set(on)
2829
+ }
2830
+ });
2831
+ 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 });
985
2832
  }
986
- function Confirm({ question, action, cancel, onYes, onNo, testId, yesId, noId }) {
987
- const no = useRef2(
2833
+ var runChoice = (close) => (c) => {
2834
+ if (c.closes) {
2835
+ close();
2836
+ }
2837
+ c.run?.();
2838
+ };
2839
+ function Confirm({ question, action, cancel, onYes, onNo, testId, yesId, noId, danger = false, busy = false, focusYes = false }) {
2840
+ const no = useRef3(
988
2841
  /** @type {HTMLButtonElement | null} */
989
2842
  null
990
2843
  );
991
- useEffect2(() => {
992
- no.current?.focus({ preventScroll: true });
993
- }, []);
994
- return /* @__PURE__ */ React3.createElement("div", { className: "pk-confirm pk-save-confirm", role: "group", "aria-label": question, "data-testid": testId }, /* @__PURE__ */ React3.createElement("span", { className: "pk-confirm-text" }, question), /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-btn pk-primary", "data-testid": yesId, onClick: onYes }, action), /* @__PURE__ */ React3.createElement("button", { ref: no, type: "button", className: "pk-btn", "data-autofocus": "", "data-testid": noId, onClick: onNo }, cancel));
2844
+ const yes = useRef3(
2845
+ /** @type {HTMLButtonElement | null} */
2846
+ null
2847
+ );
2848
+ useEffect3(() => {
2849
+ (focusYes ? yes : no).current?.focus({ preventScroll: true });
2850
+ }, [focusYes]);
2851
+ 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));
995
2852
  }
996
2853
  function SaveView({ labels, button, onSave, resolve, close }) {
997
- const [name, setName] = useState2("");
998
- const [asking, setAsking] = useState2(
2854
+ const [name, setName] = useState5("");
2855
+ const [asking, setAsking] = useState5(
999
2856
  /** @type {any} */
1000
2857
  null
1001
2858
  );
1002
- const field = useRef2(
2859
+ const field = useRef3(
1003
2860
  /** @type {HTMLInputElement | null} */
1004
2861
  null
1005
2862
  );
1006
- const asked = useRef2(false);
1007
- useEffect2(() => {
2863
+ const asked = useRef3(false);
2864
+ useEffect3(() => {
1008
2865
  if (asking) {
1009
2866
  asked.current = true;
1010
2867
  } else if (asked.current) {
@@ -1012,7 +2869,7 @@ function SaveView({ labels, button, onSave, resolve, close }) {
1012
2869
  }
1013
2870
  }, [asking]);
1014
2871
  if (asking) {
1015
- return /* @__PURE__ */ React3.createElement(
2872
+ return /* @__PURE__ */ React7.createElement(
1016
2873
  Confirm,
1017
2874
  {
1018
2875
  question: fill(labels.replaceConfirm, { name: asking.name }),
@@ -1029,7 +2886,7 @@ function SaveView({ labels, button, onSave, resolve, close }) {
1029
2886
  }
1030
2887
  );
1031
2888
  }
1032
- return /* @__PURE__ */ React3.createElement(
2889
+ return /* @__PURE__ */ React7.createElement(
1033
2890
  "form",
1034
2891
  {
1035
2892
  className: "pk-inline-form",
@@ -1045,50 +2902,51 @@ function SaveView({ labels, button, onSave, resolve, close }) {
1045
2902
  }
1046
2903
  }
1047
2904
  },
1048
- /* @__PURE__ */ React3.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 }),
1049
- /* @__PURE__ */ React3.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: !name.trim() }, button)
2905
+ /* @__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 }),
2906
+ /* @__PURE__ */ React7.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: !name.trim() }, button)
1050
2907
  );
1051
2908
  }
1052
2909
  function LoadCheck({ check, labels, onCancel, close, title, quiet = false }) {
1053
- const titleId = useId3();
1054
- const first = useRef2(
2910
+ const titleId = useId5();
2911
+ const first = useRef3(
1055
2912
  /** @type {HTMLButtonElement | null} */
1056
2913
  null
1057
2914
  );
1058
- useEffect2(() => {
2915
+ useEffect3(() => {
1059
2916
  if (!quiet) {
1060
2917
  first.current?.focus({ preventScroll: true });
1061
2918
  }
1062
2919
  }, [quiet]);
1063
- return /* @__PURE__ */ React3.createElement("div", { className: "pk-load-check", role: "group", "aria-labelledby": titleId, "data-testid": "load-check" }, /* @__PURE__ */ React3.createElement("p", { id: titleId, className: "pk-load-check-title" }, /* @__PURE__ */ React3.createElement(Icon, { name: "info", size: 16 }), /* @__PURE__ */ React3.createElement("span", null, title ?? labels.loadCheckTitle)), /* @__PURE__ */ React3.createElement("ul", { className: "pk-load-check-lines" }, check.lines.map((line, i) => /* @__PURE__ */ React3.createElement("li", { key: i }, line))), /* @__PURE__ */ React3.createElement("div", { className: "pk-load-check-actions" }, check.switchTo ? /* @__PURE__ */ React3.createElement("button", { ref: first, type: "button", className: "pk-btn pk-primary", "data-autofocus": "", "data-testid": "load-switch", onClick: () => {
2920
+ 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: () => {
1064
2921
  close();
1065
2922
  check.switchTo?.run();
1066
- } }, fill(labels.switchAndLoad, { source: check.switchTo.name })) : null, /* @__PURE__ */ React3.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: () => {
2923
+ } }, 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: () => {
1067
2924
  close();
1068
2925
  check.load();
1069
- } }, labels.loadAnyway), /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-btn", "data-testid": "load-cancel", onClick: onCancel }, labels.cancel)), check.switchTo ? /* @__PURE__ */ React3.createElement("p", { className: "pk-hint" }, labels.switchStartsFresh) : null);
2926
+ } }, 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);
1070
2927
  }
1071
2928
  function LoadView({ labels, onLoadText, close }) {
1072
- const [text, setText] = useState2("");
1073
- const [problem, setProblem] = useState2(
2929
+ const [text, setText] = useState5("");
2930
+ const [problem, setProblem] = useState5(
1074
2931
  /** @type {string | null} */
1075
2932
  null
1076
2933
  );
1077
- const [check, setCheck] = useState2(
2934
+ const [check, setCheck] = useState5(
1078
2935
  /** @type {any} */
1079
2936
  null
1080
2937
  );
1081
- const [busy, setBusy] = useState2(false);
1082
- const file = useRef2(
2938
+ const [busy, setBusy] = useState5(false);
2939
+ const file = useRef3(
1083
2940
  /** @type {HTMLInputElement | null} */
1084
2941
  null
1085
2942
  );
1086
- const field = useRef2(
2943
+ const field = useRef3(
1087
2944
  /** @type {HTMLTextAreaElement | null} */
1088
2945
  null
1089
2946
  );
1090
- const problemId = useId3();
1091
- useEffect2(() => {
2947
+ const problemId = useId5();
2948
+ const fileName = useFormName();
2949
+ useEffect3(() => {
1092
2950
  if (!check) {
1093
2951
  field.current?.focus({ preventScroll: true });
1094
2952
  }
@@ -1106,9 +2964,9 @@ function LoadView({ labels, onLoadText, close }) {
1106
2964
  }
1107
2965
  };
1108
2966
  if (check) {
1109
- return /* @__PURE__ */ React3.createElement(LoadCheck, { check, labels, onCancel: () => setCheck(null), close });
2967
+ return /* @__PURE__ */ React7.createElement(LoadCheck, { check, labels, onCancel: () => setCheck(null), close });
1110
2968
  }
1111
- return /* @__PURE__ */ React3.createElement(
2969
+ return /* @__PURE__ */ React7.createElement(
1112
2970
  "form",
1113
2971
  {
1114
2972
  className: "pk-inline-form pk-load-view",
@@ -1117,8 +2975,8 @@ function LoadView({ labels, onLoadText, close }) {
1117
2975
  load(text);
1118
2976
  }
1119
2977
  },
1120
- /* @__PURE__ */ React3.createElement("p", { className: "pk-hint" }, labels.loadViewHint),
1121
- /* @__PURE__ */ React3.createElement(
2978
+ /* @__PURE__ */ React7.createElement("p", { className: "pk-hint" }, labels.loadViewHint),
2979
+ /* @__PURE__ */ React7.createElement(
1122
2980
  ClearInput,
1123
2981
  {
1124
2982
  multiline: true,
@@ -1138,16 +2996,18 @@ function LoadView({ labels, onLoadText, close }) {
1138
2996
  inputRef: field
1139
2997
  }
1140
2998
  ),
1141
- problem ? /* @__PURE__ */ React3.createElement("p", { id: problemId, className: "pk-form-problem", role: "alert", "data-testid": "load-view-problem" }, problem) : null,
1142
- /* @__PURE__ */ React3.createElement(
2999
+ problem ? /* @__PURE__ */ React7.createElement("p", { id: problemId, className: "pk-form-problem", role: "alert", "data-testid": "load-view-problem" }, problem) : null,
3000
+ /* @__PURE__ */ React7.createElement(
1143
3001
  "input",
1144
3002
  {
1145
3003
  ref: file,
1146
3004
  type: "file",
3005
+ name: `${fileName}-file`,
1147
3006
  accept: "application/json,.json",
1148
3007
  className: "pk-sr",
1149
3008
  tabIndex: -1,
1150
3009
  "aria-hidden": "true",
3010
+ "aria-label": labels.chooseFile,
1151
3011
  "data-testid": "load-view-file",
1152
3012
  onChange: async (e) => {
1153
3013
  const chosen = e.target.files?.[0];
@@ -1168,27 +3028,10 @@ function LoadView({ labels, onLoadText, close }) {
1168
3028
  }
1169
3029
  }
1170
3030
  ),
1171
- /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-btn", onClick: () => file.current?.click(), disabled: busy, "data-testid": "load-view-choose" }, /* @__PURE__ */ React3.createElement(Icon, { name: "file" }), /* @__PURE__ */ React3.createElement("span", { className: "pk-btn-text" }, labels.chooseFile)),
1172
- /* @__PURE__ */ React3.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: busy || !text.trim(), "data-testid": "load-view-apply" }, labels.load)
3031
+ /* @__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)),
3032
+ /* @__PURE__ */ React7.createElement("button", { type: "submit", className: "pk-btn pk-primary", disabled: busy || !text.trim(), "data-testid": "load-view-apply" }, labels.load)
1173
3033
  );
1174
3034
  }
1175
- function ShareSection({ labels, share, close }) {
1176
- const [loading, setLoading] = useState2(false);
1177
- const act = shareActions(share, labels);
1178
- if (loading) {
1179
- return /* @__PURE__ */ React3.createElement(Section, { title: labels.loadView.replace(/…$/, "") }, /* @__PURE__ */ React3.createElement(LoadView, { labels, onLoadText: act.loadText, close }));
1180
- }
1181
- return /* @__PURE__ */ React3.createElement(Section, { title: labels.share, id: "share" }, share.canLink ? /* @__PURE__ */ React3.createElement(Option, { icon: "link", onSelect: () => {
1182
- close();
1183
- act.copyLink();
1184
- }, testId: "copy-link" }, labels.copyLink) : null, /* @__PURE__ */ React3.createElement(Option, { icon: "copy", onSelect: () => {
1185
- close();
1186
- act.copyJson();
1187
- }, testId: "copy-json" }, labels.copyJson), /* @__PURE__ */ React3.createElement(Option, { icon: "download", onSelect: () => {
1188
- close();
1189
- act.download();
1190
- }, testId: "download-view" }, labels.downloadView), /* @__PURE__ */ React3.createElement(Option, { icon: "upload", onSelect: () => setLoading(true), testId: "load-view" }, labels.loadView), /* @__PURE__ */ React3.createElement("p", { className: "pk-hint pk-menu-hint", "data-testid": "share-privacy" }, labels.sharePrivacy));
1191
- }
1192
3035
  function viewActions(ctx, labels) {
1193
3036
  const run = (task, done, failed, rejected, name) => Promise.resolve().then(task).then(
1194
3037
  () => {
@@ -1222,114 +3065,159 @@ function ViewsPanel({ templates, labels, onLoad, actions, close, share }) {
1222
3065
  const { save, remove: onDelete, publish: onPublish } = viewActions(actions, labels);
1223
3066
  const can = { host: Boolean(actions.onSave), store: Boolean(actions.store), publish: Boolean(onPublish), sourceId: actions.sourceId };
1224
3067
  const target = saveTarget(actions.loaded, templates, can, actions.empty);
1225
- const [askShared, setAskShared] = useState2(false);
1226
3068
  const store = actions.store && !actions.onSave;
1227
- const [confirming, setConfirming] = useState2(
1228
- /** @type {{ at: number, kind: "delete" | "publish" } | null} */
1229
- null
1230
- );
1231
- const [busy, setBusy] = useState2(false);
1232
- const box = useRef2(
1233
- /** @type {HTMLDivElement | null} */
1234
- null
1235
- );
1236
- const [refocus, setRefocus] = useState2(
1237
- /** @type {{ key: string, place: number } | null} */
3069
+ const [asking, setAsking] = useState5(
3070
+ /** @type {{ kind: "delete" | "publish" | "replaceShared", t?: any, focus?: string } | null} */
1238
3071
  null
1239
3072
  );
1240
- useEffect2(() => {
3073
+ const [busy, setBusy] = useState5(false);
3074
+ useEffect3(() => {
1241
3075
  share?.prepare?.();
1242
3076
  }, [share]);
1243
- useEffect2(() => {
1244
- if (refocus && box.current) {
1245
- const entries = [...box.current.querySelectorAll("[data-pk-entry]")];
1246
- const entry2 = entries.find((el) => el.getAttribute("data-pk-entry") === refocus.key) ?? entries[Math.min(refocus.place, entries.length - 1)];
1247
- (entry2 ?? box.current).querySelector("[data-pk-option]")?.focus({ preventScroll: true });
1248
- setRefocus(null);
1249
- }
1250
- }, [refocus, templates]);
1251
- const keyOf2 = (t) => `${t.scope}:${t.at ?? ""}:${t.name}`;
1252
- useEffect2(() => {
1253
- if (confirming) {
1254
- box.current?.querySelector(".pk-confirm [data-autofocus]")?.focus({ preventScroll: true });
1255
- }
1256
- }, [confirming]);
1257
- const answer = (t) => {
1258
- setConfirming(null);
1259
- const entries = box.current ? [...box.current.querySelectorAll("[data-pk-entry], .pk-confirm")] : [];
1260
- setRefocus({ key: keyOf2(t), place: Math.max(0, entries.findIndex((el) => el.classList.contains("pk-confirm"))) });
3077
+ const sharedChange = Boolean(onPublish) || templates.some((t) => t.scope === "shared" && t.deletable);
3078
+ const ids = entryIds(templates);
3079
+ const group = (scope) => templates.flatMap((t, at) => t.scope === scope ? [at] : []);
3080
+ const entry = (at, list) => {
3081
+ const t = templates[at];
3082
+ const id = ids[at];
3083
+ const next = afterDelete(list, list.indexOf(at));
3084
+ const ask = (kind, focus) => () => setAsking({ kind, t, focus });
3085
+ return {
3086
+ id,
3087
+ testId: `saved-view-${t.name}`,
3088
+ text: t.name,
3089
+ icon: "bookmark",
3090
+ current: isLoadedEntry(t, actions.loaded),
3091
+ closes: true,
3092
+ run: () => onLoad(t),
3093
+ info: t.scope === "shared" && sharedChange && !(onDelete && t.deletable) ? "sharedView" : void 0,
3094
+ actions: [
3095
+ ...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}`) }] : [],
3096
+ ...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]}`) }] : []
3097
+ ]
3098
+ };
1261
3099
  };
1262
- const entry = (t, at) => {
1263
- if (confirming && confirming.at === at) {
1264
- const kind = confirming.kind;
1265
- const publish = kind === "publish";
1266
- const question = fill(publish ? labels.publishConfirm : labels.deleteConfirm, { name: t.name });
1267
- return /* @__PURE__ */ React3.createElement("div", { key: `${at}:${t.name}`, className: "pk-template pk-confirm", role: "group", "aria-label": question }, /* @__PURE__ */ React3.createElement("span", { className: "pk-confirm-text" }, question), /* @__PURE__ */ React3.createElement(
1268
- "button",
3100
+ const shared = group("shared");
3101
+ const mine = group("user");
3102
+ const thisView = [];
3103
+ if (target) {
3104
+ thisView.push({
3105
+ id: "save-loaded",
3106
+ text: fill(labels.saveNamed, { name: actions.loaded.name }),
3107
+ icon: "save",
3108
+ disabled: target.kind === null,
3109
+ reason: target.kind === null ? labels[target.why] : void 0,
3110
+ // over a shared view: asked first, everyone sees the change
3111
+ ...target.kind === "publish" ? { open: "confirm", run: () => setAsking({ kind: "replaceShared" }) } : { closes: true, run: () => save(target, actions.loaded.name) }
3112
+ });
3113
+ }
3114
+ if (canSaveAs(can)) {
3115
+ thisView.push({ id: "save-as", text: actions.loaded ? labels.saveAs : `${labels.saveView}\u2026`, icon: "save", open: "saveAs" });
3116
+ }
3117
+ const act = share ? shareActions(share, labels) : null;
3118
+ 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;
3119
+ const topics = [
3120
+ ...thisView.length ? [{ id: "thisView", title: labels.thisView, kind: (
3121
+ /** @type {const} */
3122
+ "inline"
3123
+ ), titled: true, groups: [{ choices: thisView }] }] : [],
3124
+ ...shared.length ? [{ id: "sharedViews", title: labels.sharedViews, kind: (
3125
+ /** @type {const} */
3126
+ "inline"
3127
+ ), titled: true, groups: [{ choices: shared.map((at) => entry(at, shared)) }] }] : [],
3128
+ ...mine.length || canSaveAs(can) || !shared.length ? [
3129
+ {
3130
+ id: "myViews",
3131
+ title: labels.myViews,
3132
+ kind: (
3133
+ /** @type {const} */
3134
+ "inline"
3135
+ ),
3136
+ titled: true,
3137
+ groups: [{ choices: mine.map((at) => entry(at, mine)) }],
3138
+ // empty: one line, with the store's note in short
3139
+ note: mine.length ? store ? labels.storeNote : null : store ? labels.noViewsStore : labels.noViews,
3140
+ noteId: store ? "store-note" : void 0
3141
+ }
3142
+ ] : [],
3143
+ ...act ? [
3144
+ {
3145
+ id: "share",
3146
+ title: labels.shareThisView,
3147
+ kind: (
3148
+ /** @type {const} */
3149
+ "inline"
3150
+ ),
3151
+ titled: true,
3152
+ groups: [
3153
+ {
3154
+ choices: [
3155
+ ...share.canLink ? [{ id: "copy-link", text: labels.copyLink, icon: "link", closes: true, run: act.copyLink }] : [],
3156
+ { id: "copy-json", text: labels.copyJson, icon: "copy", closes: true, run: act.copyJson },
3157
+ { id: "download-view", text: labels.downloadView, icon: "download", closes: true, run: act.download },
3158
+ { id: "load-view", text: labels.loadView, icon: "upload", open: "load" }
3159
+ ]
3160
+ }
3161
+ ],
3162
+ // what leaves the report with a view: filter values can be values of the data
3163
+ note: labels.sharePrivacy,
3164
+ noteId: "share-privacy"
3165
+ }
3166
+ ] : [],
3167
+ { id: "saveAs", title: labels.saveAs, levelTitle: (actions.loaded ? labels.saveAs : labels.saveView).replace(/…$/, ""), kind: "panel", hidden: true },
3168
+ { id: "load", title: labels.loadView, levelTitle: labels.loadView.replace(/…$/, ""), kind: "panel", hidden: true },
3169
+ { id: "confirm", title: question?.action ?? "", kind: "panel", hidden: true }
3170
+ ];
3171
+ const panel = (id, back) => {
3172
+ if (id === "saveAs") {
3173
+ 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 });
3174
+ }
3175
+ if (id === "load" && act) {
3176
+ return /* @__PURE__ */ React7.createElement(LoadView, { labels, onLoadText: act.loadText, close });
3177
+ }
3178
+ if (id === "confirm" && question && asking) {
3179
+ return /* @__PURE__ */ React7.createElement(
3180
+ Confirm,
1269
3181
  {
1270
- type: "button",
1271
- className: publish ? "pk-btn pk-primary" : "pk-btn pk-danger-btn",
1272
- disabled: busy,
1273
- "data-autofocus": "",
1274
- "data-testid": `confirm-${kind}`,
1275
- onClick: async () => {
3182
+ question: question.text,
3183
+ action: question.action,
3184
+ cancel: labels.cancel,
3185
+ danger: asking.kind === "delete",
3186
+ focusYes: asking.kind !== "replaceShared",
3187
+ busy,
3188
+ testId: question.testId,
3189
+ yesId: question.yesId,
3190
+ noId: question.noId,
3191
+ onNo: () => back(),
3192
+ onYes: async () => {
3193
+ if (asking.kind === "replaceShared") {
3194
+ close();
3195
+ save(target, actions.loaded.name);
3196
+ return;
3197
+ }
1276
3198
  setBusy(true);
1277
- const ok = await (publish ? onPublish : onDelete)?.(t);
3199
+ const ok = await (asking.kind === "publish" ? onPublish : onDelete)?.(asking.t);
1278
3200
  setBusy(false);
1279
3201
  if (ok) {
1280
- answer(t);
3202
+ back(asking.focus);
1281
3203
  }
1282
3204
  }
1283
- },
1284
- publish ? labels.publishAction : labels.deleteAction
1285
- ), /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-btn", disabled: busy, onClick: () => answer(t) }, labels.cancel));
3205
+ }
3206
+ );
1286
3207
  }
1287
- const button = (kind, icon, text) => /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-icon-btn", onClick: () => setConfirming({ at, kind }), "aria-label": text, title: text, "data-testid": `${kind}-view-${t.name}` }, /* @__PURE__ */ React3.createElement(Icon, { name: icon }));
1288
- return /* @__PURE__ */ React3.createElement("div", { key: `${at}:${t.name}`, className: "pk-template", "data-pk-entry": keyOf2(t) }, /* @__PURE__ */ React3.createElement(Option, { icon: "bookmark", current: isLoadedEntry(t, actions.loaded), onSelect: () => {
1289
- close();
1290
- onLoad(t);
1291
- }, testId: `saved-view-${t.name}` }, t.name), onPublish && t.scope === "user" ? button("publish", "upload", fill(labels.publishView, { name: t.name })) : null, onDelete && t.deletable ? button("delete", "trash", fill(labels.deleteView, { name: t.name })) : t.scope === "shared" && sharedChange ? /* @__PURE__ */ React3.createElement(SettingInfo, { id: "sharedView", name: t.name }) : null);
3208
+ return null;
1292
3209
  };
1293
- const sharedChange = Boolean(onPublish) || templates.some((t) => t.scope === "shared" && t.deletable);
1294
- const group = (scope) => templates.map((t, at) => t.scope === scope ? entry(t, at) : null).filter(Boolean);
1295
- const shared = group("shared");
1296
- const mine = group("user");
1297
- return /* @__PURE__ */ React3.createElement("div", { ref: box, className: "pk-views" }, /* @__PURE__ */ React3.createElement(Section, { title: labels.thisView, id: "thisView" }, target && askShared && target.kind === "publish" ? /* @__PURE__ */ React3.createElement(
1298
- Confirm,
1299
- {
1300
- question: fill(labels.replaceSharedConfirm, { name: actions.loaded.name }),
1301
- action: labels.replaceAction,
1302
- cancel: labels.cancel,
1303
- testId: "replace-shared-confirm",
1304
- yesId: "confirm-replace-shared",
1305
- noId: "cancel-replace-shared",
1306
- onYes: () => {
1307
- close();
1308
- save(target, actions.loaded.name);
1309
- },
1310
- onNo: () => setAskShared(false)
1311
- }
1312
- ) : target ? /* @__PURE__ */ React3.createElement(Option, { icon: "save", onSelect: () => {
1313
- if (target.kind === "publish") {
1314
- setAskShared(true);
1315
- } else {
1316
- close();
1317
- save(target, actions.loaded.name);
1318
- }
1319
- }, disabled: target.kind === null, reason: target.kind === null ? labels[target.why] : void 0, testId: "save-loaded" }, fill(labels.saveNamed, { name: actions.loaded.name })) : null, canSaveAs(can) ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { className: "pk-subtitle" }, actions.loaded ? labels.saveAs : labels.saveView), /* @__PURE__ */ React3.createElement(SaveView, { labels, button: actions.loaded ? labels.saveAs.replace(/…$/, "") : labels.save, onSave: (name, t) => save(t, name), resolve: (name) => saveAsTarget(name, templates, can), close })) : null, /* @__PURE__ */ React3.createElement("div", { className: "pk-setting-row" }, /* @__PURE__ */ React3.createElement(Option, { icon: "newFile", onSelect: () => {
1320
- close();
1321
- actions.onNew();
1322
- }, disabled: !actions.canNew, reason: actions.canNew ? void 0 : labels.newAlready, testId: "new-report" }, labels.newEmpty), /* @__PURE__ */ React3.createElement(SettingInfo, { id: "newReport", name: labels.newEmpty }))), shared.length ? /* @__PURE__ */ React3.createElement(Section, { title: labels.sharedViews, id: "sharedViews" }, shared) : null, mine.length || canSaveAs(can) || !shared.length ? /* @__PURE__ */ React3.createElement(Section, { title: labels.myViews, id: "myViews" }, mine.length ? mine : /* @__PURE__ */ React3.createElement("p", { className: "pk-hint", "data-testid": store ? "store-note" : void 0 }, store ? labels.noViewsStore : labels.noViews), store && mine.length ? /* @__PURE__ */ React3.createElement("p", { className: "pk-hint pk-menu-hint", "data-testid": "store-note" }, labels.storeNote) : null) : null, share ? /* @__PURE__ */ React3.createElement(ShareSection, { labels, share, close }) : null);
3210
+ return /* @__PURE__ */ React7.createElement(LevelMenu, { name: labels.views, labels, topics, close, onPick: runChoice(close), panel, focusAgain: templates.length });
1323
3211
  }
1324
3212
  function ExportOption({ icon, text, info, onSelect, testId, disabled, reason }) {
1325
- const option = /* @__PURE__ */ React3.createElement(Option, { icon, onSelect, disabled, reason, testId }, text);
1326
- return info ? /* @__PURE__ */ React3.createElement("div", { className: "pk-setting-row" }, option, /* @__PURE__ */ React3.createElement(SettingInfo, { id: (
3213
+ const option = /* @__PURE__ */ React7.createElement(Option, { icon, onSelect, disabled, reason, testId }, text);
3214
+ return info ? /* @__PURE__ */ React7.createElement("div", { className: "pk-setting-row" }, option, /* @__PURE__ */ React7.createElement(SettingInfo, { id: (
1327
3215
  /** @type {any} */
1328
3216
  info
1329
3217
  ), name: text })) : option;
1330
3218
  }
1331
3219
  function ExportPanel({ labels, onExport, chartReady, display, empty = false, prepare, close }) {
1332
- useEffect2(() => {
3220
+ useEffect3(() => {
1333
3221
  prepare();
1334
3222
  }, [prepare]);
1335
3223
  const run = (kind) => () => {
@@ -1337,116 +3225,11 @@ function ExportPanel({ labels, onExport, chartReady, display, empty = false, pre
1337
3225
  onExport(kind);
1338
3226
  };
1339
3227
  const off = empty ? { disabled: true, reason: labels.exportNeedsField } : {};
1340
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(Section, { title: labels.exportDownload, id: "exportDownload" }, /* @__PURE__ */ React3.createElement(ExportOption, { icon: "file", text: labels.exportXlsx, info: "exportXlsx", onSelect: run("xlsx"), ...off, testId: "export-xlsx" }), /* @__PURE__ */ React3.createElement(ExportOption, { icon: "file", text: labels.exportCsv, info: "exportCsv", onSelect: run("csv"), ...off, testId: "export-csv" }), /* @__PURE__ */ React3.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__ */ React3.createElement(Section, { title: labels.exportCopy, id: "exportCopy" }, /* @__PURE__ */ React3.createElement(ExportOption, { icon: "copy", text: labels.copyTable, info: "copyTable", onSelect: run("copy-table"), ...off, testId: "export-copy-table" }), /* @__PURE__ */ React3.createElement(ExportOption, { icon: "copy", text: labels.copyDataJson, info: "copyDataJson", onSelect: run("copy-json"), ...off, testId: "export-copy-json" })));
1341
- }
1342
-
1343
- // src/filter.jsx
1344
- import React4, { useMemo, useState as useState3 } from "react";
1345
- import { CATALOG as CATALOG2, fieldItems, fieldLabel as fieldLabel2 } from "pivotkit-core";
1346
- var FILTER_LIST_MAX = 300;
1347
- var keyOf = (v) => JSON.stringify(v);
1348
- function FilterBody({ view: current, base, field, encoded, locale, labels, commit, close }) {
1349
- const view = base ?? current;
1350
- const info = useMemo(() => fieldItems(encoded, field, { view, locale, labels: labels.core }), [encoded, field, view, locale, labels]);
1351
- const all = useMemo(() => info ? info.items.map((i) => i.value) : [], [info]);
1352
- const [selected, setSelected] = useState3(() => new Set(selectedItems(view, field, all).map(keyOf)));
1353
- const [query, setQuery] = useState3("");
1354
- const label = filtersOf(view, field, ["label"])[0];
1355
- const [op, setOp] = useState3(label?.op ?? "");
1356
- const [text, setText] = useState3(label?.value ?? "");
1357
- if (!info) {
1358
- return null;
1359
- }
1360
- const q = query.trim().toLocaleLowerCase();
1361
- const matching = q ? info.items.filter((i) => i.label.toLocaleLowerCase().includes(q)) : info.items;
1362
- const shown = matching.slice(0, FILTER_LIST_MAX);
1363
- const setAll = (on) => {
1364
- const next = new Set(selected);
1365
- for (const i of matching) {
1366
- if (on) {
1367
- next.add(keyOf(i.value));
1368
- } else {
1369
- next.delete(keyOf(i.value));
1370
- }
1371
- }
1372
- setSelected(next);
1373
- };
1374
- const toggle = (v) => {
1375
- const next = new Set(selected);
1376
- const k = keyOf(v);
1377
- if (next.has(k)) {
1378
- next.delete(k);
1379
- } else {
1380
- next.add(k);
1381
- }
1382
- setSelected(next);
1383
- };
1384
- const name = fieldLabel2(field, labels.core);
1385
- const apply = () => {
1386
- let next = setItemFilter(view, field, all.filter((v) => selected.has(keyOf(v))), all);
1387
- next = setLabelFilter(next, field, op ? { op, value: text } : null);
1388
- close();
1389
- commit(next, { step: "filter", field: name });
1390
- };
1391
- const filtering = !base && hasFilter(view, field);
1392
- const kind = conditionKind(encoded, view, field) ?? (label ? "text" : null);
1393
- return /* @__PURE__ */ React4.createElement(
1394
- "form",
1395
- {
1396
- className: "pk-filter",
1397
- onSubmit: (e) => {
1398
- e.preventDefault();
1399
- apply();
1400
- }
1401
- },
1402
- /* @__PURE__ */ React4.createElement("div", { className: "pk-popover-head" }, /* @__PURE__ */ React4.createElement("h3", null, fill(labels.filterTitle, { field: name })), /* @__PURE__ */ React4.createElement("span", { className: "pk-muted" }, fill(labels.selected, { count: selected.size.toLocaleString(locale) }))),
1403
- filtering ? /* @__PURE__ */ React4.createElement(
1404
- "button",
1405
- {
1406
- type: "button",
1407
- className: "pk-btn pk-remove-filter",
1408
- onClick: () => {
1409
- close();
1410
- commit(removeFilters(view, field), { step: "filter", field: name });
1411
- },
1412
- "data-testid": "filter-remove"
1413
- },
1414
- /* @__PURE__ */ React4.createElement(Icon, { name: "x" }),
1415
- /* @__PURE__ */ React4.createElement("span", { className: "pk-btn-text" }, labels.removeFilter)
1416
- ) : null,
1417
- /* @__PURE__ */ React4.createElement("label", { className: "pk-search" }, /* @__PURE__ */ React4.createElement(Icon, { name: "search" }), /* @__PURE__ */ React4.createElement("span", { className: "pk-sr" }, labels.searchValues), /* @__PURE__ */ React4.createElement(ClearInput, { type: "search", value: query, placeholder: labels.searchValues, onChange: setQuery, clearLabel: labels.clearText, "data-autofocus": "", "data-testid": "filter-search" })),
1418
- /* @__PURE__ */ React4.createElement("div", { className: "pk-filter-actions" }, /* @__PURE__ */ React4.createElement("button", { type: "button", className: "pk-link", onClick: () => setAll(true) }, labels.selectAll), /* @__PURE__ */ React4.createElement("button", { type: "button", className: "pk-link", onClick: () => setAll(false) }, labels.selectNone)),
1419
- /* @__PURE__ */ React4.createElement("div", { className: "pk-filter-body" }, /* @__PURE__ */ React4.createElement("ul", { className: "pk-values", role: "list" }, shown.map((i) => {
1420
- const k = keyOf(i.value);
1421
- return /* @__PURE__ */ React4.createElement("li", { key: k, className: "pk-value" }, /* @__PURE__ */ React4.createElement("label", null, /* @__PURE__ */ React4.createElement("input", { type: "checkbox", checked: selected.has(k), onChange: () => toggle(i.value) }), /* @__PURE__ */ React4.createElement("span", { className: "pk-value-label" }, i.label), /* @__PURE__ */ React4.createElement("span", { className: "pk-count" }, i.count.toLocaleString(locale))), /* @__PURE__ */ React4.createElement("button", { type: "button", className: "pk-link pk-only", onClick: () => setSelected(/* @__PURE__ */ new Set([k])), "aria-label": `${labels.onlyThis}: ${i.label}` }, labels.onlyThis));
1422
- })), matching.length > shown.length ? /* @__PURE__ */ React4.createElement("p", { className: "pk-hint" }, fill(labels.valuesShown, { shown: shown.length, total: matching.length.toLocaleString(locale) })) : null, kind ? /* @__PURE__ */ React4.createElement("fieldset", { className: "pk-condition" }, /* @__PURE__ */ React4.createElement("legend", null, kind === "number" ? labels.conditionNumber : labels.condition), /* @__PURE__ */ React4.createElement("select", { value: op, onChange: (e) => setOp(e.target.value), "aria-label": kind === "number" ? labels.conditionNumber : labels.condition }, /* @__PURE__ */ React4.createElement("option", { value: "" }, labels.conditionNone), CATALOG2.labelOps.map((o) => /* @__PURE__ */ React4.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))), op ? /* @__PURE__ */ React4.createElement(
1423
- ClearInput,
1424
- {
1425
- type: "text",
1426
- value: text,
1427
- onChange: setText,
1428
- onClear: () => {
1429
- if (!base && filtersOf(view, field, ["label"]).length) {
1430
- commit(setLabelFilter(view, field, null), { step: "filter", field: name });
1431
- }
1432
- },
1433
- clearLabel: labels.clearText,
1434
- "aria-label": labels.conditionValue,
1435
- placeholder: labels.conditionValue,
1436
- maxLength: 1e3,
1437
- "data-testid": "filter-condition-text"
1438
- }
1439
- ) : null) : null),
1440
- /* @__PURE__ */ React4.createElement("div", { className: "pk-popover-foot" }, /* @__PURE__ */ React4.createElement("button", { type: "button", className: "pk-btn", onClick: close }, labels.cancel), /* @__PURE__ */ React4.createElement("button", { type: "submit", className: "pk-btn pk-primary", "data-testid": "filter-apply" }, labels.apply))
1441
- );
1442
- }
1443
- function FilterPopover({ target, onClose, view, encoded, locale, labels, commit }) {
1444
- const anchor = useMemo(() => ({ current: target ? target.anchor : null }), [target]);
1445
- return /* @__PURE__ */ React4.createElement(Popover, { open: Boolean(target), anchor, onClose, label: target ? fill(labels.filterTitle, { field: fieldLabel2(target.field, labels.core) }) : "", className: "pk-filter-popover", fill: true }, target ? /* @__PURE__ */ React4.createElement(FilterBody, { key: target.field, view, base: target.base, field: target.field, encoded, locale, labels, commit, close: onClose }) : null);
3228
+ 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: "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(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" })));
1446
3229
  }
1447
3230
 
1448
3231
  // src/drill-panel.jsx
1449
- import React5, { useContext as useContext3, useEffect as useEffect3, useId as useId4, useMemo as useMemo2, useRef as useRef3, useState as useState4 } from "react";
3232
+ import React8, { useContext as useContext4, useEffect as useEffect4, useId as useId6, useMemo as useMemo3, useRef as useRef4, useState as useState6 } from "react";
1450
3233
 
1451
3234
  // src/export-run.js
1452
3235
  import { toGrid } from "pivotkit-core";
@@ -1559,17 +3342,17 @@ async function exportDrill(kind, { drill, encoded, labels, onExport, announce, r
1559
3342
  }
1560
3343
 
1561
3344
  // src/drill-table.js
1562
- import { fieldLabel as fieldLabel3, findNode, formatter, isFormat as isFormat3 } from "pivotkit-core";
3345
+ import { fieldLabel as fieldLabel5, findNode, formatter as formatter3, isFormat as isFormat3 } from "pivotkit-core";
1563
3346
  var DATE_FORMATS = /* @__PURE__ */ new Set(["date", "datetime", "time"]);
1564
3347
  function columnText(column, { locale, labels, format }) {
1565
3348
  const spec = typeof format === "string" && isFormat3(format) ? format.trim().toLowerCase() : null;
1566
3349
  if (column.type === "date") {
1567
- const f = formatter(spec && DATE_FORMATS.has(spec.split(":")[0]) ? spec : column.dateOnly ? "date" : "datetime", { locale });
3350
+ const f = formatter3(spec && DATE_FORMATS.has(spec.split(":")[0]) ? spec : column.dateOnly ? "date" : "datetime", { locale });
1568
3351
  return { text: f, numeric: false };
1569
3352
  }
1570
3353
  if (column.type === "number") {
1571
3354
  const nf = new Intl.NumberFormat(locale, { maximumFractionDigits: 6 });
1572
- const f = spec && !DATE_FORMATS.has(spec.split(":")[0]) ? formatter(spec, { locale }) : (v) => nf.format(
3355
+ const f = spec && !DATE_FORMATS.has(spec.split(":")[0]) ? formatter3(spec, { locale }) : (v) => nf.format(
1573
3356
  /** @type {number} */
1574
3357
  v
1575
3358
  );
@@ -1599,7 +3382,7 @@ function pathTitle(result, rowPath, colPath, labels) {
1599
3382
  const node = findNode(result, axis, path);
1600
3383
  for (let n = node; n && n.parent; n = n.parent) {
1601
3384
  const item = result.label(axis, n, labels.core);
1602
- parts.unshift(`${fieldLabel3(fields[n.depth - 1], labels.core)}: ${item}`);
3385
+ parts.unshift(`${fieldLabel5(fields[n.depth - 1], labels.core)}: ${item}`);
1603
3386
  items.unshift(item);
1604
3387
  }
1605
3388
  };
@@ -1616,16 +3399,16 @@ function drillOf({ result, rowPath, colPath, count, indices, formatOf, nameOf, i
1616
3399
 
1617
3400
  // src/drill-panel.jsx
1618
3401
  function DrillPanel({ drill: source, onClose, labels, locale, exportContext }) {
1619
- const id = useId4();
1620
- const drill = useMemo2(() => source ? drillOf(source, labels) : null, [source, labels]);
1621
- const panel = useRef3(
3402
+ const id = useId6();
3403
+ const drill = useMemo3(() => source ? drillOf(source, labels) : null, [source, labels]);
3404
+ const panel = useRef4(
1622
3405
  /** @type {HTMLDivElement | null} */
1623
3406
  null
1624
3407
  );
1625
- const [big, setBig] = useState4(false);
1626
- const narrow = useContext3(LayerContext).size === "narrow";
3408
+ const [big, setBig] = useState6(false);
3409
+ const narrow = useContext4(LayerContext).size === "narrow";
1627
3410
  const { onKeyDown } = useModal(panel, Boolean(drill), big ? () => setBig(false) : onClose);
1628
- useEffect3(() => {
3411
+ useEffect4(() => {
1629
3412
  if (drill && exportContext) {
1630
3413
  prepareExporters();
1631
3414
  }
@@ -1641,7 +3424,7 @@ function DrillPanel({ drill: source, onClose, labels, locale, exportContext }) {
1641
3424
  void exportDrill(kind, { drill, labels, ...exportContext, root: exportContext.root.current });
1642
3425
  }
1643
3426
  };
1644
- return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("div", { className: "pk-scrim pk-drill-scrim", onClick: onClose, "aria-hidden": "true" }), /* @__PURE__ */ React5.createElement(
3427
+ 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(
1645
3428
  "div",
1646
3429
  {
1647
3430
  className: `pk-drill${big && !narrow ? " pk-drill-big" : ""}`,
@@ -1658,15 +3441,55 @@ function DrillPanel({ drill: source, onClose, labels, locale, exportContext }) {
1658
3441
  }
1659
3442
  }
1660
3443
  },
1661
- /* @__PURE__ */ React5.createElement("div", { className: "pk-drill-head" }, /* @__PURE__ */ React5.createElement("div", { className: "pk-drill-heading" }, /* @__PURE__ */ React5.createElement("h2", { id }, labels.drillTitle), /* @__PURE__ */ React5.createElement("p", { className: "pk-drill-path" }, drill.title), /* @__PURE__ */ React5.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__ */ React5.createElement("div", { className: "pk-drill-actions" }, exportContext ? /* @__PURE__ */ React5.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__ */ React5.createElement(React5.Fragment, null, partial ? /* @__PURE__ */ React5.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__ */ React5.createElement(Section, { title: labels.exportDownload, id: "exportDownload" }, /* @__PURE__ */ React5.createElement(ExportOption, { icon: "file", text: labels.drillCsv, onSelect: run("drill-csv", close), testId: "drill-csv" }), /* @__PURE__ */ React5.createElement(ExportOption, { icon: "file", text: labels.drillXlsx, onSelect: run("drill-xlsx", close), testId: "drill-xlsx" })), /* @__PURE__ */ React5.createElement(Section, { title: labels.exportCopy, id: "exportCopy" }, /* @__PURE__ */ React5.createElement(ExportOption, { icon: "copy", text: labels.drillCopy, info: "drillCopy", onSelect: run("drill-copy", close), testId: "drill-copy" }), /* @__PURE__ */ React5.createElement(ExportOption, { icon: "copy", text: labels.drillJson, info: "drillJson", onSelect: run("drill-json", close), testId: "drill-json" })))) : null, narrow ? null : /* @__PURE__ */ React5.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__ */ React5.createElement(Icon, { name: "enlarge", size: 14 }), /* @__PURE__ */ React5.createElement("span", { className: "pk-btn-text" }, big ? labels.reduce : labels.enlarge)), /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-icon-btn", onClick: onClose, "data-autofocus": "", "aria-label": labels.close, title: labels.close }, /* @__PURE__ */ React5.createElement(Icon, { name: "x" })))),
1662
- /* @__PURE__ */ React5.createElement("div", { className: "pk-drill-body", tabIndex: 0, "aria-label": drill.title }, /* @__PURE__ */ React5.createElement("table", { className: "pk-drill-table" }, /* @__PURE__ */ React5.createElement("thead", null, /* @__PURE__ */ React5.createElement("tr", null, drill.columns.map((c) => /* @__PURE__ */ React5.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__ */ React5.createElement("tbody", null, drill.rows.map((row, i) => /* @__PURE__ */ React5.createElement("tr", { key: i }, drill.columns.map((c, k) => /* @__PURE__ */ React5.createElement("td", { key: c.name, className: c.numeric ? "pk-num" : void 0 }, c.numeric || row[k].length < 24 ? row[k] : /* @__PURE__ */ React5.createElement("div", { className: "pk-drill-text" }, row[k]))))))))
3444
+ /* @__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" })))),
3445
+ /* @__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]))))))))
1663
3446
  ));
1664
3447
  }
3448
+
3449
+ // src/data-menu.jsx
3450
+ import React9, { useEffect as useEffect5, useRef as useRef5, useState as useState7 } from "react";
3451
+ function DataMenu({ api, close, labels }) {
3452
+ const mod = importNow();
3453
+ const [failed, setFailed] = useState7(false);
3454
+ const [attempt, setAttempt] = useState7(0);
3455
+ const box = useRef5(
3456
+ /** @type {HTMLDivElement | null} */
3457
+ null
3458
+ );
3459
+ const [late] = useState7(() => !mod);
3460
+ const load = useRef5(api.load);
3461
+ useEffect5(() => {
3462
+ load.current = api.load;
3463
+ });
3464
+ useEffect5(() => {
3465
+ if (mod) {
3466
+ return void 0;
3467
+ }
3468
+ let live = true;
3469
+ load.current().catch(() => live && setFailed(true));
3470
+ return () => {
3471
+ live = false;
3472
+ };
3473
+ }, [mod, attempt]);
3474
+ useEffect5(() => {
3475
+ const popover = box.current?.closest(".pk-popover");
3476
+ const now = activeIn(popover);
3477
+ if (late && popover && (now === popover || !now || !popover.contains(now))) {
3478
+ popover.querySelector("[data-pk-option], [data-autofocus]")?.focus({ preventScroll: true });
3479
+ }
3480
+ }, [late, mod, failed]);
3481
+ 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: () => {
3482
+ setFailed(false);
3483
+ setAttempt((n) => n + 1);
3484
+ } }, labels.tryAgain)) : /* @__PURE__ */ React9.createElement("p", { className: "pk-hint pk-menu-loading", role: "status" }, labels.loadingMenu));
3485
+ }
1665
3486
  export {
1666
3487
  AxisMenu,
1667
3488
  ChartTypePanel,
3489
+ DataMenu,
1668
3490
  DrillPanel,
1669
3491
  ExportPanel,
3492
+ FilterMenu,
1670
3493
  FilterPopover,
1671
3494
  LoadCheck,
1672
3495
  OptionsPanel,