pivotkit-react 0.4.0 → 0.6.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 (59) hide show
  1. package/CHANGELOG.md +267 -1
  2. package/README.md +5 -2
  3. package/dist/chunks/{chunk-YITKWZ4L.js → chunk-2RAVX4DO.js} +604 -505
  4. package/dist/chunks/{chunk-ZYEYZSYL.js → chunk-7LERNGUW.js} +36 -2
  5. package/dist/chunks/{chunk-EM23V5GH.js → chunk-E6M57YLL.js} +19 -8
  6. package/dist/chunks/{chunk-RWYHJRQO.js → chunk-JMRTIOX4.js} +17 -7
  7. package/dist/chunks/{chunk-XN55BQ4M.js → chunk-RIOSIYGC.js} +54 -7
  8. package/dist/chunks/{chunk-LEN5RPBM.js → chunk-TR2HROIK.js} +43 -7
  9. package/dist/chunks/chunk-W2KIPREL.js +36 -0
  10. package/dist/chunks/{chunk-6MDAL3IO.js → chunk-XN5HNKJ2.js} +88 -101
  11. package/dist/chunks/{chunk-WB4GKWFQ.js → chunk-YXLANLGL.js} +34 -6
  12. package/dist/chunks/report-run-BZBFOMPF.js +12 -0
  13. package/dist/chunks/{unused-texts-K3VFH65P.js → unused-texts-Y4R67XSN.js} +1 -1
  14. package/dist/chunks/{unused-texts-de-OW4TGIVX.js → unused-texts-de-6YVPTNVS.js} +1 -1
  15. package/dist/echarts.js +38 -156
  16. package/dist/import-ui.js +69 -168
  17. package/dist/index.js +160 -102
  18. package/dist/labels.js +6 -6
  19. package/dist/menu-texts-de.js +1 -1
  20. package/dist/menus.js +778 -277
  21. package/dist/styles.css +207 -93
  22. package/package.json +8 -4
  23. package/types/chart-decorate.d.ts +28 -4
  24. package/types/chart-types.d.ts +2 -4
  25. package/types/echarts.d.ts +1 -1
  26. package/types/export-run.d.ts +42 -4
  27. package/types/field-info.d.ts +3 -10
  28. package/types/filter.d.ts +1 -1
  29. package/types/icons.d.ts +1 -0
  30. package/types/import-host.d.ts +34 -8
  31. package/types/import-labels.d.ts +47 -0
  32. package/types/import-limits.d.ts +6 -0
  33. package/types/import-module.d.ts +1 -1
  34. package/types/import-steps.d.ts +8 -0
  35. package/types/import-ui.d.ts +18 -4
  36. package/types/index.d.ts +76 -17
  37. package/types/labels.d.ts +200 -24
  38. package/types/light-tokens.d.ts +16 -0
  39. package/types/menu-labels.d.ts +43 -14
  40. package/types/menu-ops.d.ts +166 -43
  41. package/types/menu-topics.d.ts +7 -4
  42. package/types/names.d.ts +47 -19
  43. package/types/place.d.ts +24 -0
  44. package/types/print-frame.d.ts +24 -0
  45. package/types/report-run.d.ts +14 -0
  46. package/types/share-actions.d.ts +17 -3
  47. package/types/share.d.ts +13 -17
  48. package/types/sheet-views.d.ts +60 -0
  49. package/types/templates.d.ts +21 -1
  50. package/types/theme.d.ts +2 -16
  51. package/types/tips.d.ts +5 -0
  52. package/types/toolbar-panels.d.ts +9 -6
  53. package/types/unused-texts.d.ts +13 -3
  54. package/types/use-export.d.ts +2 -2
  55. package/types/view-ops.d.ts +65 -6
  56. package/types/view-save.d.ts +10 -6
  57. package/types/view-store.d.ts +21 -11
  58. package/types/chart-layout.d.ts +0 -111
  59. package/types/import-source.d.ts +0 -32
package/dist/menus.js CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  ClearInput,
5
5
  HelpContext,
6
6
  InfoButton,
7
+ RULE_OPS,
7
8
  SHORTCUTS,
8
9
  SLICE_TYPES,
9
10
  ZONES,
@@ -13,11 +14,13 @@ import {
13
14
  dateSpan,
14
15
  dayText,
15
16
  decodeRow,
17
+ emptyPick,
16
18
  filterZoneFields,
17
19
  filtersOf,
18
20
  groupField,
19
21
  groupingName,
20
22
  groupingOf,
23
+ hiddenNot,
21
24
  importNow,
22
25
  isoDay,
23
26
  itemRuleText,
@@ -26,15 +29,20 @@ import {
26
29
  loadLink,
27
30
  moveField,
28
31
  numericResult,
32
+ opOf,
29
33
  periodText,
34
+ pickFilter,
35
+ plainRange,
30
36
  rangeShare,
31
37
  readLinkParam,
32
38
  refLabel,
33
39
  relativeDays,
34
40
  relativeText,
35
41
  reorder,
42
+ ruleOp,
36
43
  same,
37
44
  sameRef,
45
+ searchItems,
38
46
  selectedItems,
39
47
  setSort,
40
48
  shareBase,
@@ -48,12 +56,16 @@ import {
48
56
  viewFromText,
49
57
  wholeYears,
50
58
  withLinkParam
51
- } from "./chunks/chunk-YITKWZ4L.js";
59
+ } from "./chunks/chunk-2RAVX4DO.js";
52
60
  import {
53
61
  addMenuTexts,
54
62
  hasMenuTexts,
55
63
  menuLabels
56
- } from "./chunks/chunk-LEN5RPBM.js";
64
+ } from "./chunks/chunk-TR2HROIK.js";
65
+ import {
66
+ listedFor,
67
+ sheetOfSource
68
+ } from "./chunks/chunk-W2KIPREL.js";
57
69
  import {
58
70
  Group,
59
71
  Icon,
@@ -66,28 +78,28 @@ import {
66
78
  stopAfter,
67
79
  useFormName,
68
80
  useModal
69
- } from "./chunks/chunk-XN55BQ4M.js";
81
+ } from "./chunks/chunk-RIOSIYGC.js";
70
82
  import {
71
83
  fill,
72
84
  hostFailure,
73
85
  messageOf,
74
86
  plural
75
- } from "./chunks/chunk-6MDAL3IO.js";
87
+ } from "./chunks/chunk-XN5HNKJ2.js";
76
88
 
77
89
  // src/chip-menus.jsx
78
- import React6, { useId as useId4, useState as useState4 } from "react";
79
- import { fieldLabel as fieldLabel4 } from "pivotkit-core";
90
+ import React6, { useId as useId4, useMemo as useMemo3, useState as useState4 } from "react";
91
+ import { computePivot as computePivot2, fieldLabel as fieldLabel4 } from "pivotkit-core";
80
92
 
81
93
  // src/filter-level.jsx
