pivotkit-react 0.2.0 → 0.3.0

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