82
94
  import React5, { useContext as useContext3, useEffect as useEffect2, useId as useId3, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
83
- import { CATALOG as CATALOG4, LIMITS, fieldItems as fieldItems2, fieldLabel as fieldLabel3, formatter as formatter2 } from "pivotkit-core";
95
+ import { CATALOG as CATALOG3, LIMITS as LIMITS2, fieldItems as fieldItems2, fieldLabel as fieldLabel3, formatter as formatter2, relativeDateRange } from "pivotkit-core";
84
96
 
85
97
  // src/filter.jsx
86
98
  import React, { useMemo, useState } from "react";
87
- import { CATALOG as CATALOG2, fieldItems, fieldLabel } from "pivotkit-core";
99
+ import { LIMITS, fieldItems, fieldLabel } from "pivotkit-core";
88
100
 
89
101
  // src/menu-ops.js
90
- import { CATALOG, computePivot, isFormat } from "pivotkit-core";
102
+ import { CATALOG, MATCH_DEFAULTS, computePivot, isFormat } from "pivotkit-core";
91
103
  var COUNTING = /* @__PURE__ */ new Set(["count", "countUnique", "listUnique"]);
92
104
  var unitOf = (agg) => COUNTING.has(agg) ? "count" : "field";
93
105
  function updateValue(view, index, patch, options = {}) {
@@ -135,20 +147,21 @@ function replaceFilters(view, field, types, entries) {
135
147
  kept.splice(at, 0, ...entries);
136
148
  next.filters = kept;
137
149
  if (!axisOf(next, field) && filterZoneFields(view).some((f) => same(f, field)) && !kept.some((f) => same(f.field, field))) {
138
- next.filters.splice(at, 0, { field, type: "exclude", items: [] });
150
+ next.filters.splice(at, 0, emptyPick(field));
139
151
  }
140
152
  return next;
141
153
  }
142
- function replaceFilter(view, field, previous, entry) {
154
+ function replaceFilter(view, field, previous, entry, before = null) {
143
155
  const next = clone(view);
144
- const key = previous ? JSON.stringify(previous) : null;
145
- const at = key === null ? -1 : next.filters.findIndex((f) => same(f.field, field) && JSON.stringify(f) === key);
156
+ const indexOf = (f) => f ? next.filters.findIndex((g) => same(g.field, field) && JSON.stringify(g) === JSON.stringify(f)) : -1;
157
+ const at = indexOf(previous);
146
158
  if (at === -1) {
147
159
  if (!entry) {
148
160
  return next;
149
161
  }
162
+ const ahead = indexOf(before);
150
163
  const last = next.filters.map((f) => same(f.field, field)).lastIndexOf(true);
151
- next.filters.splice(last + 1, 0, entry);
164
+ next.filters.splice(ahead === -1 ? last + 1 : ahead, 0, entry);
152
165
  return next;
153
166
  }
154
167
  if (entry) {
@@ -156,7 +169,7 @@ function replaceFilter(view, field, previous, entry) {
156
169
  } else {
157
170
  next.filters.splice(at, 1);
158
171
  if (!axisOf(next, field) && filterZoneFields(view).some((f) => same(f, field)) && !next.filters.some((f) => same(f.field, field))) {
159
- next.filters.splice(at, 0, { field, type: "exclude", items: [] });
172
+ next.filters.splice(at, 0, emptyPick(field));
160
173
  }
161
174
  }
162
175
  return next;
@@ -164,22 +177,27 @@ function replaceFilter(view, field, previous, entry) {
164
177
  function setItemFilter(view, field, selected, all) {
165
178
  const keep = new Set(selected.map((v) => JSON.stringify(v)));
166
179
  const excluded = all.filter((v) => !keep.has(JSON.stringify(v)));
167
- return replaceFilters(view, field, ["include", "exclude"], excluded.length ? [{ field, type: "exclude", items: excluded }] : []);
180
+ return replaceFilters(view, field, ["in"], excluded.length ? [pickFilter(field, excluded)] : []);
168
181
  }
169
182
  function setLabelFilter(view, field, condition) {
170
- return replaceFilters(view, field, ["label"], condition && condition.value !== "" ? [{ field, type: "label", op: condition.op, value: condition.value }] : []);
183
+ return replaceFilters(view, field, ["text"], condition && condition.value !== "" ? [textRule(field, condition)] : []);
171
184
  }
185
+ var textRule = (field, { op, value, on }) => ({ field, type: "text", ...opOf(op), value, on, match: { ...MATCH_DEFAULTS }, blanks: "exclude" });
186
+ var textOn = (encoded, field) => encoded.column(field)?.type === "string" ? "value" : "label";
172
187
  function setTopFilter(view, field, top, previous) {
173
- const entry = top ? { field, type: "top", count: top.count, bottom: Boolean(top.bottom), ...top.by ? { by: top.by } : {} } : null;
188
+ const ties = top?.ties ?? previous?.ties;
189
+ const entry = top ? { field, type: "top", count: top.count, bottom: Boolean(top.bottom), ...top.by ? { by: top.by } : {}, ...ties === "all" ? { ties: "all" } : {} } : null;
174
190
  if (previous) {
175
191
  return replaceFilter(view, field, previous, entry);
176
192
  }
177
193
  return replaceFilters(view, field, ["top"], entry ? [entry] : []);
178
194
  }
179
- var RULE_TYPES = Object.freeze(["relative", "compare", "value", "label"]);
195
+ var RULE_TYPES = Object.freeze(["relative", "compare", "value", "text"]);
180
196
  var RULES_MAX = 10;
181
- var setRule = (view, field, previous, entry) => replaceFilter(view, field, previous, entry);
197
+ var setRule = (view, field, previous, entry, before = null) => replaceFilter(view, field, previous, entry, before);
182
198
  var COARSE = Object.freeze(["year", "yearQuarter"]);
199
+ var QUICK_UNITS = Object.freeze(["day", "week", "month", "quarter", "year"]);
200
+ var FINEST = Object.freeze({ day: "day", yearWeek: "week", yearMonth: "month", yearQuarter: "quarter", year: "year" });
183
201
  function ruleKind(encoded, view, field) {
184
202
  const grouping = groupingOf(view, field);
185
203
  const source = encoded.column(sourceOf(view, field))?.type ?? "string";
@@ -187,10 +205,12 @@ function ruleKind(encoded, view, field) {
187
205
  const item = grouping ? grouping.by === "day" ? "date" : "group" : source === "number" || source === "date" ? source : null;
188
206
  const cyclic = dates && Boolean(grouping) && CATALOG.cyclicUnits.includes(grouping.by);
189
207
  const quick = dates && !cyclic;
190
- return { item, dates, cyclic, quick, months: quick && !COARSE.includes(grouping?.by), days: quick && item === "date", unit: grouping?.by ?? null };
208
+ const finest = grouping ? Object.hasOwn(FINEST, grouping.by) ? FINEST[grouping.by] : "day" : "day";
209
+ const units = quick ? QUICK_UNITS.slice(QUICK_UNITS.indexOf(finest)) : [];
210
+ return { item, dates, cyclic, quick, months: quick && !COARSE.includes(grouping?.by), days: quick && item === "date", unit: grouping?.by ?? null, units };
191
211
  }
192
212
  function ruleText(view, f, { labels, locale, timeZone, date, labelOf, span }) {
193
- return f.type === "value" ? valueConditionText(view, f, labels, locale) : itemRuleText(f, labels, locale, { timeZone, date, labelOf, span });
213
+ return f.type === "value" ? valueConditionText(view, f, labels, locale) : itemRuleText(f, labels, locale, { timeZone, date, labelOf, span, weekStart: view.formatting?.weekStart });
194
214
  }
195
215
  function quickChoice(view, field, fk, all = []) {
196
216
  const ranges = filtersOf(view, field, ["relative"]);
@@ -200,16 +220,16 @@ function quickChoice(view, field, fk, all = []) {
200
220
  const years = whole.length ? yearsCombined(whole, all) : null;
201
221
  return years ? { id: "yearsCombined", years, filters: whole } : { id: "all", filters: [] };
202
222
  }
203
- const offered = { year: true, month: fk.months, day: fk.days };
204
- const r = ranges.find((f) => offered[f.unit]);
223
+ const units = fk.units ?? [];
224
+ const r = ranges.find((f) => units.includes(f.unit) && !f.not && f.blanks !== "only");
205
225
  if (!r) {
206
226
  return { id: "all", filters: [] };
207
227
  }
208
228
  const id = (
209
- /** @type {"thisYear" | "years" | "months" | "days"} */
210
- r.unit === "year" ? r.count === 1 ? "thisYear" : "years" : `${r.unit}s`
229
+ /** @type {"this" | "last" | "next" | "before"} */
230
+ r.direction ?? "last"
211
231
  );
212
- return { id, count: r.count, anchor: r.anchor ?? "today", filters: [r] };
232
+ return { id, unit: r.unit, count: r.count ?? 1, anchor: r.anchor ?? "today", calendar: r.calendar !== false, includeCurrent: r.includeCurrent !== false, filters: [r] };
213
233
  }
214
234
  function yearsCombined(compared, all) {
215
235
  let kept = new Set(all);
@@ -218,45 +238,76 @@ function yearsCombined(compared, all) {
218
238
  /** @type {[string, string]} */
219
239
  wholeYears(f.value, f.value2).map(Number)
220
240
  );
221
- kept = new Set([...kept].filter((y) => (a <= y && y <= b) === (f.op === "between")));
241
+ kept = new Set([...kept].filter((y) => (a <= y && y <= b) !== f.not));
222
242
  }
223
243
  return kept.size ? [...kept].sort((x, y) => x - y) : null;
224
244
  }
225
- var isWholeYear = (f) => f.type === "compare" && (f.op === "between" || f.op === "notBetween") && wholeYears(f.value, f.value2) !== null;
226
- function yearRules(field, years, all) {
245
+ var isWholeYear = (f) => f.type === "compare" && f.op === "between" && f.blanks !== "only" && wholeYears(f.value, f.value2) !== null;
246
+ function yearRules(field, years, all, blanks = "exclude") {
227
247
  if (!years.length || years.length === all.length) {
228
248
  return [];
229
249
  }
230
250
  const day = (y, last) => `${String(y).padStart(4, "0")}-${last ? "12-31" : "01-01"}`;
231
- const rule = (op, from, to) => ({ field, type: "compare", op, value: day(from, false), value2: day(to, true) });
232
- const rules = [rule("between", years[0], years[years.length - 1])];
251
+ const rule = (not, from, to) => ({ field, type: "compare", op: "between", value: day(from, false), value2: day(to, true), not, blanks });
252
+ const rules = [rule(false, years[0], years[years.length - 1])];
233
253
  for (let i = 1; i < years.length; i++) {
234
254
  if (all.some((y) => years[i - 1] < y && y < years[i])) {
235
- rules.push(rule("notBetween", years[i - 1] + 1, years[i] - 1));
255
+ rules.push(rule(true, years[i - 1] + 1, years[i] - 1));
236
256
  }
237
257
  }
238
258
  return rules;
239
259
  }
240
260
  function setYearsCombined(view, field, years, all) {
261
+ const blanks = keepsBlanks(view, field) ? "include" : "exclude";
241
262
  const cleared = filtersOf(view, field, ["compare"]).filter(isWholeYear).reduce((v, f) => setRule(v, field, f, null), view);
242
- return yearRules(field, years, all).reduce((v, r) => setRule(v, field, null, r), cleared);
243
- }
244
- function setQuickRange(view, field, range) {
245
- return replaceFilters(view, field, ["relative"], range ? [{ field, type: "relative", unit: range.unit, count: range.count, ...range.anchor === "latest" ? { anchor: "latest" } : {} }] : []);
263
+ return yearRules(field, years, all, blanks).reduce((v, r) => setRule(v, field, null, r), cleared);
246
264
  }
265
+ function setQuickRange(view, field, range, previous) {
266
+ const entry = range ? relativeRule(field, range) : null;
267
+ if (previous !== void 0) {
268
+ return replaceFilter(view, field, previous, entry);
269
+ }
270
+ return replaceFilters(view, field, ["relative"], entry ? [entry] : []);
271
+ }
272
+ var relativeRule = (field, { direction = "last", unit, count, anchor, calendar = true, includeCurrent = true, blanks = "exclude" }) => ({
273
+ field,
274
+ type: "relative",
275
+ ...direction === "last" ? {} : { direction },
276
+ unit,
277
+ ...direction === "this" ? {} : { count },
278
+ ...calendar ? {} : { calendar: false },
279
+ ...includeCurrent || !calendar || direction === "this" ? {} : { includeCurrent: false },
280
+ ...anchor && anchor !== "today" ? { anchor } : {},
281
+ not: false,
282
+ blanks
283
+ });
247
284
  function setAnchor(view, field, anchor) {
248
285
  const next = clone(view);
249
286
  for (const f of next.filters) {
250
287
  if (same(f.field, field) && f.type === "relative") {
251
288
  delete f.anchor;
252
- if (anchor === "latest") {
253
- f.anchor = "latest";
289
+ if (anchor !== "today") {
290
+ f.anchor = anchor;
254
291
  }
255
292
  }
256
293
  }
257
294
  return next;
258
295
  }
259
- var resetFilter = (view, field) => replaceFilters(view, field, ["include", "exclude", ...RULE_TYPES], []);
296
+ var ITEM_RULE_TYPES = Object.freeze(["relative", "compare", "text"]);
297
+ function keepsBlanks(view, field) {
298
+ const rules = filtersOf(view, field, ITEM_RULE_TYPES);
299
+ return rules.length > 0 && rules.every((f) => f.blanks === "include");
300
+ }
301
+ function setRuleBlanks(view, field, keep) {
302
+ const next = clone(view);
303
+ for (const f of next.filters) {
304
+ if (same(f.field, field) && ITEM_RULE_TYPES.includes(f.type)) {
305
+ f.blanks = keep ? "include" : "exclude";
306
+ }
307
+ }
308
+ return next;
309
+ }
310
+ var resetFilter = (view, field) => replaceFilters(view, field, ["in", "blank", ...RULE_TYPES], []);
260
311
  function itemTotals(encoded, view, field, by, filters) {
261
312
  const result = computePivot(encoded, { ...view, rows: [field], cols: [], values: [{ ...by.field ? { field: by.field } : {}, agg: by.agg }], filters, sort: [] });
262
313
  const totals = /* @__PURE__ */ new Map();
@@ -287,17 +338,18 @@ function removeRules(view, field, keep = []) {
287
338
  return filtersOf(view, field, RULE_TYPES).filter((f) => !kept.has(JSON.stringify(f))).reduce((v, f) => setRule(v, field, f, null), view);
288
339
  }
289
340
  var TOTALS = Object.freeze(["grandTotalRow", "grandTotalColumn", "rowSubtotals", "colSubtotals"]);
341
+ var AXIS_NEEDS = Object.freeze({
342
+ grandTotalRow: { zone: "rows", fields: 1, why: "needsRowField" },
343
+ grandTotalColumn: { zone: "cols", fields: 1, why: "needsColField" },
344
+ rowSubtotals: { zone: "rows", fields: 2, why: "needsRowFields" },
345
+ colSubtotals: { zone: "cols", fields: 2, why: "needsColFields" }
346
+ });
290
347
  function totalNoEffect(view, key) {
291
- if (key === "grandTotalRow") {
292
- return view.rows.length >= 1 ? null : "needsRowField";
348
+ const axis = AXIS_NEEDS[key];
349
+ if (view[axis.zone].length < axis.fields) {
350
+ return axis.why;
293
351
  }
294
- if (key === "grandTotalColumn") {
295
- return view.cols.length >= 1 ? null : "needsColField";
296
- }
297
- if (key === "rowSubtotals") {
298
- return view.rows.length >= 2 ? null : "needsRowFields";
299
- }
300
- return view.cols.length >= 2 ? null : "needsColFields";
352
+ return view.values.length > 0 ? null : "needsValue";
301
353
  }
302
354
  function conditionKind(encoded, view, field) {
303
355
  const type = encoded.column(sourceOf(view, field))?.type ?? "string";
@@ -311,12 +363,25 @@ function filterState(view, field, state, labels, locale) {
311
363
  }
312
364
  parts.push(...state?.rules ?? []);
313
365
  for (const f of view.filters.filter(same2)) {
314
- if (f.type === "value" || f.type === "label" && !state?.rules) {
366
+ if (f.type === "value" || f.type === "text" && !state?.rules) {
315
367
  parts.push(ruleText(view, f, { labels, locale, timeZone: "UTC", date: false }));
316
368
  }
317
369
  }
318
370
  return parts.length ? parts.join(", ") : null;
319
371
  }
372
+ var boundMs = (text) => Date.parse(text.length > 10 ? `${text}Z` : `${text}T00:00Z`);
373
+ function rowsInRange(range, dict, counts) {
374
+ const from = range.from === null ? -Infinity : boundMs(range.from);
375
+ const to = boundMs(range.to) + (range.to.length > 10 ? 6e4 : 864e5);
376
+ let rows = 0;
377
+ for (let code = 0; code < dict.length; code++) {
378
+ const v = dict[code];
379
+ if (typeof v === "number" && v >= from && v < to) {
380
+ rows += counts[code];
381
+ }
382
+ }
383
+ return rows;
384
+ }
320
385
 
321
386
  // src/filter.jsx
322
387
  var FILTER_LIST_MAX = 300;
@@ -324,8 +389,7 @@ var keyOf = (v) => JSON.stringify(v);
324
389
  function ValueList({ items, selected, onChange, labels, locale, autoFocus = false, tail, children }) {
325
390
  const [query, setQuery] = useState("");
326
391
  const name = useFormName();
327
- const q = query.trim().toLocaleLowerCase();
328
- const matching = q ? items.filter((i) => i.label.toLocaleLowerCase().includes(q)) : items;
392
+ const matching = searchItems(items, query);
329
393
  const inList = tail ? matching.filter((i) => !tail.isOut(i)) : matching;
330
394
  const out = tail ? matching.filter((i) => tail.isOut(i)) : [];
331
395
  const shown = inList.slice(0, FILTER_LIST_MAX);
@@ -354,7 +418,12 @@ function ValueList({ items, selected, onChange, labels, locale, autoFocus = fals
354
418
  const k = keyOf(i.value);
355
419
  return /* @__PURE__ */ React.createElement("li", { key: k, className: `pk-value${muted ? " pk-value-out" : ""}` }, /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("input", { type: "checkbox", name, checked: selected.has(k), onChange: () => toggle(i.value) }), /* @__PURE__ */ React.createElement("span", { className: "pk-value-label" }, i.label), /* @__PURE__ */ React.createElement("span", { className: "pk-count" }, i.count.toLocaleString(locale))), /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-link pk-only", onClick: () => onChange(/* @__PURE__ */ new Set([k])), "aria-label": `${labels.onlyThis}: ${i.label}` }, labels.onlyThis));
356
420
  };
357
- return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("label", { className: "pk-search" }, /* @__PURE__ */ React.createElement(Icon, { name: "search" }), /* @__PURE__ */ React.createElement("span", { className: "pk-sr" }, labels.searchValues), /* @__PURE__ */ React.createElement(ClearInput, { type: "search", value: query, placeholder: labels.searchValues, onChange: setQuery, clearLabel: labels.clearText, "data-autofocus": autoFocus ? "" : void 0, "data-testid": "filter-search" })), /* @__PURE__ */ React.createElement("div", { className: "pk-filter-actions" }, /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-action", onClick: () => setAll(true), "data-testid": "select-all" }, labels.selectAll), /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-action", onClick: () => setAll(false), "data-testid": "select-none" }, labels.selectNone)), /* @__PURE__ */ React.createElement("div", { className: "pk-filter-body" }, /* @__PURE__ */ React.createElement("ul", { className: "pk-values", role: "list" }, shown.map((i) => row(i, false)), inList.length > shown.length ? /* @__PURE__ */ React.createElement("li", { className: "pk-hint pk-values-more" }, fill(labels.valuesShown, { shown: shown.length, total: inList.length.toLocaleString(locale) })) : null, out.length && tail ? tail.render(out, (i) => row(i, true), q !== "") : null), children));
421
+ 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(
422
+ out,
423
+ (i) => row(i, true),
424
+ matching !== items
425
+ /* searchItems gives the list itself without a search */
426
+ ) : null), children));
358
427
  }
359
428
  function FilterBody({ view: current, base, field, encoded, locale, labels, commit, close }) {
360
429
  const view = base ?? current;
@@ -362,8 +431,8 @@ function FilterBody({ view: current, base, field, encoded, locale, labels, commi
362
431
  const info = useMemo(() => fieldItems(encoded, field, { view, locale, labels: labels.core }), [encoded, field, view, locale, labels]);
363
432
  const all = useMemo(() => info ? info.items.map((i) => i.value) : [], [info]);
364
433
  const [selected, setSelected] = useState(() => new Set(selectedItems(view, field, all).map(keyOf)));
365
- const label = filtersOf(view, field, ["label"])[0];
366
- const [op, setOp] = useState(label?.op ?? "");
434
+ const label = filtersOf(view, field, ["text"])[0];
435
+ const [op, setOp] = useState(label ? ruleOp(label) : "");
367
436
  const [text, setText] = useState(label?.value ?? "");
368
437
  if (!info) {
369
438
  return null;
@@ -371,7 +440,7 @@ function FilterBody({ view: current, base, field, encoded, locale, labels, commi
371
440
  const name = fieldLabel(field, labels.core);
372
441
  const apply = () => {
373
442
  let next = setItemFilter(view, field, all.filter((v) => selected.has(keyOf(v))), all);
374
- next = setLabelFilter(next, field, op ? { op, value: text } : null);
443
+ next = setLabelFilter(next, field, op ? { op, value: text, on: textOn(encoded, field) } : null);
375
444
  close();
376
445
  commit(next, { step: "filter", field: name });
377
446
  };
@@ -386,21 +455,21 @@ function FilterBody({ view: current, base, field, encoded, locale, labels, commi
386
455
  }
387
456
  },
388
457
  /* @__PURE__ */ React.createElement("div", { className: "pk-popover-head" }, /* @__PURE__ */ React.createElement("h3", null, fill(labels.filterTitle, { field: name })), /* @__PURE__ */ React.createElement("span", { className: "pk-muted" }, fill(labels.selected, { count: selected.size.toLocaleString(locale) }))),
389
- /* @__PURE__ */ React.createElement(ValueList, { items: info.items, selected, onChange: setSelected, labels, locale, autoFocus: true }, kind ? /* @__PURE__ */ React.createElement("fieldset", { className: "pk-condition" }, /* @__PURE__ */ React.createElement("legend", null, kind === "number" ? labels.conditionNumber : labels.condition), /* @__PURE__ */ React.createElement("select", { name: `${formName}-op`, value: op, onChange: (e) => setOp(e.target.value), "aria-label": kind === "number" ? labels.conditionNumber : labels.condition }, /* @__PURE__ */ React.createElement("option", { value: "" }, labels.conditionNone), CATALOG2.labelOps.map((o) => /* @__PURE__ */ React.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))), op ? /* @__PURE__ */ React.createElement(
458
+ /* @__PURE__ */ React.createElement(ValueList, { items: info.items, selected, onChange: setSelected, labels, locale, autoFocus: true }, kind ? /* @__PURE__ */ React.createElement("fieldset", { className: "pk-condition" }, /* @__PURE__ */ React.createElement("legend", null, kind === "number" ? labels.conditionNumber : labels.condition), /* @__PURE__ */ React.createElement("select", { name: `${formName}-op`, value: op, onChange: (e) => setOp(e.target.value), "aria-label": kind === "number" ? labels.conditionNumber : labels.condition }, /* @__PURE__ */ React.createElement("option", { value: "" }, labels.conditionNone), RULE_OPS.text.map((o) => /* @__PURE__ */ React.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))), op ? /* @__PURE__ */ React.createElement(
390
459
  ClearInput,
391
460
  {
392
461
  type: "text",
393
462
  value: text,
394
463
  onChange: setText,
395
464
  onClear: () => {
396
- if (!base && filtersOf(view, field, ["label"]).length) {
465
+ if (!base && filtersOf(view, field, ["text"]).length) {
397
466
  commit(setLabelFilter(view, field, null), { step: "filter", field: name });
398
467
  }
399
468
  },
400
469
  clearLabel: labels.clearText,
401
470
  "aria-label": labels.conditionValue,
402
471
  placeholder: labels.conditionValue,
403
- maxLength: 1e3,
472
+ maxLength: LIMITS.textValue,
404
473
  "data-testid": "filter-condition-text"
405
474
  }
406
475
  ) : null) : null),
@@ -431,10 +500,10 @@ function Section({ title, children, info }) {
431
500
  }
432
501
 
433
502
  // src/menu-topics.js
434
- import { CATALOG as CATALOG3, aggregatorsFor, fieldLabel as fieldLabel2, formatter, isFormat as isFormat2 } from "pivotkit-core";
503
+ import { CATALOG as CATALOG2, aggregatorsFor, fieldLabel as fieldLabel2, formatter, isFormat as isFormat2 } from "pivotkit-core";
435
504
  var FORMAT_CHOICES = Object.freeze(["number", "number:0", "number:2", "currency", "percent"].filter(isFormat2));
436
505
  var MORE_FORMATS = Object.freeze(["integer", "compact", "bytes", "duration:h", "duration:s"].filter(isFormat2));
437
- var COMMON_SHOW_AS = CATALOG3.showAs.filter((s) => ["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal"].includes(s));
506
+ var COMMON_SHOW_AS = CATALOG2.showAs.filter((s) => ["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal"].includes(s));
438
507
  var EXAMPLE = Object.freeze({ percent: 0.256, bytes: 1536e3, "duration:h": 1.5, "duration:s": 3725 });
439
508
  var TOP_COUNTS = Object.freeze([3, 5, 10]);
440
509
  function moveTopic(view, zone, index, count, labels, name, type, defaults) {
@@ -509,8 +578,8 @@ function axisTopics({ view, zone, index, field, types, labels, locale, state, de
509
578
  state: grouping ? labels.units[grouping.by] ?? grouping.by : labels.groupNoneShort,
510
579
  changed: Boolean(grouping),
511
580
  groups: [
512
- { title: labels.groupTimeline, choices: CATALOG3.timelineUnits.map(unit) },
513
- { title: labels.groupCyclic, choices: CATALOG3.cyclicUnits.map(unit) },
581
+ { title: labels.groupTimeline, choices: CATALOG2.timelineUnits.map(unit) },
582
+ { title: labels.groupCyclic, choices: CATALOG2.cyclicUnits.map(unit) },
514
583
  { choices: [{ id: "group-none", text: labels.groupNone, checked: !grouping, closes: true, change: regroup(null) }] }
515
584
  ]
516
585
  });
@@ -550,19 +619,21 @@ function filterTopic({ view, field, labels, locale, state, encoded }) {
550
619
  if (!Number.isSafeInteger(n) || n < 1) {
551
620
  return [];
552
621
  }
553
- const units = n > CATALOG3.relativeMaxCount ? [] : fk.months ? ["year", "month"] : ["year"];
622
+ const units = n > CATALOG2.relativeMaxCount ? [] : fk.months ? ["year", "month"] : ["year"];
554
623
  const anchor = filtersOf(view, field, ["relative"])[0]?.anchor;
624
+ const previous = quickChoice(view, field, fk).filters[0] ?? null;
625
+ const blanks = keepsBlanks(view, field) ? "include" : "exclude";
555
626
  const span = dateSpan(encoded, sourceOf(view, field));
556
627
  const ranges = units.map((unit) => {
557
628
  const text = capital2(relativeText({ unit, count: n, anchor }, labels, locale, timeZone, void 0, span));
558
- return { id: `quick-${unit}-${n}`, text, choice: { id: `quick-${unit}-${n}`, text, change: () => ({ view: setQuickRange(view, field, { unit, count: n, anchor }), note }) } };
629
+ return { id: `quick-${unit}-${n}`, text, choice: { id: `quick-${unit}-${n}`, text, change: () => ({ view: setQuickRange(view, field, { unit, count: n, anchor, blanks }, previous), note }) } };
559
630
  });
560
631
  const keyed = fk.item === "group" && n >= 1e3 && n <= 9999 && view.derived.some((d) => d.name.toLowerCase() === field.toLowerCase() && d.by === "year");
561
632
  if (!keyed) {
562
633
  return ranges;
563
634
  }
564
635
  const compares = [">=", "<=", "<", ">"].map((op) => {
565
- const entry = { field, type: "compare", op, value: n };
636
+ const entry = { field, type: "compare", op, value: n, not: false, blanks: "exclude" };
566
637
  const text = capital2(fill(labels.compareShort[op], { value: String(n) }));
567
638
  return { id: `compare-${op}-${n}`, text, choice: { id: `compare-${op}-${n}`, text, change: () => ({ view: setRule(view, field, null, entry), note }) } };
568
639
  });
@@ -579,7 +650,8 @@ function filterTopic({ view, field, labels, locale, state, encoded }) {
579
650
  // the rules are found by their names, and open the level on them
580
651
  searchExtra: [
581
652
  { id: "open-filter-rules", text: labels.rulesTitle, focus: "conditions" },
582
- { id: "open-filter-text", text: labels.addRuleName, focus: "conditions" },
653
+ // the rule on the name by its operators too ("does not begin with")
654
+ { id: "open-filter-text", text: labels.addRuleName, focus: "conditions", keywords: Object.values(labels.labelOps).join(" ") },
583
655
  { id: "open-filter-value", text: labels.addRuleTotal, focus: "conditions" }
584
656
  ],
585
657
  searchFor
@@ -612,7 +684,7 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
612
684
  const set = (patch) => () => ({ view: updateValue(view, index, patch, { defaults }), note: { step: "value", field: name } });
613
685
  const aggs = spec.field ? aggregatorsFor(type) : ["count"];
614
686
  const agg = (a) => ({ id: `agg-${a}`, text: labels.core.aggregators[a] ?? a, checked: spec.agg === a, closes: true, change: set({ agg: a }) });
615
- const rare = aggs.filter((a) => !CATALOG3.commonAggregators.includes(a));
687
+ const rare = aggs.filter((a) => !CATALOG2.commonAggregators.includes(a));
616
688
  const topics = [
617
689
  {
618
690
  id: "summarize",
@@ -620,7 +692,7 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
620
692
  kind: "menu",
621
693
  icon: "sigma",
622
694
  state: labels.core.aggregators[spec.agg] ?? spec.agg,
623
- groups: [{ choices: CATALOG3.commonAggregators.filter((a) => aggs.includes(a)).map(agg) }, ...rare.length ? [{ title: labels.moreStatistics, choices: rare.map(agg) }] : []]
695
+ groups: [{ choices: CATALOG2.commonAggregators.filter((a) => aggs.includes(a)).map(agg) }, ...rare.length ? [{ title: labels.moreStatistics, choices: rare.map(agg) }] : []]
624
696
  }
625
697
  ];
626
698
  if (numericResult(spec, type)) {
@@ -628,7 +700,7 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
628
700
  const text = labels.showAsNames[s] ?? s;
629
701
  return { id: `showas-${s}`, text, keywords: text.includes("%") ? labels.showAsKeywords : void 0, checked: spec.showAs?.type === s, change: set({ showAs: { type: s, axis: spec.showAs?.axis ?? "rows" } }) };
630
702
  };
631
- const along = spec.showAs && CATALOG3.showAsAlongAxis.includes(spec.showAs.type) ? spec.showAs : null;
703
+ const along = spec.showAs && CATALOG2.showAsAlongAxis.includes(spec.showAs.type) ? spec.showAs : null;
632
704
  topics.push({
633
705
  id: "showAs",
634
706
  title: labels.showAs,
@@ -639,7 +711,7 @@ function valueTopics({ view, index, types, labels, locale, defaultsOf, earlier }
639
711
  changed: Boolean(spec.showAs),
640
712
  groups: [
641
713
  { choices: [{ id: "showas-none", text: labels.showAsNone, checked: !spec.showAs, change: set({ showAs: null }) }, ...COMMON_SHOW_AS.map(showAs)] },
642
- { title: labels.moreCalculations, choices: CATALOG3.showAs.filter((s) => !COMMON_SHOW_AS.includes(s)).map(showAs) },
714
+ { title: labels.moreCalculations, choices: CATALOG2.showAs.filter((s) => !COMMON_SHOW_AS.includes(s)).map(showAs) },
643
715
  ...along ? [{ title: labels.along, choices: ["rows", "cols"].map((axis) => ({ id: `along-${axis}`, text: labels.zones[axis], checked: along.axis === axis, change: set({ showAs: { ...along, axis } }) })) }] : []
644
716
  ]
645
717
  });
@@ -722,7 +794,7 @@ function optionTopics({ view, labels, folding, tips, explanations, act }) {
722
794
  {
723
795
  choices: TOTALS.map((key) => {
724
796
  const why = totalNoEffect(view, key);
725
- return { id: `total-${key}`, text: labels[key], checkbox: true, checked: view.totals[key], disabled: why !== null, reason: why ? labels[why] : void 0, info: key, run: () => act.total(key, !view.totals[key]) };
797
+ return { id: `total-${key}`, text: labels[key], checkbox: true, checked: why === null && view.totals[key], disabled: why !== null, reason: why ? labels[why] : void 0, info: key, run: () => act.total(key, !view.totals[key]) };
726
798
  })
727
799
  }
728
800
  ]
@@ -760,7 +832,7 @@ function searchEntries(topics, query = "") {
760
832
  return [];
761
833
  }
762
834
  const typed = query && topic.searchFor ? topic.searchFor(query) : [];
763
- const extra = [...typed, ...topic.searchExtra ?? []].map((x) => ({ id: x.id, text: x.text, path: topic.title, topic, choice: x.choice, focus: x.focus }));
835
+ const extra = [...typed, ...topic.searchExtra ?? []].map((x) => ({ id: x.id, text: x.text, path: topic.title, topic, choice: x.choice, focus: x.focus, keywords: x.keywords }));
764
836
  return topic.kind === "panel" ? [{ id: `open-${topic.id}`, text: topic.title, path: "", topic }, ...extra] : (topic.groups ?? []).flatMap((g) => g.choices.map((choice) => ({ id: choice.id, text: choice.text, path: [topic.title, g.title].filter(Boolean).join(" \u203A "), topic, choice })));
765
837
  });
766
838
  }
@@ -772,7 +844,7 @@ function searchHits(entries, query, locale) {
772
844
  return [];
773
845
  }
774
846
  const found = entries.filter((e) => {
775
- const text = lower(`${e.text} ${e.path} ${e.topic.keywords ?? ""} ${e.choice?.keywords ?? ""}`);
847
+ const text = lower(`${e.text} ${e.path} ${e.topic.keywords ?? ""} ${e.choice?.keywords ?? e.keywords ?? ""}`);
776
848
  return words.every((w) => text.includes(w));
777
849
  });
778
850
  const own = (e) => lower(e.choice?.keywords ?? "").split(/\s+/).includes(words[0]);
@@ -1340,26 +1412,17 @@ function measuresOf(view, types, labels, ref) {
1340
1412
  var twin = (op) => op === "between" || op === "notBetween";
1341
1413
  var capital = (text, locale) => text.charAt(0).toLocaleUpperCase(locale) + text.slice(1);
1342
1414
  var rulesKeyOf = (rules) => JSON.stringify(rules, (_k, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : 1)) : v);
1343
- var rowKind = (f) => f.type === "value" ? "total" : f.type === "label" ? "name" : "item";
1344
- var REACH = Object.freeze({ year: 10, month: 24, day: 90 });
1415
+ var rowKind = (f) => !editable(f) ? "fixed" : f.type === "value" ? "total" : f.type === "text" ? "name" : "item";
1416
+ var RANGE_UNITS = Object.freeze(["year", "month", "day"]);
1417
+ var ruleRange = (f) => plainRange(f) && (f.direction ?? "last") === "last" && f.includeCurrent !== false && RANGE_UNITS.includes(f.unit);
1418
+ var editable = (f) => !hiddenNot(f) && (f.type !== "relative" || ruleRange(f)) && (f.type !== "compare" || (f.precision ?? "day") === "day");
1419
+ var REACH = Object.freeze({ year: 10, quarter: 12, month: 24, week: 104, day: 90 });
1345
1420
  var PICKER_MIN = 13;
1346
- var MS_PER_DAY = 864e5;
1347
1421
  function nounOf(fk, labels) {
1348
1422
  const unit = fk.unit;
1349
1423
  const key = unit === null ? fk.item === "number" ? "value" : fk.item === "date" ? "date" : "item" : unit === "bin" ? "range" : unit === "day" ? "day" : unit.replace(/^year(.)/, (_m, c) => c.toLowerCase());
1350
1424
  return Object.hasOwn(labels.nouns, key) ? labels.nouns[key] : labels.nouns.item;
1351
1425
  }
1352
- function rowsIn(range, column, counts) {
1353
- const from = Date.parse(`${range.from}T00:00Z`);
1354
- const to = Date.parse(`${range.to}T00:00Z`) + MS_PER_DAY;
1355
- let rows = 0;
1356
- column.dict.forEach((v, code) => {
1357
- if (typeof v === "number" && v >= from && v < to) {
1358
- rows += counts[code];
1359
- }
1360
- });
1361
- return rows;
1362
- }
1363
1426
  function countsOf(column) {
1364
1427
  const counts = new Float64Array(column.dict.length);
1365
1428
  for (let i = 0; i < column.codes.length; i++) {
@@ -1430,155 +1493,268 @@ function Summary({ ctx, state }) {
1430
1493
  }
1431
1494
  return /* @__PURE__ */ React5.createElement("div", { className: "pk-filter-summary" }, /* @__PURE__ */ React5.createElement("div", { className: `pk-summary-card${shown === 0 ? " pk-summary-empty" : ""}`, role: "status", "data-testid": "filter-summary" }, /* @__PURE__ */ React5.createElement("p", { className: "pk-summary-head", "data-testid": "filter-summary-head" }, head), /* @__PURE__ */ React5.createElement("p", { className: "pk-summary-why", "data-testid": "filter-summary-why" }, why.length ? why.join(" \xB7 ") : state.rules ? labels.summaryKept : quickWords ? fill(labels.summaryQuickOnly, { quick: quickWords }) : labels.summaryOk), /* @__PURE__ */ React5.createElement("p", { className: "pk-summary-meta", "data-testid": "filter-summary-meta" }, meta.join(" \xB7 ")), /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-action pk-summary-reset", disabled: !state.canReset, onClick: () => ctx.act(resetFilter(view, field), "section-picks"), "data-testid": "filter-reset" }, labels.resetFilter)));
1432
1495
  }
1433
- function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts }) {
1496
+ var COUNTED = Object.freeze(["last", "next", "before"]);
1497
+ var MORE = Object.freeze(["next", "before"]);
1498
+ var inMore = (quick) => MORE.includes(quick.id) || COUNTED.includes(quick.id) && quick.calendar === false;
1499
+ function QuickChoices({ ctx, quick, anchor, setAnchorLocal, span, column, counts, moreOpen, setMoreOpen }) {
1434
1500
  const { view, field, labels, locale, fk, timeZone, commit, note, back } = ctx;
1435
1501
  const lang = { lang: labels.lang, locale };
1436
- const latest = span.max;
1437
- const latestDay = isoDay(latest);
1502
+ const more = labels.relativeMore;
1503
+ const units = fk.units;
1504
+ const weekStart = view.formatting?.weekStart;
1505
+ const latestDay = isoDay(span.max);
1438
1506
  const [now] = useState3(() => Date.now());
1439
- const days = (unit, count) => relativeDays({ unit, count, anchor }, timeZone, now, latest);
1507
+ const datesOf = (spec, at = anchor) => {
1508
+ try {
1509
+ return relativeDateRange(spec.unit, spec.count ?? 1, { ...spec, anchor: at, timeZone, now, latest: span.max, first: span.min, weekStart });
1510
+ } catch {
1511
+ return null;
1512
+ }
1513
+ };
1514
+ const rowsOf = (range) => range ? rowsInRange(range, column.dict, counts) : 0;
1515
+ const reaches = (r) => r !== null && r.from !== null && r.from.slice(0, 10) <= latestDay;
1440
1516
  const reach = (unit) => {
1441
1517
  for (let n = 1; n <= REACH[unit]; n++) {
1442
- const r = days(unit, n);
1443
- if (r && r.from <= latestDay) {
1518
+ if (reaches(datesOf({ unit, count: n }))) {
1444
1519
  return n;
1445
1520
  }
1446
1521
  }
1447
- return null;
1522
+ return REACH[unit];
1448
1523
  };
1449
- const defaults = useMemo2(() => ({ year: Math.max(2, reach("year") ?? REACH.year), month: reach("month") ?? REACH.month, day: reach("day") ?? REACH.day }), [anchor, latest, timeZone]);
1450
- const counted = { year: quick.id === "years" ? quick.count : defaults.year, month: quick.id === "months" ? quick.count : defaults.month, day: quick.id === "days" ? quick.count : defaults.day };
1451
- const [texts, setTexts] = useState3(() => Object.fromEntries(Object.entries(counted).map(([u, n]) => [u, numberText(n, locale)])));
1524
+ const defaultCount = (unit) => Math.max(2, reach(unit));
1525
+ const firstUnit = units.includes("month") ? "month" : units[0];
1526
+ const readCount = (text) => readNumber(text, { kind: "count", max: CATALOG3.relativeMaxCount, labels, locale });
1527
+ const rowOf = (d) => quick.id === d ? { text: numberText(quick.count, locale), unit: quick.unit, current: quick.includeCurrent } : { text: numberText(d === "next" ? 1 : defaultCount(firstUnit), locale), unit: firstUnit, current: true };
1528
+ const [rows, setRows] = useState3(() => Object.fromEntries(COUNTED.map((d) => [d, rowOf(d)])));
1529
+ const [thisUnit, setThisUnit] = useState3(quick.id === "this" ? quick.unit : "year");
1530
+ const [rolling, setRolling] = useState3(() => COUNTED.includes(quick.id) && quick.calendar === false);
1452
1531
  const [editing, setEditing] = useState3(
1453
1532
  /** @type {string | null} */
1454
1533
  null
1455
1534
  );
1456
- const quickKey = `${quick.id}:${quick.count ?? ""}:${anchor}`;
1535
+ const quickKey = JSON.stringify([quick.id, quick.unit, quick.count, quick.calendar, quick.includeCurrent]);
1457
1536
  const [seen, setSeen] = useState3(quickKey);
1458
1537
  if (quickKey !== seen) {
1459
1538
  setSeen(quickKey);
1460
- const synced = { ...texts };
1461
- for (const unit of CATALOG4.relativeUnits) {
1462
- if (unit !== editing) {
1463
- synced[unit] = numberText(counted[unit], locale);
1464
- }
1539
+ if (COUNTED.includes(quick.id)) {
1540
+ const d = quick.id;
1541
+ const own = rowOf(d);
1542
+ setRows({ ...rows, [d]: editing === d ? { ...own, text: rows[d].text } : own });
1543
+ setRolling(quick.calendar === false);
1544
+ } else if (quick.id === "this") {
1545
+ setThisUnit(
1546
+ /** @type {string} */
1547
+ quick.unit
1548
+ );
1465
1549
  }
1466
- setTexts(synced);
1467
1550
  }
1468
1551
  const later = useLater();
1469
1552
  const group = useId3();
1470
1553
  const groupName = useFormName();
1471
- const set = (range) => commit(setQuickRange(view, field, range ? { ...range, anchor } : null), note);
1554
+ const formName = useFormName();
1555
+ const anchorId = useId3();
1556
+ const moreId = useId3();
1557
+ const set = (spec) => commit(setQuickRange(view, field, spec ? { ...spec, anchor, blanks: ctx.keepBlanks ? "include" : "exclude" } : null, quick.filters[0] ?? null), note);
1558
+ const specOf = (d, row = rows[d], roll = rolling) => {
1559
+ const n = readCount(row.text).value;
1560
+ return n === null ? null : { direction: d, unit: row.unit, count: n, calendar: !roll, includeCurrent: row.current };
1561
+ };
1562
+ const subId = (id) => `${group}-${id}`;
1472
1563
  const sub = (range, unit, id) => {
1473
- const share = rangeShare(range, unit, span, locale);
1474
- if (share?.none) {
1564
+ if (!range) {
1475
1565
  return null;
1476
1566
  }
1477
- const period = share ? `${share.data} ` : periodText(range, unit, locale);
1478
- const missing = share ? fill(plural(labels.noData, share.count, lang), { range: share.missing.join(", ") }) : null;
1479
- return /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-sub", id: subId(id) }, /* @__PURE__ */ React5.createElement("span", null, period, missing ? /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-missing" }, "(", missing, ")") : null), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-rows" }, fill(labels.quickRows, { rows: rowsIn(range, column, counts).toLocaleString(locale) })));
1567
+ const shownUnit = range.from === null || range.from.length > 10 || range.to.length > 10 ? "day" : unit;
1568
+ let period;
1569
+ let missing = null;
1570
+ if (range.from === null) {
1571
+ period = fill(more.until, { to: periodText({ from: range.to, to: range.to }, shownUnit, locale) });
1572
+ } else {
1573
+ const share = rangeShare(range, shownUnit, span, locale);
1574
+ if (share?.none) {
1575
+ period = "";
1576
+ missing = fill(plural(labels.noData, 1, lang), { range: periodText(range, shownUnit, locale) });
1577
+ } else {
1578
+ period = share ? `${share.data} ` : periodText(range, shownUnit, locale);
1579
+ missing = share ? fill(plural(labels.noData, share.count, lang), { range: share.missing.join(", ") }) : null;
1580
+ }
1581
+ }
1582
+ 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" }, period ? `(${missing})` : missing) : null), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-rows" }, fill(labels.quickRows, { rows: rowsOf(range).toLocaleString(locale) })));
1480
1583
  };
1481
- const subId = (id) => `${group}-${id}`;
1482
- const radio = (id, checked, onPick, name, children, sub2, described = Boolean(sub2)) => /* @__PURE__ */ React5.createElement("label", { className: "pk-radio pk-quick", key: id }, /* @__PURE__ */ React5.createElement("input", { type: "radio", name: groupName, checked, onChange: onPick, "aria-label": name, "aria-describedby": described ? subId(id) : void 0, "data-autofocus": checked && ctx.hint !== "conditions" ? "" : void 0, "data-testid": `quick-${id}` }), children, sub2);
1584
+ const radio = (id, checked, onPick, name, children, described = true) => /* @__PURE__ */ React5.createElement("label", { className: "pk-radio pk-quick" }, /* @__PURE__ */ React5.createElement(
1585
+ "input",
1586
+ {
1587
+ type: "radio",
1588
+ name: groupName,
1589
+ checked,
1590
+ onChange: onPick,
1591
+ "aria-label": name,
1592
+ "aria-describedby": described ? subId(id) : void 0,
1593
+ "data-autofocus": checked && ctx.hint !== "conditions" ? "" : void 0,
1594
+ "data-testid": `quick-${id}`
1595
+ }
1596
+ ), children);
1597
+ const unitPick = (value, options, onChange, testId, label) => options.length > 1 ? /* @__PURE__ */ React5.createElement("select", { name: `${formName}-${testId}`, value, onChange: (e) => onChange(e.target.value), "aria-label": label, "data-testid": testId }, options.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o.value, value: o.value }, o.text))) : /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, options[0]?.text);
1483
1598
  const hidden = [];
1484
- const rows = [radio("all", quick.id === "all" || quick.id === "custom", () => set(null), labels.filterAll, /* @__PURE__ */ React5.createElement("span", null, labels.filterAll), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-sub", id: subId("all") }, /* @__PURE__ */ React5.createElement("span", null, `${dayText(isoDay(span.min), locale)}\u2013${dayText(latestDay, locale)}`), /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-rows" }, fill(labels.quickRows, { rows: column.codes.length.toLocaleString(locale) }))))];
1485
- const thisYear = days("year", 1);
1486
- const yearWords = capital(labels.relative.year, locale);
1487
- if (thisYear && sub(thisYear, "year", "thisYear")) {
1488
- rows.push(radio("thisYear", quick.id === "thisYear", () => set({ unit: "year", count: 1 }), yearWords, /* @__PURE__ */ React5.createElement("span", null, yearWords), sub(thisYear, "year", "thisYear")));
1489
- } else if (thisYear) {
1490
- hidden.push(`${yearWords} (${periodText(thisYear, "year", locale)})`);
1491
- }
1492
- for (
1493
- const unit of
1494
- /** @type {const} */
1495
- ["year", "month", "day"]
1496
- ) {
1497
- if (unit === "month" && !fk.months || unit === "day" && !fk.days) {
1498
- continue;
1499
- }
1500
- const read = readNumber(texts[unit], { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale });
1501
- const n = read.value;
1502
- const id = `${unit}s`;
1503
- const shown = n ?? counted[unit];
1504
- const forms = Object.fromEntries(Object.entries(labels.quickLast[unit]).map(([k, v]) => [k, String(v).replace("{count}", "{n}")]));
1505
- const words = plural(forms, shown, lang);
1506
- const [before, after] = words.split("{n}");
1507
- const range = days(unit, shown);
1508
- const line = range ? sub(range, unit, id) : null;
1509
- if (!line) {
1510
- if (quick.id !== id) {
1511
- hidden.push(fill(words, { n: shown.toLocaleString(locale) }));
1512
- continue;
1599
+ const main = [
1600
+ /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-row", key: "all" }, radio("all", quick.id === "all", () => 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) }))))
1601
+ ];
1602
+ const thisUnits = units.filter((u) => rowsOf(datesOf({ direction: "this", unit: u })) > 0 || quick.id === "this" && quick.unit === u);
1603
+ if (thisUnits.length) {
1604
+ const u = thisUnits.includes(thisUnit) ? thisUnit : thisUnits[thisUnits.length - 1];
1605
+ const name = capital(more.this[u], locale);
1606
+ main.push(
1607
+ /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-row", key: "this" }, radio("this", quick.id === "this", () => set({ direction: "this", unit: u }), name, thisUnits.length > 1 ? null : /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, name)), thisUnits.length > 1 && unitPick(
1608
+ u,
1609
+ thisUnits.map((o) => ({ value: o, text: capital(more.this[o], locale) })),
1610
+ (v) => {
1611
+ setThisUnit(v);
1612
+ set({ direction: "this", unit: v });
1613
+ },
1614
+ "quick-this-unit",
1615
+ labels.quickThisUnit
1616
+ ), sub(datesOf({ direction: "this", unit: u }), u, "this"))
1617
+ );
1618
+ } else {
1619
+ const year = datesOf({ direction: "this", unit: "year" });
1620
+ if (year?.from) {
1621
+ hidden.push(`${capital(more.this.year, locale)} (${periodText({ from: year.from, to: year.to }, "year", locale)})`);
1622
+ }
1623
+ }
1624
+ const counted = (d) => {
1625
+ const row = rows[d];
1626
+ const read = readCount(row.text);
1627
+ const n = read.value ?? 2;
1628
+ const formOf = (unit) => plural(Object.fromEntries(Object.entries(more[d][unit]).map(([k, v]) => [k, String(v).replace("{count}", "{n}")])), n, lang);
1629
+ const [before] = formOf(row.unit).split("{n}");
1630
+ const name = capital(fill(formOf(row.unit), { n: n.toLocaleString(locale) }), locale);
1631
+ const range = datesOf({ direction: d, unit: row.unit, count: n, calendar: !rolling, includeCurrent: row.current });
1632
+ const change = (patch, wait = false) => {
1633
+ const next = { ...row, ...patch };
1634
+ setRows({ ...rows, [d]: next });
1635
+ const run = () => {
1636
+ const spec = specOf(d, next);
1637
+ if (spec) {
1638
+ set(spec);
1639
+ }
1640
+ };
1641
+ if (wait) {
1642
+ later.later(run);
1643
+ } else {
1644
+ later.cancel();
1645
+ run();
1513
1646
  }
1514
- }
1515
- const pick = () => set({ unit, count: shown });
1516
- rows.push(
1517
- /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-row", key: unit }, radio(id, quick.id === id, pick, fill(words, { n: shown.toLocaleString(locale) }), /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, before), null, Boolean(line)), /* @__PURE__ */ React5.createElement(
1518
- NumberField,
1519
- {
1520
- value: texts[unit],
1521
- onChange: (t) => {
1522
- setTexts({ ...texts, [unit]: t });
1523
- later.later(() => {
1524
- const v = readNumber(t, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale }).value;
1525
- if (v !== null) {
1526
- set({ unit, count: v });
1527
- }
1528
- });
1529
- },
1530
- onKeyDown: fieldKeys({
1531
- now: later.now,
1532
- restore: () => {
1533
- later.cancel();
1534
- const was = numberText(counted[unit], locale);
1535
- if (texts[unit] === was) {
1536
- return false;
1537
- }
1538
- setTexts({ ...texts, [unit]: was });
1539
- return true;
1540
- },
1541
- back
1542
- }),
1543
- onBlur: () => {
1544
- setEditing(null);
1545
- later.now();
1647
+ };
1648
+ const pickUnit = (unit) => {
1649
+ const r = d === "last" && read.value !== null ? datesOf({ unit, count: read.value, calendar: !rolling, includeCurrent: row.current }) : null;
1650
+ const keep = d !== "last" || reaches(r);
1651
+ change({ unit, ...keep ? {} : { text: numberText(defaultCount(unit), locale) } });
1652
+ };
1653
+ const current = datesOf({ direction: "this", unit: row.unit });
1654
+ const currentEmpty = current?.from ? rowsOf(current) === 0 : false;
1655
+ return /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-row", key: d }, radio(d, quick.id === d, () => change({}), name, /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, capital(before.trimEnd(), locale)), range !== null), /* @__PURE__ */ React5.createElement(
1656
+ NumberField,
1657
+ {
1658
+ value: row.text,
1659
+ onChange: (t) => change({ text: t }, true),
1660
+ onKeyDown: fieldKeys({
1661
+ now: later.now,
1662
+ restore: () => {
1663
+ later.cancel();
1664
+ if (quick.id !== d) {
1665
+ return false;
1666
+ }
1667
+ const was = numberText(
1668
+ /** @type {number} */
1669
+ quick.count,
1670
+ locale
1671
+ );
1672
+ if (row.text === was) {
1673
+ return false;
1674
+ }
1675
+ setRows({ ...rows, [d]: { ...row, text: was } });
1676
+ return true;
1546
1677
  },
1547
- onFocus: () => setEditing(unit),
1548
- problem: read.problem,
1549
- label: labels.quickCount[unit],
1550
- testId: `quick-${id}-count`,
1551
- className: "pk-field-label pk-count-input"
1552
- }
1553
- ), /* @__PURE__ */ React5.createElement("span", { "aria-hidden": "true" }, after), line)
1554
- );
1555
- }
1678
+ back
1679
+ }),
1680
+ onBlur: () => {
1681
+ setEditing(null);
1682
+ later.now();
1683
+ },
1684
+ onFocus: () => setEditing(d),
1685
+ problem: read.problem,
1686
+ label: labels.quickCount[row.unit] ?? labels.quickCount.year,
1687
+ testId: `quick-${d}-count`,
1688
+ className: "pk-field-label pk-count-input"
1689
+ }
1690
+ ), unitPick(
1691
+ row.unit,
1692
+ units.map((u) => ({ value: u, text: formOf(u).split("{n}")[1]?.trim() ?? u })),
1693
+ pickUnit,
1694
+ `quick-${d}-unit`,
1695
+ fill(labels.quickUnitOf, { choice: capital(before.trimEnd(), locale) })
1696
+ ), sub(range, row.unit, d), quick.id === d && !rolling ? /* @__PURE__ */ React5.createElement("label", { className: "pk-check pk-quick-current" }, /* @__PURE__ */ React5.createElement("input", { type: "checkbox", name: `${formName}-${d}-current`, checked: row.current, onChange: (e) => change({ current: e.target.checked }), "data-testid": `quick-${d}-current` }), /* @__PURE__ */ React5.createElement("span", null, labels.quickCurrent[row.unit], currentEmpty ? /* @__PURE__ */ React5.createElement("span", { className: "pk-quick-missing" }, ` (${fill(plural(labels.noData, 1, lang), { range: current?.from ? periodText({ from: current.from, to: current.to }, row.unit, locale) : "" })})`) : null)) : null, quick.id === d && d !== "next" && currentEmpty && anchor === "today" ? /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-fix" }, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-btn pk-small-btn", onClick: () => setAnchorTo("latest"), "data-testid": `quick-${d}-from-latest` }, /* @__PURE__ */ React5.createElement(Icon, { name: "date", size: 14 }), /* @__PURE__ */ React5.createElement("span", { className: "pk-btn-text" }, fill(labels.anchorUseLatest, { date: dayText(latestDay, locale) })))) : null);
1697
+ };
1698
+ main.push(counted("last"));
1556
1699
  const today = new Date(relativeDays({ unit: "day", count: 1 }, timeZone, now)?.from ?? isoDay(now));
1557
1700
  const periodStart = fk.months ? Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1) : Date.UTC(today.getUTCFullYear(), 0, 1);
1558
- const showAnchor = latest < periodStart;
1559
- const anchorId = useId3();
1560
- const anchorName = useFormName();
1561
- return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("div", { role: "radiogroup", "aria-label": labels.quickTitle, className: "pk-radios pk-quick-choices", "data-testid": "quick-choices" }, rows), showAnchor ? /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-anchor" }, /* @__PURE__ */ React5.createElement("label", { htmlFor: anchorId }, labels.anchorLabel), /* @__PURE__ */ React5.createElement(
1562
- "select",
1701
+ const [anchorOutside] = useState3(() => span.max < periodStart || anchor !== "today");
1702
+ const anchorKind = ["today", "latest", "first"].includes(anchor) ? anchor : "date";
1703
+ const [day, setDay] = useState3(anchorKind === "date" ? anchor.slice(0, 10) : latestDay);
1704
+ const dayWhole = /^\d{4}-\d{2}-\d{2}$/.test(day);
1705
+ const [seenAnchor, setSeenAnchor] = useState3(anchor);
1706
+ if (anchor !== seenAnchor) {
1707
+ setSeenAnchor(anchor);
1708
+ if (anchorKind === "date") {
1709
+ setDay(anchor.slice(0, 10));
1710
+ }
1711
+ }
1712
+ const dayHint = `${anchorId}-hint`;
1713
+ const setAnchorTo = (a) => {
1714
+ setAnchorLocal(a);
1715
+ if (quick.filters.length) {
1716
+ commit(setAnchor(view, field, a), note);
1717
+ }
1718
+ };
1719
+ const anchorRow = /* @__PURE__ */ React5.createElement("div", { className: "pk-quick-anchor" }, /* @__PURE__ */ React5.createElement("label", { htmlFor: anchorId }, labels.anchorLabel), /* @__PURE__ */ React5.createElement("select", { id: anchorId, name: `${formName}-anchor`, value: anchorKind, onChange: (e) => setAnchorTo(e.target.value === "date" ? dayWhole ? day : latestDay : e.target.value), "data-testid": "quick-anchor" }, /* @__PURE__ */ React5.createElement("option", { value: "today" }, fill(labels.anchorToday, { date: dayText(isoDay(today.getTime()), locale) })), /* @__PURE__ */ React5.createElement("option", { value: "latest" }, fill(labels.anchorLatest, { date: dayText(latestDay, locale) })), /* @__PURE__ */ React5.createElement("option", { value: "first" }, fill(labels.anchorFirst, { date: dayText(isoDay(span.min), locale) })), /* @__PURE__ */ React5.createElement("option", { value: "date" }, labels.anchorDate)), anchorKind === "date" ? /* @__PURE__ */ React5.createElement(
1720
+ "input",
1563
1721
  {
1564
- id: anchorId,
1565
- name: anchorName,
1566
- value: anchor,
1722
+ type: "date",
1723
+ name: `${formName}-day`,
1724
+ value: day,
1567
1725
  onChange: (e) => {
1568
- const next = (
1569
- /** @type {"today" | "latest"} */
1570
- e.target.value
1571
- );
1572
- setAnchorLocal(next);
1573
- if (quick.filters.length) {
1574
- commit(setAnchor(view, field, next), note);
1726
+ setDay(e.target.value);
1727
+ if (/^\d{4}-\d{2}-\d{2}$/.test(e.target.value)) {
1728
+ setAnchorTo(e.target.value);
1575
1729
  }
1576
1730
  },
1577
- "data-testid": "quick-anchor"
1578
- },
1579
- /* @__PURE__ */ React5.createElement("option", { value: "today" }, fill(labels.anchorToday, { date: dayText(isoDay(today.getTime()), locale) })),
1580
- /* @__PURE__ */ React5.createElement("option", { value: "latest" }, fill(labels.anchorLatest, { date: dayText(latestDay, locale) }))
1581
- )) : null, hidden.length ? /* @__PURE__ */ React5.createElement("p", { className: "pk-hint pk-quick-hidden", "data-testid": "quick-hidden" }, fill(plural(labels.quickHidden, hidden.length, lang), { choices: hidden.join(", "), latest: dayText(latestDay, locale) })) : null);
1731
+ onBlur: () => {
1732
+ if (!dayWhole) {
1733
+ setDay(anchor.slice(0, 10));
1734
+ }
1735
+ },
1736
+ "aria-label": labels.anchorDay,
1737
+ "aria-invalid": dayWhole ? void 0 : true,
1738
+ "aria-describedby": dayWhole ? void 0 : dayHint,
1739
+ "data-testid": "quick-anchor-date"
1740
+ }
1741
+ ) : null, anchorKind === "date" && !dayWhole ? /* @__PURE__ */ React5.createElement("p", { className: "pk-hint pk-quick-missing", id: dayHint, "data-testid": "quick-anchor-date-hint" }, fill(labels.anchorDayIncomplete, { date: dayText(anchor.slice(0, 10), locale) })) : null);
1742
+ 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" }, main), 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, anchorOutside ? anchorRow : null, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-quick-more-toggle", "aria-expanded": moreOpen, "aria-controls": moreId, onClick: () => setMoreOpen(!moreOpen), "data-testid": "quick-more" }, /* @__PURE__ */ React5.createElement(Icon, { name: moreOpen ? "chevronDown" : "chevronRight", size: 14 }), /* @__PURE__ */ React5.createElement("span", null, labels.quickMore)), moreOpen ? /* @__PURE__ */ React5.createElement("div", { id: moreId, className: "pk-quick-more", "data-testid": "quick-more-body" }, /* @__PURE__ */ React5.createElement("div", { role: "radiogroup", "aria-label": labels.quickMore, className: "pk-radios pk-quick-choices" }, counted("next"), counted("before")), /* @__PURE__ */ React5.createElement("label", { className: "pk-check" }, /* @__PURE__ */ React5.createElement(
1743
+ "input",
1744
+ {
1745
+ type: "checkbox",
1746
+ name: `${formName}-rolling`,
1747
+ checked: rolling,
1748
+ onChange: (e) => {
1749
+ setRolling(e.target.checked);
1750
+ const spec = COUNTED.includes(quick.id) ? specOf(quick.id, rows[quick.id], e.target.checked) : null;
1751
+ if (spec) {
1752
+ set(spec);
1753
+ }
1754
+ },
1755
+ "data-testid": "quick-rolling"
1756
+ }
1757
+ ), /* @__PURE__ */ React5.createElement("span", null, labels.quickRolling)), anchorOutside ? null : anchorRow) : null);
1582
1758
  }
1583
1759
  function YearsCombined({ ctx, years, on }) {
1584
1760
  const { view, field, labels, locale, commit, note, noun } = ctx;
@@ -1602,8 +1778,7 @@ function ItemPicker({ items, value, onChange, label, testId, labels, locale }) {
1602
1778
  );
1603
1779
  const listId = useId3();
1604
1780
  const searchName = useFormName();
1605
- const q = query.trim().toLocaleLowerCase();
1606
- const found = q ? items.filter((i) => i.label.toLocaleLowerCase().includes(q)) : items;
1781
+ const found = searchItems(items, query);
1607
1782
  const matching = found.slice(0, FILTER_LIST_MAX);
1608
1783
  const current = items.find((i) => String(i.value) === value);
1609
1784
  const show = () => {
@@ -1694,12 +1869,12 @@ function ItemRule({ rule, ctx, apply, first }) {
1694
1869
  const { field, labels, locale, fk, items } = ctx;
1695
1870
  const narrow = useContext3(LayerContext).size === "narrow";
1696
1871
  const words = fk.dates ? labels.dateOps : labels.valueOps;
1697
- const ops = fk.dates ? [...CATALOG4.valueOps, "last"] : CATALOG4.valueOps;
1872
+ const ops = fk.dates ? [...RULE_OPS.compare, "last"] : RULE_OPS.compare;
1698
1873
  const textOf = (v) => v === void 0 ? "" : fk.item === "number" ? numberText(v, locale) : String(v);
1699
1874
  const compared = rule?.type === "compare" ? rule : null;
1700
1875
  const ranged = rule?.type === "relative" ? rule : null;
1701
1876
  const [s, setS] = useState3(() => ({
1702
- op: ranged ? "last" : compared?.op ?? ">=",
1877
+ op: ranged ? "last" : compared ? ruleOp(compared) : ">=",
1703
1878
  a: textOf(compared?.value),
1704
1879
  b: textOf(compared?.value2),
1705
1880
  count: numberText(ranged?.count ?? 5, locale),
@@ -1710,11 +1885,11 @@ function ItemRule({ rule, ctx, apply, first }) {
1710
1885
  const read = (text) => fk.item === "number" ? parseNumber(text, locale) : fk.item === "date" ? /^\d{4,}-\d{2}-\d{2}$/.test(text) ? text : null : text === "" ? null : Number(text);
1711
1886
  const entryOf = (x) => {
1712
1887
  if (x.op === "last") {
1713
- const n = readNumber(x.count, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale }).value;
1714
- return n !== null ? { field, type: "relative", unit: x.unit, count: n, ...ranged?.anchor === "latest" ? { anchor: "latest" } : {} } : null;
1888
+ const n = readNumber(x.count, { kind: "count", max: CATALOG3.relativeMaxCount, labels, locale }).value;
1889
+ return n !== null ? { ...relativeRule(field, { unit: x.unit, count: n, anchor: ranged?.anchor }), ...ranged ? { not: ranged.not, blanks: ranged.blanks } : {} } : null;
1715
1890
  }
1716
1891
  const [a, b] = [read(x.a), read(x.b)];
1717
- return a === null || twin(x.op) && b === null ? null : { field, type: "compare", op: x.op, value: a, ...twin(x.op) ? { value2: b } : {} };
1892
+ return a === null || twin(x.op) && b === null ? null : { field, type: "compare", ...opOf(x.op), value: a, ...twin(x.op) ? { value2: b } : {}, blanks: compared?.blanks ?? "exclude" };
1718
1893
  };
1719
1894
  const change = (patch, wait = false) => {
1720
1895
  const next = { ...s, ...patch };
@@ -1759,7 +1934,7 @@ function ItemRule({ rule, ctx, apply, first }) {
1759
1934
  };
1760
1935
  const label = fk.item === "date" ? labels.ruleDate : labels.ruleValue;
1761
1936
  const lang = { lang: labels.lang, locale };
1762
- const counted = readNumber(s.count, { kind: "count", max: CATALOG4.relativeMaxCount, labels, locale });
1937
+ const counted = readNumber(s.count, { kind: "count", max: CATALOG3.relativeMaxCount, labels, locale });
1763
1938
  const many = counted.value ?? 2;
1764
1939
  return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-subject" }, fieldLabel3(field, labels.core)), /* @__PURE__ */ React5.createElement("select", { className: "pk-rule-op", name: `${formName}-op`, value: s.op, onChange: (e) => change({ op: e.target.value }), "aria-label": labels.valueFilterOp, "data-autofocus": first ? "" : void 0, "data-testid": "rule-item-op" }, ops.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, o === "last" ? plural(labels.lastOp, many, lang) : words[o] ?? o))), s.op === "last" ? /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement(
1765
1940
  NumberField,
@@ -1773,12 +1948,12 @@ function ItemRule({ rule, ctx, apply, first }) {
1773
1948
  testId: "rule-last-count",
1774
1949
  className: "pk-field-label pk-count-input"
1775
1950
  }
1776
- ), /* @__PURE__ */ React5.createElement("select", { name: `${formName}-unit`, value: s.unit, onChange: (e) => change({ unit: e.target.value }), "aria-label": labels.ruleUnit, "data-testid": "rule-last-unit" }, CATALOG4.relativeUnits.map((u) => /* @__PURE__ */ React5.createElement("option", { key: u, value: u }, plural(labels.ruleUnits[u], many, lang))))) : /* @__PURE__ */ React5.createElement(React5.Fragment, null, value("a", label, "rule-item-value"), twin(s.op) ? /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", null, labels.valueFilterTo), value("b", `${labels.valueFilterTo} ${label}`, "rule-item-value2")) : null, s.op === "!=" || s.op === "notBetween" ? /* @__PURE__ */ React5.createElement("span", { className: "pk-hint pk-rule-note", "data-testid": "rule-blanks" }, labels.blanksOut) : null));
1951
+ ), /* @__PURE__ */ React5.createElement("select", { name: `${formName}-unit`, value: s.unit, onChange: (e) => change({ unit: e.target.value }), "aria-label": labels.ruleUnit, "data-testid": "rule-last-unit" }, RANGE_UNITS.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") && (compared?.blanks ?? (ctx.keepBlanks ? "include" : "exclude")) === "exclude" ? /* @__PURE__ */ React5.createElement("span", { className: "pk-hint pk-rule-note", "data-testid": "rule-blanks" }, labels.blanksOut) : null));
1777
1952
  }
1778
1953
  function TotalRule({ rule, ctx, apply, first }) {
1779
1954
  const { view, types, labels, locale } = ctx;
1780
1955
  const { choices, names } = measuresOf(view, types, labels, rule?.by);
1781
- const [s, setS] = useState3(() => ({ by: choiceIndex(choices, rule?.by), op: rule?.op ?? ">", a: numberText(rule?.value, locale), b: numberText(rule?.value2, locale) }));
1956
+ const [s, setS] = useState3(() => ({ by: choiceIndex(choices, rule?.by), op: rule ? ruleOp(rule) : ">", a: numberText(rule?.value, locale), b: numberText(rule?.value2, locale) }));
1782
1957
  const later = useLater();
1783
1958
  const formName = useFormName();
1784
1959
  const change = (patch, wait = false) => {
@@ -1788,7 +1963,7 @@ function TotalRule({ rule, ctx, apply, first }) {
1788
1963
  const [a, b] = [parseNumber(next.a, locale), parseNumber(next.b, locale)];
1789
1964
  if (a !== null && (!twin(next.op) || b !== null)) {
1790
1965
  const by = choices[next.by];
1791
- apply({ field: ctx.field, type: "value", by: { field: by.field, agg: by.agg }, op: next.op, value: a, ...twin(next.op) ? { value2: b } : {} });
1966
+ apply({ field: ctx.field, type: "value", by: { field: by.field, agg: by.agg }, ...opOf(next.op), value: a, ...twin(next.op) ? { value2: b } : {} });
1792
1967
  }
1793
1968
  };
1794
1969
  if (wait) {
@@ -1809,14 +1984,16 @@ function TotalRule({ rule, ctx, apply, first }) {
1809
1984
  };
1810
1985
  const keys = fieldKeys({ now: later.now, restore, back: ctx.back });
1811
1986
  const number = (key, label, testId, shown) => /* @__PURE__ */ React5.createElement(NumberField, { value: s[key], onChange: (t) => change({ [key]: t }, true), onKeyDown: keys, onBlur: later.now, problem: readNumber(s[key], { required: false, labels, locale }).problem, label, shown, testId, className: "pk-field-label pk-narrow-input" });
1812
- return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-subject pk-rule-lead" }, fill(labels.ruleWhose, { field: fieldLabel3(ctx.field, labels.core) })), /* @__PURE__ */ React5.createElement(MeasurePick, { choices, names, index: s.by, onChange: (i) => change({ by: i }), label: labels.valueFilterBy, testId: "value-filter-by" }), /* @__PURE__ */ React5.createElement("select", { className: "pk-rule-op", name: `${formName}-op`, value: s.op, onChange: (e) => change({ op: e.target.value }), "aria-label": labels.valueFilterOp, "data-autofocus": first ? "" : void 0, "data-testid": "value-filter-op" }, CATALOG4.valueOps.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, labels.valueOps[o] ?? o))), number("a", labels.valueFilterNumber, "value-filter-number"), twin(s.op) ? number("b", `${labels.valueFilterTo} ${labels.valueFilterNumber}`, "value-filter-number2", labels.valueFilterTo) : null);
1987
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-subject pk-rule-lead" }, fill(labels.ruleWhose, { field: fieldLabel3(ctx.field, labels.core) })), /* @__PURE__ */ React5.createElement(MeasurePick, { choices, names, index: s.by, onChange: (i) => change({ by: i }), label: labels.valueFilterBy, testId: "value-filter-by" }), /* @__PURE__ */ React5.createElement("select", { className: "pk-rule-op", name: `${formName}-op`, value: s.op, onChange: (e) => change({ op: e.target.value }), "aria-label": labels.valueFilterOp, "data-autofocus": first ? "" : void 0, "data-testid": "value-filter-op" }, RULE_OPS.compare.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, labels.valueOps[o] ?? o))), number("a", labels.valueFilterNumber, "value-filter-number"), twin(s.op) ? number("b", `${labels.valueFilterTo} ${labels.valueFilterNumber}`, "value-filter-number2", labels.valueFilterTo) : null);
1813
1988
  }
1814
- function NameRule({ rule, ctx, apply, first }) {
1989
+ function NameRule({ rule, ctx, apply, unset, first }) {
1815
1990
  const { field, labels } = ctx;
1816
- const [op, setOp] = useState3(rule?.op ?? "contains");
1991
+ const [op, setOp] = useState3(rule ? ruleOp(rule) : "contains");
1817
1992
  const send = (o, value) => {
1818
- if (value !== "") {
1819
- apply({ field, type: "label", op: o, value });
1993
+ if (value.trim() !== "") {
1994
+ apply({ ...textRule(field, { op: o, value, on: ctx.textOn }), ...rule ? { blanks: rule.blanks } : {} });
1995
+ } else if (rule) {
1996
+ unset();
1820
1997
  }
1821
1998
  };
1822
1999
  const text = useAppliedText(rule?.value ?? "", (value) => send(op, value));
@@ -1835,7 +2012,7 @@ function NameRule({ rule, ctx, apply, first }) {
1835
2012
  "data-autofocus": first ? "" : void 0,
1836
2013
  "data-testid": "filter-condition-op"
1837
2014
  },
1838
- CATALOG4.labelOps.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))
2015
+ RULE_OPS.text.map((o) => /* @__PURE__ */ React5.createElement("option", { key: o, value: o }, labels.labelOps[o] ?? o))
1839
2016
  ), /* @__PURE__ */ React5.createElement(
1840
2017
  ClearInput,
1841
2018
  {
@@ -1848,13 +2025,16 @@ function NameRule({ rule, ctx, apply, first }) {
1848
2025
  clearLabel: labels.clearText,
1849
2026
  "aria-label": labels.conditionValue,
1850
2027
  placeholder: labels.conditionValue,
1851
- maxLength: 1e3,
2028
+ maxLength: LIMITS2.textValue,
1852
2029
  "data-testid": "filter-condition-text"
1853
2030
  }
1854
2031
  ));
1855
2032
  }
1856
- var ROWS = { item: ItemRule, total: TotalRule, name: NameRule };
1857
- function RuleEditor({ ctx, rules, focusFirst, quickLine, results }) {
2033
+ function FixedRule({ rule, ctx }) {
2034
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-subject" }, ctx.say(rule)), /* @__PURE__ */ React5.createElement("span", { className: "pk-hint pk-rule-note", "data-testid": "rule-fixed" }, ctx.labels.ruleFixed));
2035
+ }
2036
+ var ROWS = { item: ItemRule, total: TotalRule, name: NameRule, fixed: FixedRule };
2037
+ function RuleEditor({ ctx, rules, focusFirst, quickLine, results, blanks }) {
1858
2038
  const { view, field, labels, locale, commit, note, fk, nameKind, noun } = ctx;
1859
2039
  const { explain } = useContext3(HelpContext);
1860
2040
  const lang = { lang: labels.lang, locale };
@@ -1862,6 +2042,11 @@ function RuleEditor({ ctx, rules, focusFirst, quickLine, results }) {
1862
2042
  /** @type {"item" | "total" | "name" | null} */
1863
2043
  null
1864
2044
  );
2045
+ const [held, setHeld] = useState3(
2046
+ /** @type {Array<{ at: number, kind: "item" | "total" | "name", blanks?: string }>} */
2047
+ []
2048
+ );
2049
+ const blanksName = useFormName();
1865
2050
  const [info, setInfo] = useState3(
1866
2051
  /** @type {number | null} */
1867
2052
  null
@@ -1878,6 +2063,7 @@ function RuleEditor({ ctx, rules, focusFirst, quickLine, results }) {
1878
2063
  if (rulesKey !== own) {
1879
2064
  setGen(gen + 1);
1880
2065
  setDraft(null);
2066
+ setHeld([]);
1881
2067
  }
1882
2068
  }
1883
2069
  const box = useRef2(
@@ -1912,8 +2098,8 @@ function RuleEditor({ ctx, rules, focusFirst, quickLine, results }) {
1912
2098
  /** @type {Array<"item" | "total" | "name">} */
1913
2099
  ["item", "total", "name"].filter((k) => k === "item" ? Boolean(fk.item) : k === "name" ? Boolean(nameKind) : true)
1914
2100
  );
1915
- const count = rules.length + (draft ? 1 : 0);
1916
- const full = count >= RULES_MAX || view.filters.length >= LIMITS.filters;
2101
+ const count = rules.length + (draft ? 1 : 0) + held.length;
2102
+ const full = count >= RULES_MAX || view.filters.length >= LIMITS2.filters;
1917
2103
  const addText = { item: fill(labels.addRuleItem, { field: fieldLabel3(field, labels.core) }), total: labels.addRuleTotal, name: labels.addRuleName };
1918
2104
  const infoText = (rule, kind) => {
1919
2105
  const one = plural(noun, 1, lang);
@@ -1926,31 +2112,59 @@ function RuleEditor({ ctx, rules, focusFirst, quickLine, results }) {
1926
2112
  }
1927
2113
  return fill(labels.ruleInfo[fk.item === "group" ? fk.cyclic ? "cyclic" : "group" : fk.item ?? "group"], { noun: one });
1928
2114
  };
1929
- const row = (rule, kind, i) => {
2115
+ const commitOwn = (next) => {
2116
+ setOwn(rulesKeyOf(filtersOf(next, field, RULE_TYPES).filter((f) => !ctx.quickFilters.includes(f))));
2117
+ commit(next, note);
2118
+ };
2119
+ const row = (rule, kind, i, isHeld = false) => {
1930
2120
  const Row = ROWS[kind];
1931
2121
  const apply = (entry) => {
1932
- const next = setRule(view, field, rule, entry);
1933
- setOwn(rulesKeyOf(filtersOf(next, field, RULE_TYPES).filter((f) => !ctx.quickFilters.includes(f))));
1934
- if (!rule) {
2122
+ const was = isHeld ? held.find((h) => h.at === i) : void 0;
2123
+ const own2 = was?.blanks && ITEM_RULE_TYPES.includes(entry.type) ? { ...entry, blanks: was.blanks } : !rule && ctx.keepBlanks && ITEM_RULE_TYPES.includes(entry.type) ? { ...entry, blanks: "include" } : entry;
2124
+ if (isHeld) {
2125
+ setHeld(held.filter((h) => h.at !== i));
2126
+ } else if (!rule) {
1935
2127
  setDraft(null);
1936
2128
  }
1937
- commit(next, note);
2129
+ const before = isHeld ? rows.slice(i + 1).find((x) => x.rule)?.rule ?? null : null;
2130
+ commitOwn(setRule(view, field, rule, own2, before));
2131
+ };
2132
+ const unset = () => {
2133
+ if (rule) {
2134
+ setHeld([...held, { at: i, kind, blanks: rule.blanks }].sort((a, b) => a.at - b.at));
2135
+ ctx.keepSections();
2136
+ commitOwn(setRule(view, field, rule, null));
2137
+ }
1938
2138
  };
1939
2139
  const remove = () => {
1940
2140
  focusAdd.current = true;
1941
2141
  if (rule) {
1942
2142
  commit(setRule(view, field, rule, null), note);
1943
2143
  } else {
1944
- setDraft(null);
2144
+ if (isHeld) {
2145
+ setHeld(held.filter((h) => h.at !== i));
2146
+ } else {
2147
+ setDraft(null);
2148
+ }
1945
2149
  setGen(gen + 1);
2150
+ if (rows.length === 1) {
2151
+ ctx.releaseSections();
2152
+ }
1946
2153
  }
1947
2154
  };
1948
2155
  const result = rule ? results.get(rule) : null;
1949
2156
  const open = info === i;
1950
2157
  const infoId = `${gen}-${i}`;
1951
- return /* @__PURE__ */ React5.createElement("li", { key: `${gen}:${i}`, className: "pk-rule", "data-testid": "rule", "data-kind": kind }, i > 0 || quickLine ? /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-and" }, labels.ruleAnd) : null, /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-body" }, /* @__PURE__ */ React5.createElement(Row, { rule, ctx, apply, first: focusFirst && i === 0 || !rule && draft !== null })), /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-tools" }, explain ? /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-icon-btn pk-rule-info", "aria-expanded": open, "aria-controls": open ? infoId : void 0, onClick: () => setInfo(open ? null : i), "aria-label": labels.explainRule, title: labels.explainRule, "data-testid": "rule-info" }, /* @__PURE__ */ React5.createElement(Icon, { name: "info", size: 14 })) : null, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-icon-btn pk-rule-remove", onClick: remove, "aria-label": labels.removeRule, title: labels.removeRule, "data-testid": "rule-remove" }, /* @__PURE__ */ React5.createElement(Icon, { name: "x", size: 14 }))), /* @__PURE__ */ React5.createElement("p", { className: `pk-hint pk-rule-result${result && result.kept === 0 ? " pk-rule-result-empty" : ""}`, "data-testid": "rule-result" }, result ? result.text : labels.ruleIncomplete), open ? /* @__PURE__ */ React5.createElement("p", { className: "pk-rule-info-text", id: infoId, "data-testid": "rule-info-text" }, infoText(rule, kind)) : null);
2158
+ 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, unset, first: focusFirst && i === 0 || !rule && !isHeld && draft !== null })), /* @__PURE__ */ React5.createElement("span", { className: "pk-rule-tools" }, explain ? /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-icon-btn pk-rule-info", "aria-expanded": open, "aria-controls": open ? infoId : void 0, onClick: () => setInfo(open ? null : i), "aria-label": labels.explainRule, title: labels.explainRule, "data-testid": "rule-info" }, /* @__PURE__ */ React5.createElement(Icon, { name: "info", size: 14 })) : null, /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-icon-btn pk-rule-remove", onClick: remove, "aria-label": labels.removeRule, title: labels.removeRule, "data-testid": "rule-remove" }, /* @__PURE__ */ React5.createElement(Icon, { name: "x", size: 14 }))), /* @__PURE__ */ React5.createElement("p", { className: `pk-hint pk-rule-result${result && result.kept === 0 ? " pk-rule-result-empty" : ""}`, "data-testid": "rule-result" }, result ? result.text : labels.ruleIncomplete), open ? /* @__PURE__ */ React5.createElement("p", { className: "pk-rule-info-text", id: infoId, "data-testid": "rule-info-text" }, infoText(rule, kind)) : null);
1952
2159
  };
1953
- return /* @__PURE__ */ React5.createElement("fieldset", { ref: box, className: "pk-condition pk-rules", "data-testid": "rules" }, /* @__PURE__ */ React5.createElement("legend", { className: "pk-sr" }, labels.rulesTitle), /* @__PURE__ */ React5.createElement("p", { className: "pk-hint" }, fill(count || quickLine ? labels.rulesKeep : labels.rulesNone, { noun: plural(noun, 2, lang) })), count || quickLine ? /* @__PURE__ */ React5.createElement("ul", { className: "pk-rule-list", role: "list" }, quickLine ? /* @__PURE__ */ React5.createElement("li", { className: "pk-rule pk-rule-quick", "data-testid": "rule-quick" }, /* @__PURE__ */ React5.createElement("span", null, fill(labels.quickLine, { text: quickLine })), /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-action", onClick: ctx.focusQuick, "data-testid": "rule-quick-change" }, labels.changeAbove)) : null, [...rules.map((r, i) => row(r, rowKind(r), i)), ...draft ? [row(null, draft, rules.length)] : []]) : null, /* @__PURE__ */ React5.createElement("div", { className: "pk-rule-adds", role: "group", "aria-label": labels.addRule }, kinds.map((k, i) => /* @__PURE__ */ React5.createElement(
2160
+ const rows = rules.map((r) => ({ rule: r, kind: rowKind(r), isHeld: false }));
2161
+ for (const h of held) {
2162
+ rows.splice(h.at, 0, { rule: null, kind: h.kind, isHeld: true });
2163
+ }
2164
+ if (draft) {
2165
+ rows.push({ rule: null, kind: draft, isHeld: false });
2166
+ }
2167
+ 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, rows.map((x, i) => row(x.rule, x.kind, i, x.isHeld))) : null, blanks ? /* @__PURE__ */ React5.createElement("label", { className: "pk-check pk-rules-blanks" }, /* @__PURE__ */ React5.createElement("input", { type: "checkbox", name: `${blanksName}`, checked: blanks.on, onChange: (e) => commit(setRuleBlanks(view, field, e.target.checked), note), "data-testid": "rules-blanks" }), /* @__PURE__ */ React5.createElement("span", null, fill(plural(labels.rulesBlanks, blanks.rows, lang), { rows: blanks.rows.toLocaleString(locale) }))) : null, /* @__PURE__ */ React5.createElement("div", { className: "pk-rule-adds", role: "group", "aria-label": labels.addRule }, kinds.map((k, i) => /* @__PURE__ */ React5.createElement(
1954
2168
  "button",
1955
2169
  {
1956
2170
  key: k,
@@ -1977,13 +2191,11 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
1977
2191
  const years = useMemo2(() => fk.cyclic && column && counts ? yearsOf(column, counts) : [], [fk.cyclic, column, counts]);
1978
2192
  const quick = quickChoice(view, field, fk, years.map((y) => y.year));
1979
2193
  const [anchorLocal, setAnchorLocal] = useState3(
1980
- /** @type {"today" | "latest" | null} */
2194
+ /** @type {string | null} */
1981
2195
  null
1982
2196
  );
1983
- const anchor = (
1984
- /** @type {"today" | "latest"} */
1985
- quick.anchor ?? anchorLocal ?? "today"
1986
- );
2197
+ const anchor = quick.anchor ?? anchorLocal ?? "today";
2198
+ const [moreOpen, setMoreOpen] = useState3(() => inMore(quick));
1987
2199
  const [openQuick, setOpenQuick] = useState3(true);
1988
2200
  const [openPicks, setOpenPicks] = useState3(
1989
2201
  /** @type {boolean | null} */
@@ -2034,7 +2246,7 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
2034
2246
  if (goQuick) {
2035
2247
  const target = (
2036
2248
  /** @type {HTMLElement | null | undefined} */
2037
- box.current?.querySelector('[data-testid="quick-choices"] input:checked, [data-testid="years-combined"] [aria-pressed="true"]:not(:disabled)') ?? box.current?.querySelector('[data-testid="years-combined"] button:not(:disabled)')
2249
+ box.current?.querySelector('[data-testid="quick-choices"] input:checked, [data-testid="quick-more-body"] input[type="radio"]:checked, [data-testid="years-combined"] [aria-pressed="true"]:not(:disabled)') ?? box.current?.querySelector('[data-testid="years-combined"] button:not(:disabled)')
2038
2250
  );
2039
2251
  target?.scrollIntoView?.({ block: "center" });
2040
2252
  target?.focus({ preventScroll: true });
@@ -2079,13 +2291,13 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
2079
2291
  const all = info.items.map((i) => i.value);
2080
2292
  const picked = selectedItems(view, field, all);
2081
2293
  const selected = new Set(picked.map(keyOf));
2082
- const nameKind = conditionKind(encoded, view, field) ?? (rules.some((r) => r.type === "label") ? "text" : null);
2294
+ const nameKind = conditionKind(encoded, view, field) ?? (rules.some((r) => r.type === "text") ? "text" : null);
2083
2295
  const labelOf = (v) => info.items.find((i) => i.value === v)?.label;
2084
2296
  const say = (f) => ruleText(view, f, { labels, locale, timeZone, date: fk.dates, labelOf, span });
2085
2297
  const number = (n) => n.toLocaleString(locale);
2086
2298
  const yearsOn = quick.id === "yearsCombined" && quick.years ? quick.years : years.map((y) => y.year);
2087
2299
  const yearsText = fk.cyclic && years.length > 1 ? yearsOn.length === 1 ? fill(labels.yearsOne, { year: String(yearsOn[0]) }) : fill(labels.yearsAll, { years: yearsOn.length === years.length || yearsOn[yearsOn.length - 1] - yearsOn[0] === yearsOn.length - 1 ? `${yearsOn[0]}\u2013${yearsOn[yearsOn.length - 1]}` : yearsOn.join(", ") }) : null;
2088
- const quickWords = quick.id === "yearsCombined" ? yearsText : quick.filters.length ? relativeText(quick.filters[0], labels, locale, timeZone, void 0, span) : null;
2300
+ const quickWords = quick.id === "yearsCombined" ? yearsText : quick.filters.length ? relativeText(quick.filters[0], labels, locale, timeZone, void 0, span, view.formatting?.weekStart) : null;
2089
2301
  const outByQuick = (
2090
2302
  /** @type {Set<string> | undefined} */
2091
2303
  itemResults.get("quick") ?? (quick.filters.length ? new Set(info.items.filter((i) => !i.kept).map((i) => keyOf(i.value))) : /* @__PURE__ */ new Set())
@@ -2109,7 +2321,7 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
2109
2321
  };
2110
2322
  const totalWords = (r) => {
2111
2323
  const measure = refLabel(view, r.by, labels);
2112
- const op = labels.valueOps[r.op] ?? r.op;
2324
+ const op = labels.valueOps[ruleOp(r)] ?? ruleOp(r);
2113
2325
  const num = (x) => typeof x === "number" ? x.toLocaleString(locale, { maximumFractionDigits: 6 }) : "";
2114
2326
  return twin(r.op) ? fill(labels.totalWordsTwo, { measure, op, from: num(Math.min(r.value, r.value2)), to: num(Math.max(r.value, r.value2)) }) : fill(labels.totalWords, { measure, op, number: num(r.value) });
2115
2327
  };
@@ -2146,6 +2358,9 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
2146
2358
  const scope = scopeParts.length ? scopeParts.join(labels.listAnd) : labels.scopeRows;
2147
2359
  const focusQuick = () => {
2148
2360
  setOpenQuick(true);
2361
+ if (inMore(quick)) {
2362
+ setMoreOpen(true);
2363
+ }
2149
2364
  setGoQuick((n) => n + 1);
2150
2365
  };
2151
2366
  const act = (next, header) => {
@@ -2157,7 +2372,22 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
2157
2372
  }
2158
2373
  });
2159
2374
  };
2160
- const ctx = { view, field, types, labels, locale, commit, note, back, fk, nameKind, timeZone, hint, items: info.items, noun, scope, quickFilters: quick.filters, focusQuick, act };
2375
+ const keepBlanks = keepsBlanks(view, field);
2376
+ const keepSections = () => {
2377
+ if (rules.length === 1 && !quick.filters.length) {
2378
+ byHand.current = true;
2379
+ setOpenPicks(openPicks ?? !anyRule);
2380
+ setOpenRules(openRules ?? anyRule);
2381
+ }
2382
+ };
2383
+ const releaseSections = () => {
2384
+ setOpenPicks(null);
2385
+ setOpenRules(null);
2386
+ lost.current = true;
2387
+ };
2388
+ const ctx = { view, field, types, labels, locale, commit, note, back, fk, nameKind, say, textOn: textOn(encoded, field), timeZone, hint, items: info.items, noun, scope, quickFilters: quick.filters, focusQuick, act, keepBlanks, keepSections, releaseSections };
2389
+ const blankRows = info.items.find((i) => i.value === null)?.count ?? 0;
2390
+ const blanks = blankRows > 0 && (itemRules.length > 0 || quick.filters.length > 0) ? { rows: blankRows, on: keepBlanks } : null;
2161
2391
  const picksOpen = openPicks ?? !anyRule;
2162
2392
  const rulesOpen = openRules ?? anyRule;
2163
2393
  const togglePicks = () => {
@@ -2176,7 +2406,7 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
2176
2406
  };
2177
2407
  const summary = { shown, total: all.length, noun, unpicked, byQuick, byRules, byTotals, itemRules: itemRules.length, totalRules: totalRules.length, rows: totals.rows, rowsAll: encoded.length, span, yearsText, empty, quickWords, rules: rules.length, canReset: unpicked > 0 || anyRule };
2178
2408
  const outOf = (i) => i.kept === false;
2179
- const quickSection = fk.quick && span && column && counts ? { id: "quick", title: labels.quickTitle, body: /* @__PURE__ */ React5.createElement(QuickChoices, { ctx, quick, anchor, setAnchorLocal, span, column, counts }) } : fk.cyclic && years.length > 1 && years.length <= 12 ? { id: "years", title: labels.yearsCombined, body: /* @__PURE__ */ React5.createElement(YearsCombined, { ctx, years, on: yearsOn }) } : null;
2409
+ const quickSection = fk.quick && span && column && counts ? { id: "quick", title: labels.quickTitle, body: /* @__PURE__ */ React5.createElement(QuickChoices, { ctx, quick, anchor, setAnchorLocal, span, column, counts, moreOpen, setMoreOpen }) } : fk.cyclic && years.length > 1 && years.length <= 12 ? { id: "years", title: labels.yearsCombined, body: /* @__PURE__ */ React5.createElement(YearsCombined, { ctx, years, on: yearsOn }) } : null;
2180
2410
  return /* @__PURE__ */ React5.createElement("div", { ref: box, className: "pk-filter pk-filter-level" }, /* @__PURE__ */ React5.createElement(Summary, { ctx, state: summary }), quickSection ? /* @__PURE__ */ React5.createElement(Section2, { id: quickSection.id, title: quickSection.title, state: quickWords && !openQuick ? quickWords : null, open: openQuick, onToggle: () => setOpenQuick(!openQuick) }, quickSection.body) : null, /* @__PURE__ */ React5.createElement(
2181
2411
  Section2,
2182
2412
  {
@@ -2209,13 +2439,15 @@ function FilterLevel({ view, field, encoded, types, labels, locale, commit, back
2209
2439
  onToggle: toggleRules,
2210
2440
  action: /* @__PURE__ */ React5.createElement("button", { type: "button", className: "pk-action", disabled: !rules.length, "aria-label": labels.removeRules, onClick: () => act(removeRules(view, field, quick.filters), "section-rules"), "data-testid": "filter-remove-rules" }, labels.removeAll)
2211
2441
  },
2212
- /* @__PURE__ */ React5.createElement(RuleEditor, { ctx, rules, focusFirst: hint === "conditions", quickLine: quickWords, results })
2442
+ /* @__PURE__ */ React5.createElement(RuleEditor, { ctx, rules, focusFirst: hint === "conditions", quickLine: quickWords, results, blanks })
2213
2443
  ));
2214
2444
  }
2215
2445
 
2216
2446
  // src/chip-menus.jsx
2217
- function TopLevel({ view, field, types, labels, locale, commit, back }) {
2447
+ function TopLevel({ view, field, types, labels, locale, commit, back, encoded }) {
2218
2448
  const top = filtersOf(view, field, ["top"])[0];
2449
+ const axis = view.rows[0]?.toLowerCase() === field.toLowerCase() ? "rowRoot" : view.cols[0]?.toLowerCase() === field.toLowerCase() ? "colRoot" : null;
2450
+ const shown = useMemo3(() => top && axis && encoded ? computePivot2(encoded, view)[axis].children.length : null, [top, axis, encoded, view]);
2219
2451
  const { choices, names } = measuresOf(view, types, labels, top?.by);
2220
2452
  const [by, setBy] = useState4(() => choiceIndex(choices, top?.by));
2221
2453
  const quick = top && !top.bottom && TOP_COUNTS.includes(top.count) ? top.count : null;
@@ -2234,7 +2466,8 @@ function TopLevel({ view, field, types, labels, locale, commit, back }) {
2234
2466
  }
2235
2467
  };
2236
2468
  const groupName = useFormName();
2237
- const radio = (id, text, checked, onPick) => /* @__PURE__ */ React6.createElement("label", { className: "pk-radio" }, /* @__PURE__ */ React6.createElement("input", { type: "radio", name: groupName, checked, onChange: onPick, "data-autofocus": checked ? "" : void 0, "data-testid": `top-${id}` }), /* @__PURE__ */ React6.createElement("span", null, text));
2469
+ const tiesName = useFormName();
2470
+ const radio = (id, text, checked, onPick) => /* @__PURE__ */ React6.createElement("label", { className: "pk-radio" }, /* @__PURE__ */ React6.createElement("input", { type: "radio", name: groupName, checked, onClick: (e) => e.currentTarget.focus(), onChange: onPick, "data-autofocus": checked ? "" : void 0, "data-testid": `top-${id}` }), /* @__PURE__ */ React6.createElement("span", null, text));
2238
2471
  return /* @__PURE__ */ React6.createElement("div", { className: "pk-level-form" }, /* @__PURE__ */ React6.createElement("div", { role: "radiogroup", "aria-label": labels.topN, className: "pk-radios" }, radio("off", labels.off, !top && !own, () => {
2239
2472
  setOwn(false);
2240
2473
  set(null);
@@ -2289,7 +2522,16 @@ function TopLevel({ view, field, types, labels, locale, commit, back }) {
2289
2522
  if (top) {
2290
2523
  set({ count: top.count, bottom: Boolean(top.bottom), by: choices[i] });
2291
2524
  }
2292
- }, label: labels.topBy, prefix: labels.topBy, testId: "top-by" })));
2525
+ }, label: labels.topBy, prefix: labels.topBy, testId: "top-by" })), top ? /* @__PURE__ */ React6.createElement("label", { className: "pk-check" }, /* @__PURE__ */ React6.createElement(
2526
+ "input",
2527
+ {
2528
+ type: "checkbox",
2529
+ name: tiesName,
2530
+ checked: top.ties === "all",
2531
+ onChange: (e) => set({ count: top.count, bottom: Boolean(top.bottom), by: top.by ?? choices[by], ties: e.target.checked ? "all" : "first" }),
2532
+ "data-testid": "top-ties"
2533
+ }
2534
+ ), /* @__PURE__ */ React6.createElement("span", null, labels.topTies)) : null, top && (shown !== null || top.ties === "all") ? /* @__PURE__ */ React6.createElement("p", { className: "pk-hint pk-top-shown", "data-testid": "top-shown" }, shown !== null ? fill(plural(labels.topShown, shown, { lang: labels.lang, locale }), { count: shown.toLocaleString(locale) }) : fill(labels.topTiesGroups, { count: top.count.toLocaleString(locale) })) : null);
2293
2535
  }
2294
2536
  function BinsLevel({ view, field, labels, locale, range, regroup, back }) {
2295
2537
  const grouping = groupingOf(view, field);
@@ -2404,7 +2646,7 @@ function AxisMenu({ view, zone, index, field, types, labels, commit, close, onRe
2404
2646
  const grouped = unit ? groupingName(sourceName, unit, labels, size) : null;
2405
2647
  commit(groupField(view, field, unit, { size, origin, name: grouped ?? void 0 }).view, { step: "group", field: sourceName });
2406
2648
  };
2407
- const panel = (id, back, hint) => id === "filter" ? /* @__PURE__ */ React6.createElement(FilterLevel, { view, field, encoded, types, labels, locale, commit, back, hint }) : id === "top" ? /* @__PURE__ */ React6.createElement(TopLevel, { view, field, types, labels, locale, commit, back }) : id === "bins" ? /* @__PURE__ */ React6.createElement(BinsLevel, { view, field, labels, locale, range: rangeOf?.(source) ?? null, regroup, back }) : null;
2649
+ 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, encoded }) : id === "bins" ? /* @__PURE__ */ React6.createElement(BinsLevel, { view, field, labels, locale, range: rangeOf?.(source) ?? null, regroup, back }) : null;
2408
2650
  const name = fieldLabel4(field, labels.core);
2409
2651
  return /* @__PURE__ */ React6.createElement(
2410
2652
  LevelMenu,
@@ -2547,13 +2789,14 @@ async function copyText(text, container) {
2547
2789
  }
2548
2790
 
2549
2791
  // src/version.js
2550
- var VERSION = true ? "0.4.0" : "0.0.0-source";
2792
+ var VERSION = true ? "0.6.0" : "0.0.0-source";
2551
2793
 
2552
2794
  // src/share-actions.js
2553
2795
  var here = () => typeof location !== "undefined" ? location.href : void 0;
2554
2796
  function shareActions(ctx, labels) {
2555
- const { view, viewName, sourceId, sourceName, schemaUrl, encoded, announce, limits, param } = ctx;
2556
- const viewFile = () => viewFileText(toViewFile(view, { name: viewName ?? "", createdAt: /* @__PURE__ */ new Date(), generator: { name: "pivotkit-react", version: VERSION }, source: { id: sourceId, name: sourceName }, data: encoded, ...schemaUrl !== void 0 ? { schemaUrl } : {} }));
2797
+ const { view, viewName, sourceId, sourceName, sourceParams, schemaUrl, encoded, announce, limits, linkKey } = ctx;
2798
+ const params = sourceParams ? { params: sourceParams } : {};
2799
+ const viewFile = () => viewFileText(toViewFile(view, { name: viewName ?? "", createdAt: /* @__PURE__ */ new Date(), generator: { name: "pivotkit-react", version: VERSION }, source: { id: sourceId, name: sourceName, ...params }, data: encoded, ...schemaUrl !== void 0 ? { schemaUrl } : {} }));
2557
2800
  return {
2558
2801
  copyLink: async () => {
2559
2802
  const target = shareBase(ctx.shareLink, here());
@@ -2562,13 +2805,13 @@ function shareActions(ctx, labels) {
2562
2805
  }
2563
2806
  let text;
2564
2807
  try {
2565
- text = (linkNow() ?? await loadLink()).encodeViewLink(toViewFile(view, { name: viewName ?? void 0, source: { id: sourceId } }, { link: true }));
2808
+ text = (linkNow() ?? await loadLink()).encodeViewLink(toViewFile(view, { name: viewName ?? void 0, source: { id: sourceId, ...params } }, { link: true }));
2566
2809
  } catch (e) {
2567
2810
  announce(e && /** @type {any} */
2568
2811
  e.code === "LIMIT_EXCEEDED" ? labels.toastLinkTooLong : fill(labels.error, { message: String(e) }), { tone: "error" });
2569
2812
  return;
2570
2813
  }
2571
- const ok = await copyText(withLinkParam(target, param, text), ctx.root.current);
2814
+ const ok = await copyText(withLinkParam(target, linkKey, text), ctx.root.current);
2572
2815
  announce(ok ? labels.toastLinkCopied : labels.toastCopyFailed, ok ? void 0 : { tone: "error" });
2573
2816
  },
2574
2817
  copyJson: async () => {
@@ -2593,7 +2836,7 @@ function shareActions(ctx, labels) {
2593
2836
  let loaded = viewFromText(text, encoded, { limits, sourceId });
2594
2837
  if (loaded.failed === "notJson") {
2595
2838
  const t = text.trim();
2596
- const fromUrl = t.includes("#") ? readLinkParam(t.slice(t.indexOf("#")), param) ?? readLinkParam(t.slice(t.indexOf("#")), "pivot") : null;
2839
+ const fromUrl = t.includes("#") ? readLinkParam(t.slice(t.indexOf("#")), linkKey) ?? readLinkParam(t.slice(t.indexOf("#")), void 0) : null;
2597
2840
  const payload = fromUrl ?? (t.startsWith("1.") ? t : null);
2598
2841
  if (!payload) {
2599
2842
  return labels.viewFailed.notJson;
@@ -2612,6 +2855,10 @@ function shareActions(ctx, labels) {
2612
2855
  /** @type {import("./share.js").LoadedView} */
2613
2856
  loaded
2614
2857
  );
2858
+ const made = ready.file?.source;
2859
+ if (made && ready.file?.view && ctx.viaSheet?.({ id: made.id, sheet: sheetOfSource(made) }, ready.file.name || viewName || "", toViewFile(ready.file.view, { name: ready.file.name, source: made })) === "switch") {
2860
+ return null;
2861
+ }
2615
2862
  const check = loadCheck(ready, labels, Array.isArray(ctx.sources) ? ctx.sources : []);
2616
2863
  if (!check) {
2617
2864
  ctx.applyLoaded(ready);
@@ -2633,8 +2880,11 @@ function shareActions(ctx, labels) {
2633
2880
 
2634
2881
  // src/view-save.js
2635
2882
  var canSaveAs = (can) => can.host || can.store;
2636
- var isLoadedEntry = (t, loaded) => !!loaded && t.name === loaded.name && (t.scope === "user" ? "user" : "shared") === loaded.scope && t.at !== void 0 === loaded.store && (!loaded.store || (t.sourceId ?? null) === (loaded.storeSource ?? null));
2637
- var storeEntry = (entries, name, source) => entries.find((t) => t.at !== void 0 && t.name === name && (t.sourceId ?? null) === (source ?? null));
2883
+ var isLoadedEntry = (t, loaded) => !!loaded && t.name === loaded.name && (t.scope === "user" ? "user" : "shared") === loaded.scope && t.at !== void 0 === loaded.store && (!loaded.store || (t.sourceId ?? null) === (loaded.storeSource ?? null) && (t.sheet ?? null) === (loaded.storeSheet ?? null));
2884
+ var storeEntry = (entries, name, source, sheet) => {
2885
+ const of = (s) => entries.find((t) => t.at !== void 0 && t.name === name && (t.sourceId ?? null) === (source ?? null) && (t.sheet ?? null) === s);
2886
+ return of(source ? sheet ?? null : null) ?? (source && sheet ? of(null) : void 0);
2887
+ };
2638
2888
  function saveTarget(loaded, entries, can, empty = false) {
2639
2889
  if (!loaded) {
2640
2890
  return null;
@@ -2643,8 +2893,8 @@ function saveTarget(loaded, entries, can, empty = false) {
2643
2893
  if (loaded.scope === "shared") {
2644
2894
  target = can.publish ? { kind: "publish" } : canSaveAs(can) ? { kind: null, why: "saveSharedLocked" } : null;
2645
2895
  } else if (loaded.scope === "user" && loaded.store) {
2646
- const entry = storeEntry(entries, loaded.name, loaded.storeSource);
2647
- target = can.store ? entry ? { kind: "store", at: entry.at, storeSource: loaded.storeSource ?? null } : { kind: "store", storeSource: can.sourceId ?? null } : null;
2896
+ const entry = storeEntry(entries, loaded.name, loaded.storeSource, loaded.storeSheet);
2897
+ target = can.store ? entry ? { kind: "store", at: entry.at, storeSource: loaded.storeSource ?? null, storeSheet: loaded.storeSheet ?? null } : { kind: "store", storeSource: can.sourceId ?? null, storeSheet: can.sheet ?? null } : null;
2648
2898
  } else if (loaded.scope === "user") {
2649
2899
  target = can.host ? { kind: "host" } : null;
2650
2900
  } else {
@@ -2658,9 +2908,9 @@ function saveAsTarget(name, entries, can) {
2658
2908
  }
2659
2909
  const old = (
2660
2910
  /** @type {T | undefined} */
2661
- storeEntry(entries, name, can.sourceId) ?? storeEntry(entries, name, null)
2911
+ storeEntry(entries, name, can.sourceId, can.sheet) ?? storeEntry(entries, name, null, null)
2662
2912
  );
2663
- return old ? { kind: "store", at: old.at, storeSource: old.sourceId ?? null, replaces: old } : { kind: "store", storeSource: can.sourceId ?? null, replaces: null };
2913
+ return old ? { kind: "store", at: old.at, storeSource: old.sourceId ?? null, storeSheet: old.sheet ?? null, replaces: old } : { kind: "store", storeSource: can.sourceId ?? null, storeSheet: can.sheet ?? null, replaces: null };
2664
2914
  }
2665
2915
 
2666
2916
  // src/view-store.js
@@ -2681,9 +2931,13 @@ function readAll(raw) {
2681
2931
  }
2682
2932
  return parseTemplates(raw).templates;
2683
2933
  }
2684
- function storedViews(raw, sourceId) {
2685
- return readAll(raw).map((t, at) => ({ name: t.name, view: t.view, at, ...t.source?.id ? { sourceId: t.source.id } : {} })).filter((t) => !t.sourceId || !sourceId || t.sourceId === sourceId);
2934
+ function storedViews(raw, sourceId, shown = { sheet: null, sheets: [] }) {
2935
+ return readAll(raw).map((t, at) => {
2936
+ const sheet = sheetOfSource(t.source);
2937
+ return { name: t.name, view: t.view, at, ...t.source?.id ? { sourceId: t.source.id } : {}, ...sheet ? { sheet } : {} };
2938
+ }).filter((t) => listedFor(t, { id: sourceId, ...shown }));
2686
2939
  }
2940
+ var sourceOf2 = (id, sheet) => id ? { id, ...sheet ? { params: { sheet } } : {} } : void 0;
2687
2941
  function changedViews(raw, change, message) {
2688
2942
  const all = readAll(raw);
2689
2943
  let next = all;
@@ -2699,20 +2953,23 @@ function changedViews(raw, change, message) {
2699
2953
  if (old?.name !== change.name) {
2700
2954
  throw new Error(message("changed", 0));
2701
2955
  }
2956
+ const source = old.source?.id && old.source.id === change.sourceId ? sourceOf2(change.sourceId, change.sheet) : old.source;
2702
2957
  next = all.map((t, i) => i === change.replace ? { name: old.name, view: (
2703
2958
  /** @type {Record<string, unknown>} */
2704
2959
  change.view
2705
- ), ...old.source ? { source: old.source } : {} } : t);
2960
+ ), ...source ? { source } : {} } : t);
2706
2961
  } else if (saving) {
2707
2962
  const id = change.sourceId;
2708
- next = next.filter((t) => t.name !== change.name || (t.source?.id ?? void 0) !== id);
2963
+ const sheet = id ? change.sheet ?? null : null;
2964
+ next = next.filter((t) => t.name !== change.name || (t.source?.id ?? void 0) !== id || sheetOfSource(t.source) !== sheet);
2965
+ const source = sourceOf2(id, sheet);
2709
2966
  next.push({ name: (
2710
2967
  /** @type {string} */
2711
2968
  change.name
2712
2969
  ), view: (
2713
2970
  /** @type {Record<string, unknown>} */
2714
2971
  change.view
2715
- ), ...id ? { source: { id } } : {} });
2972
+ ), ...source ? { source } : {} });
2716
2973
  if (next.length > VIEW_STORE_LIMITS.count) {
2717
2974
  throw new Error(message("count", VIEW_STORE_LIMITS.count));
2718
2975
  }
@@ -3047,23 +3304,33 @@ function viewActions(ctx, labels) {
3047
3304
  const save = (target, name) => {
3048
3305
  const key = ctx.viewKey;
3049
3306
  return run(
3050
- () => target.kind === "publish" ? ctx.onPublish(name, ctx.view) : target.kind === "host" ? ctx.onSave(name, ctx.view, { scope: "user" }) : write({ name, view: ctx.view, sourceId: ctx.sourceId, replace: target.at }),
3307
+ () => target.kind === "publish" ? ctx.onPublish(name, ctx.view, { source: ctx.source }) : target.kind === "host" ? ctx.onSave(name, ctx.view, { scope: "user", source: ctx.source }) : write({ name, view: ctx.view, sourceId: ctx.sourceId, sheet: ctx.sheet, replace: target.at }),
3051
3308
  labels.toastSaved,
3052
3309
  labels.toastSaveFailed,
3053
3310
  labels.toastSaveRejected,
3054
3311
  name
3055
- ).then((ok) => ok && ctx.onSaved({ name, scope: target.kind === "publish" ? "shared" : "user", store: target.kind === "store", storeSource: target.kind === "store" ? target.storeSource : null }, key));
3312
+ ).then((ok) => ok && ctx.onSaved({ name, scope: target.kind === "publish" ? "shared" : "user", store: target.kind === "store", storeSource: target.kind === "store" ? target.storeSource : null, storeSheet: target.kind === "store" ? storedSheet(target, ctx) : null }, key));
3056
3313
  };
3057
3314
  return {
3058
3315
  // Save and Save as: where to is view-save.js's (the host's onSaveTemplate wins over the store)
3059
3316
  save,
3060
3317
  remove: ctx.onDelete || ctx.store ? (t) => run(() => t.at !== void 0 ? write({ remove: t.at, removeName: t.name }) : ctx.onDelete(t.name, { scope: t.scope }), labels.toastDeleted, labels.toastDeleteFailed, labels.toastDeleteRejected, t.name) : null,
3061
- publish: ctx.onPublish ? (t) => run(() => ctx.onPublish(t.name, ctx.normalized(t.view)), labels.toastPublished, labels.toastPublishFailed, labels.toastPublishRejected, t.name) : null
3318
+ // a view of the menu is published with the data it was made for, which is the data shown unless
3319
+ // the entry names other data (a view of the browser store kept for another file or sheet)
3320
+ publish: ctx.onPublish ? (t) => run(() => ctx.onPublish(t.name, ctx.normalized(t.view), { source: entrySource(t, ctx.source) }), labels.toastPublished, labels.toastPublishFailed, labels.toastPublishRejected, t.name) : null
3062
3321
  };
3063
3322
  }
3323
+ var entrySource = (t, shown) => {
3324
+ const id = t.sourceId ?? t.sheetOf ?? t.fileSource;
3325
+ if (!id) {
3326
+ return shown ?? null;
3327
+ }
3328
+ return { id, ...shown?.id === id && shown.name ? { name: shown.name } : {}, ...t.sheet ? { params: { sheet: t.sheet } } : {} };
3329
+ };
3330
+ var storedSheet = (target, ctx) => target.storeSource && target.storeSource === ctx.sourceId ? ctx.sheet ?? null : target.storeSheet ?? null;
3064
3331
  function ViewsPanel({ templates, labels, onLoad, actions, close, share }) {
3065
3332
  const { save, remove: onDelete, publish: onPublish } = viewActions(actions, labels);
3066
- const can = { host: Boolean(actions.onSave), store: Boolean(actions.store), publish: Boolean(onPublish), sourceId: actions.sourceId };
3333
+ const can = { host: Boolean(actions.onSave), store: Boolean(actions.store), publish: Boolean(onPublish), sourceId: actions.sourceId, sheet: actions.sheet ?? null };
3067
3334
  const target = saveTarget(actions.loaded, templates, can, actions.empty);
3068
3335
  const store = actions.store && !actions.onSave;
3069
3336
  const [asking, setAsking] = useState5(
@@ -3086,6 +3353,9 @@ function ViewsPanel({ templates, labels, onLoad, actions, close, share }) {
3086
3353
  id,
3087
3354
  testId: `saved-view-${t.name}`,
3088
3355
  text: t.name,
3356
+ // while a workbook's sheet is shown, a view made on a sheet says which (two views of a
3357
+ // name can be kept, one per sheet; one of another sheet reads that sheet when opened)
3358
+ hint: t.sheet && actions.sheet ? fill(labels.viewSheet, { sheet: t.sheet }) : void 0,
3089
3359
  icon: "bookmark",
3090
3360
  current: isLoadedEntry(t, actions.loaded),
3091
3361
  closes: true,
@@ -3216,7 +3486,7 @@ function ExportOption({ icon, text, info, onSelect, testId, disabled, reason })
3216
3486
  info
3217
3487
  ), name: text })) : option;
3218
3488
  }
3219
- function ExportPanel({ labels, onExport, chartReady, display, empty = false, prepare, close }) {
3489
+ function ExportPanel({ labels, onExport, chartReady, display, empty = false, dataExport = false, prepare, close }) {
3220
3490
  useEffect3(() => {
3221
3491
  prepare();
3222
3492
  }, [prepare]);
@@ -3225,14 +3495,140 @@ function ExportPanel({ labels, onExport, chartReady, display, empty = false, pre
3225
3495
  onExport(kind);
3226
3496
  };
3227
3497
  const off = empty ? { disabled: true, reason: labels.exportNeedsField } : {};
3228
- return /* @__PURE__ */ React7.createElement(React7.Fragment, null, /* @__PURE__ */ React7.createElement(Section, { title: labels.exportDownload }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportXlsx, info: "exportXlsx", onSelect: run("xlsx"), ...off, testId: "export-xlsx" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportCsv, info: "exportCsv", onSelect: run("csv"), ...off, testId: "export-csv" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "image", text: labels.exportPng, disabled: empty || !chartReady, reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("png"), testId: "export-png" })), /* @__PURE__ */ React7.createElement(Section, { title: labels.exportCopy }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "copy", text: labels.copyTable, info: "copyTable", onSelect: run("copy-table"), ...off, testId: "export-copy-table" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "copy", text: labels.copyDataJson, info: "copyDataJson", onSelect: run("copy-json"), ...off, testId: "export-copy-json" })));
3498
+ return /* @__PURE__ */ React7.createElement(React7.Fragment, null, /* @__PURE__ */ React7.createElement(Section, { title: labels.exportDownload }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportXlsx, info: "exportXlsx", onSelect: run("xlsx"), ...off, testId: "export-xlsx" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportCsv, info: "exportCsv", onSelect: run("csv"), ...off, testId: "export-csv" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportHtml, info: "exportHtml", onSelect: run("html"), ...off, testId: "export-html" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "image", text: labels.exportPng, disabled: empty || !chartReady, reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("png"), testId: "export-png" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "image", text: labels.exportSvg, disabled: empty || display !== "chart", reason: empty ? off.reason : display !== "chart" ? labels.exportPngNeedsChart : void 0, onSelect: run("svg"), testId: "export-svg" })), /* @__PURE__ */ React7.createElement(Section, { title: labels.exportPrintGroup }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "print", text: labels.exportPrint, info: "exportPrint", onSelect: run("print"), ...off, testId: "export-print" })), /* @__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" })), dataExport ? /* @__PURE__ */ React7.createElement(Section, { title: labels.exportDataGroup }, /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportDataCsv, info: "exportDataCsv", onSelect: run("data-csv"), testId: "export-data-csv" }), /* @__PURE__ */ React7.createElement(ExportOption, { icon: "file", text: labels.exportDataJson, info: "exportDataJson", onSelect: run("data-json"), testId: "export-data-json" })) : null);
3229
3499
  }
3230
3500
 
3231
3501
  // src/drill-panel.jsx
3232
- import React8, { useContext as useContext4, useEffect as useEffect4, useId as useId6, useMemo as useMemo3, useRef as useRef4, useState as useState6 } from "react";
3502
+ import React8, { useContext as useContext4, useEffect as useEffect4, useId as useId6, useMemo as useMemo4, useRef as useRef4, useState as useState6 } from "react";
3503
+
3504
+ // src/export-run.js
3505
+ import { chartThemeFrom, toGrid } from "pivotkit-core";
3506
+
3507
+ // src/print-frame.js
3508
+ var FRAME_CLASS = "pk-print-frame";
3509
+ var listeners = /* @__PURE__ */ new WeakMap();
3510
+ function removeFrame(frame) {
3511
+ listeners.get(frame)?.abort();
3512
+ frame.remove();
3513
+ }
3514
+ var PRINT_LOAD_TIMEOUT = 5e3;
3515
+ function printParts(html, parser) {
3516
+ const styles = [];
3517
+ const text = html.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => (styles.push(css), ""));
3518
+ const parsed = parser.parseFromString(text, "text/html");
3519
+ for (const node of parsed.querySelectorAll("style, script, meta, link, base")) {
3520
+ node.remove();
3521
+ }
3522
+ return { css: styles.join("\n"), lang: parsed.documentElement.getAttribute("lang") ?? "", dir: parsed.documentElement.getAttribute("dir") ?? "", title: parsed.title, body: parsed.body };
3523
+ }
3524
+ async function printHtml(html, container) {
3525
+ const doc = container.ownerDocument;
3526
+ const view = doc.defaultView;
3527
+ if (!view) {
3528
+ return false;
3529
+ }
3530
+ for (const old of container.querySelectorAll(`iframe.${FRAME_CLASS}`)) {
3531
+ removeFrame(
3532
+ /** @type {HTMLIFrameElement} */
3533
+ old
3534
+ );
3535
+ }
3536
+ const parts = printParts(html, new view.DOMParser());
3537
+ const frame = doc.createElement("iframe");
3538
+ frame.className = FRAME_CLASS;
3539
+ frame.setAttribute("sandbox", "allow-same-origin allow-modals");
3540
+ frame.setAttribute("aria-hidden", "true");
3541
+ frame.setAttribute("tabindex", "-1");
3542
+ frame.title = parts.title;
3543
+ frame.hidden = true;
3544
+ const loaded = new Promise((resolve) => {
3545
+ const timer = setTimeout(() => resolve(false), PRINT_LOAD_TIMEOUT);
3546
+ const done = () => {
3547
+ if (frame.contentDocument?.URL === "about:srcdoc" && frame.contentDocument.readyState === "complete") {
3548
+ clearTimeout(timer);
3549
+ frame.removeEventListener("load", done);
3550
+ resolve(true);
3551
+ }
3552
+ };
3553
+ frame.addEventListener("load", done);
3554
+ });
3555
+ frame.srcdoc = '<!doctype html><html><head><meta charset="utf-8"><title></title></head><body></body></html>';
3556
+ container.append(frame);
3557
+ const win = await loaded ? frame.contentWindow : null;
3558
+ const fdoc = frame.contentDocument;
3559
+ if (!win || !fdoc || !fdoc.body) {
3560
+ frame.remove();
3561
+ return false;
3562
+ }
3563
+ fdoc.documentElement.lang = parts.lang;
3564
+ fdoc.documentElement.dir = parts.dir;
3565
+ fdoc.title = parts.title;
3566
+ const FrameSheet = (
3567
+ /** @type {any} */
3568
+ win.CSSStyleSheet
3569
+ );
3570
+ if (typeof FrameSheet === "function" && "adoptedStyleSheets" in fdoc) {
3571
+ const sheet = new FrameSheet();
3572
+ sheet.replaceSync(parts.css);
3573
+ fdoc.adoptedStyleSheets = [sheet];
3574
+ } else {
3575
+ const style = fdoc.createElement("style");
3576
+ style.textContent = parts.css;
3577
+ fdoc.head.append(style);
3578
+ }
3579
+ fdoc.body.replaceChildren(...[...parts.body.childNodes].map((node) => fdoc.importNode(node, true)));
3580
+ frame.hidden = false;
3581
+ await new Promise((resolve) => view.requestAnimationFrame(() => setTimeout(resolve, 0)));
3582
+ if (!frame.isConnected) {
3583
+ return true;
3584
+ }
3585
+ const ended = new AbortController();
3586
+ listeners.set(frame, ended);
3587
+ const after = () => setTimeout(() => removeFrame(frame), 0);
3588
+ win.addEventListener("afterprint", after, { once: true, signal: ended.signal });
3589
+ view.addEventListener("afterprint", after, { once: true, signal: ended.signal });
3590
+ win.print();
3591
+ return true;
3592
+ }
3593
+
3594
+ // src/light-tokens.js
3595
+ function lightTokens(root, names, more = () => ({})) {
3596
+ const host = (
3597
+ /** @type {{ host?: Element }} */
3598
+ root.getRootNode().host
3599
+ );
3600
+ const dark = [root, ...host ? [host] : []].filter((el) => el.getAttribute("data-pk-theme") === "dark");
3601
+ const read = () => {
3602
+ const style = getComputedStyle(root);
3603
+ return { ...Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name).trim()]).filter(([, value]) => value)), ...more() };
3604
+ };
3605
+ if (!dark.length) {
3606
+ return read();
3607
+ }
3608
+ const kept = [root.style.getPropertyValue("--pk-duration"), root.style.getPropertyPriority("--pk-duration")];
3609
+ root.style.setProperty("--pk-duration", "0ms", "important");
3610
+ try {
3611
+ for (const el of dark) {
3612
+ el.setAttribute("data-pk-theme", "light");
3613
+ }
3614
+ try {
3615
+ return read();
3616
+ } finally {
3617
+ for (const el of dark) {
3618
+ el.setAttribute("data-pk-theme", "dark");
3619
+ }
3620
+ getComputedStyle(root).getPropertyValue("--pk-duration");
3621
+ }
3622
+ } finally {
3623
+ if (kept[0]) {
3624
+ root.style.setProperty("--pk-duration", kept[0], kept[1]);
3625
+ } else {
3626
+ root.style.removeProperty("--pk-duration");
3627
+ }
3628
+ }
3629
+ }
3233
3630
 
3234
3631
  // src/export-run.js
3235
- import { toGrid } from "pivotkit-core";
3236
3632
  var XLSX_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
3237
3633
  var exporters = null;
3238
3634
  var pending = null;
@@ -3249,6 +3645,14 @@ function loadExporters() {
3249
3645
  );
3250
3646
  return pending;
3251
3647
  }
3648
+ var reportPending = null;
3649
+ function loadReport(loadECharts) {
3650
+ reportPending ??= Promise.all([import("./chunks/report-run-BZBFOMPF.js"), loadECharts()]).catch((error) => {
3651
+ reportPending = null;
3652
+ throw error;
3653
+ });
3654
+ return reportPending;
3655
+ }
3252
3656
  var exportersNow = () => exporters;
3253
3657
  var prepareExporters = () => void loadExporters().catch(() => void 0);
3254
3658
  function deliver(blob, { doc, onExport, ...file }) {
@@ -3264,7 +3668,42 @@ async function copyOut(text, { type, container, onExport, ...file }) {
3264
3668
  }
3265
3669
  return await copyText(text, container) ? "copied" : "blocked";
3266
3670
  }
3267
- async function runExport(kind, { fileName, result, locale, labels, limits, root, chartRef, announce, onExport }) {
3671
+ var isColor = (text) => typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("color", text);
3672
+ function hexColor(text, ctx, supports = isColor) {
3673
+ if (!text || !ctx || !supports(text)) {
3674
+ return null;
3675
+ }
3676
+ ctx.fillStyle = text;
3677
+ const hex = String(ctx.fillStyle).toLowerCase();
3678
+ return /^#[0-9a-f]{6}$/.test(hex) ? hex : null;
3679
+ }
3680
+ var XLSX_TOKENS = Object.freeze(["--pk-scale-low", "--pk-scale-mid", "--pk-scale-high", "--pk-chart-1"]);
3681
+ function xlsxThemeOf(style, toHex) {
3682
+ const { colorScale = [], dataBar = "" } = chartThemeFrom(style);
3683
+ const scale = colorScale.map(toHex);
3684
+ const [low, high, mid] = [scale[0], scale.at(-1), scale.length === 3 ? scale[1] : null];
3685
+ const bar = toHex(dataBar);
3686
+ return {
3687
+ ...low && high ? { colorScale: mid ? [low, mid, high] : [low, high] } : {},
3688
+ ...bar ? { dataBar: bar } : {}
3689
+ };
3690
+ }
3691
+ function xlsxTheme(root) {
3692
+ if (!root) {
3693
+ return void 0;
3694
+ }
3695
+ const tokens = lightTokens(root, XLSX_TOKENS);
3696
+ const ctx = root.ownerDocument.createElement("canvas").getContext("2d");
3697
+ return xlsxThemeOf({ getPropertyValue: (name) => tokens[name] ?? "" }, (text) => hexColor(text, ctx));
3698
+ }
3699
+ function reportTokens(root, report, chart) {
3700
+ if (!root) {
3701
+ return void 0;
3702
+ }
3703
+ const tokens = lightTokens(root, report.REPORT_TOKENS, () => chart.tokenLengths(root, [...chart.LENGTH_TOKENS, ...report.REPORT_LENGTHS]));
3704
+ return Object.keys(tokens).length ? tokens : void 0;
3705
+ }
3706
+ async function runExport(kind, { fileName, result, encoded, exportData, locale, labels, limits, root, chartRef, announce, onExport, title, source, loadECharts }) {
3268
3707
  labels = menuLabels(labels);
3269
3708
  const base = safeFileName(fileName);
3270
3709
  const doc = root.current?.ownerDocument;
@@ -3278,9 +3717,70 @@ async function runExport(kind, { fileName, result, locale, labels, limits, root,
3278
3717
  }
3279
3718
  return;
3280
3719
  }
3720
+ if (kind === "data-csv" || kind === "data-json") {
3721
+ const data = encoded ?? result?.encoded;
3722
+ if (!exportData || !data) {
3723
+ return;
3724
+ }
3725
+ const m2 = exporters ?? await loadExporters();
3726
+ const csv = kind === "data-csv";
3727
+ const file2 = `${base}-data.${csv ? "csv" : "json"}`;
3728
+ const blob = csv ? new Blob([
3729
+ /** @type {BlobPart} */
3730
+ m2.dataToCsvBytes(data, limits ? { limits } : {})
3731
+ ], { type: "text/csv;charset=utf-8" }) : new Blob([m2.dataToJson(data, limits ? { limits } : {})], { type: "application/json" });
3732
+ if (deliver(blob, { kind, fileName: file2, doc, onExport })) {
3733
+ announce(fill(labels.toastExported, { file: file2 }));
3734
+ }
3735
+ return;
3736
+ }
3281
3737
  if (!result) {
3282
3738
  return;
3283
3739
  }
3740
+ if (kind === "html" || kind === "svg" || kind === "print") {
3741
+ const [report, echarts] = await loadReport(
3742
+ /** @type {() => Promise<any>} */
3743
+ loadECharts
3744
+ );
3745
+ const chart = chartRef.current;
3746
+ const size = chart ? { width: clampSize(chart.getWidth()), height: clampSize(chart.getHeight()) } : void 0;
3747
+ const rendered = await report.render(result.view, result.encoded, {
3748
+ format: kind === "svg" ? "svg" : "html",
3749
+ echarts,
3750
+ locale,
3751
+ trusted: true,
3752
+ labels: labels.core,
3753
+ ...limits ? { limits } : {},
3754
+ timeZone: result.timeZone,
3755
+ ...title ? { title } : {},
3756
+ ...source ? { source } : {},
3757
+ ...size ? { size } : {},
3758
+ tokens: reportTokens(root.current, report, echarts),
3759
+ chartEmbed: kind === "print" ? "inline" : "image"
3760
+ });
3761
+ const file2 = `${base}.${kind === "svg" ? "svg" : "html"}`;
3762
+ const blob = new Blob([
3763
+ /** @type {BlobPart} */
3764
+ rendered.body
3765
+ ], { type: rendered.mediaType });
3766
+ if (kind !== "print") {
3767
+ if (deliver(blob, { kind, fileName: file2, doc, onExport })) {
3768
+ announce(fill(labels.toastExported, { file: file2 }));
3769
+ }
3770
+ return;
3771
+ }
3772
+ if (onExport?.({ kind, fileName: file2, blob }) === false) {
3773
+ return;
3774
+ }
3775
+ if (!root.current || !await printHtml(
3776
+ /** @type {string} */
3777
+ rendered.text,
3778
+ root.current
3779
+ )) {
3780
+ announce(labels.toastPrintBlocked, { tone: "error" });
3781
+ }
3782
+ return;
3783
+ }
3284
3784
  const m = exporters ?? await loadExporters();
3285
3785
  const grid = toGrid(result, { locale, labels: labels.core, limits });
3286
3786
  if (kind === "copy-table" || kind === "copy-json") {
@@ -3292,7 +3792,7 @@ async function runExport(kind, { fileName, result, locale, labels, limits, root,
3292
3792
  return;
3293
3793
  }
3294
3794
  const file = `${base}.${kind}`;
3295
- const bytes = kind === "xlsx" ? m.toXlsx(grid, { sheetName: base }) : m.toCsvBytes(grid, { bom: true });
3795
+ const bytes = kind === "xlsx" ? m.toXlsx(grid, { sheetName: base, theme: xlsxTheme(root.current) }) : m.toCsvBytes(grid, { bom: true });
3296
3796
  if (deliver(new Blob([
3297
3797
  /** @type {BlobPart} */
3298
3798
  bytes
@@ -3303,6 +3803,7 @@ async function runExport(kind, { fileName, result, locale, labels, limits, root,
3303
3803
  announce(fill(labels.toastExportFailed, { message: messageOf(e) }), { tone: "error" });
3304
3804
  }
3305
3805
  }
3806
+ var clampSize = (px) => Math.max(100, Math.min(8e3, Math.round(Number(px) || 0)));
3306
3807
 
3307
3808
  // src/drill-export.js
3308
3809
  function rowsText({ shown, count }, labels, locale) {
@@ -3400,7 +3901,7 @@ function drillOf({ result, rowPath, colPath, count, indices, formatOf, nameOf, i
3400
3901
  // src/drill-panel.jsx
3401
3902
  function DrillPanel({ drill: source, onClose, labels, locale, exportContext }) {
3402
3903
  const id = useId6();
3403
- const drill = useMemo3(() => source ? drillOf(source, labels) : null, [source, labels]);
3904
+ const drill = useMemo4(() => source ? drillOf(source, labels) : null, [source, labels]);
3404
3905
  const panel = useRef4(
3405
3906
  /** @type {HTMLDivElement | null} */
3406
3907
  null