pivotkit-react 0.8.1 → 0.9.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 (56) hide show
  1. package/CHANGELOG.md +102 -1
  2. package/dist/chunks/chunk-24T2VRMU.js +1010 -0
  3. package/dist/chunks/chunk-6R7TJHS3.js +212 -0
  4. package/dist/chunks/{chunk-GUSQWPTH.js → chunk-EPGRJSPP.js} +20 -5
  5. package/dist/chunks/{chunk-JAOOFDNR.js → chunk-FAAQZSR4.js} +4 -1
  6. package/dist/chunks/{chunk-2N2UGSIG.js → chunk-FI22Z6CC.js} +5 -2
  7. package/dist/chunks/{chunk-ZM45YU3W.js → chunk-G3R5C3J7.js} +28 -6
  8. package/dist/chunks/{chunk-MU5BTKSY.js → chunk-QCBVEI23.js} +6 -2
  9. package/dist/chunks/{chunk-6OWC6X5W.js → chunk-QVE7JM4G.js} +1 -1
  10. package/dist/chunks/{chunk-3WWWKPB4.js → chunk-V233JHVY.js} +75 -336
  11. package/dist/chunks/chunk-W6BG3GGS.js +679 -0
  12. package/dist/chunks/chunk-YAT2TFMK.js +138 -0
  13. package/dist/chunks/chunk-ZQ2M3U74.js +341 -0
  14. package/dist/chunks/{unused-texts-de-GB3IWWEM.js → labels-de-ZC3CSQZR.js} +1 -1
  15. package/dist/chunks/tips-SYGQPI3Q.js +22 -0
  16. package/dist/chunks/{unused-texts-LRYVWFFN.js → unused-texts-ERQ6ACNX.js} +1 -1
  17. package/dist/chunks/unused-texts-de-AC5GS3FS.js +6 -0
  18. package/dist/deferred-late.js +13 -0
  19. package/dist/deferred.js +18 -0
  20. package/dist/echarts.js +30 -6
  21. package/dist/import-ui.js +3 -3
  22. package/dist/index.js +442 -208
  23. package/dist/labels.js +15 -12
  24. package/dist/menu-texts-de.js +1 -1
  25. package/dist/menus.js +518 -381
  26. package/dist/styles.css +128 -9
  27. package/package.json +5 -4
  28. package/types/PivotReport.d.ts +3 -1
  29. package/types/chart-tooltip.d.ts +18 -1
  30. package/types/chart-types.d.ts +7 -2
  31. package/types/chart.d.ts +10 -2
  32. package/types/chip-menus.d.ts +1 -1
  33. package/types/deferred-late.d.ts +2 -0
  34. package/types/deferred.d.ts +28 -0
  35. package/types/field-info.d.ts +6 -3
  36. package/types/fields.d.ts +3 -2
  37. package/types/icons.d.ts +2 -0
  38. package/types/index.d.ts +20 -10
  39. package/types/labels-de.d.ts +2 -0
  40. package/types/labels.d.ts +55 -459
  41. package/types/lazy-menus.d.ts +2 -2
  42. package/types/menu-labels.d.ts +20 -0
  43. package/types/menu-ops.d.ts +33 -0
  44. package/types/menu-topics.d.ts +6 -3
  45. package/types/menus.d.ts +1 -0
  46. package/types/names.d.ts +20 -2
  47. package/types/notices.d.ts +212 -0
  48. package/types/point-menu.d.ts +21 -0
  49. package/types/quick-choices.d.ts +28 -0
  50. package/types/side-by-side.d.ts +19 -0
  51. package/types/tip-state.d.ts +97 -0
  52. package/types/tips.d.ts +13 -250
  53. package/types/unused-texts.d.ts +3 -0
  54. package/types/view-ops.d.ts +27 -14
  55. package/types/view-tabs.d.ts +4 -3
  56. package/dist/chunks/chunk-W2SVDHGN.js +0 -1898
@@ -1,1898 +0,0 @@
1
- import {
2
- Icon,
3
- Popover,
4
- onTheWay,
5
- useFormName
6
- } from "./chunk-JAOOFDNR.js";
7
- import {
8
- fill,
9
- plural
10
- } from "./chunk-3WWWKPB4.js";
11
-
12
- // src/chart-types.js
13
- import { chartPlan as corePlan } from "pivotkit-core";
14
- var CHART_TYPES = Object.freeze({
15
- auto: { chart: { type: "auto", stacked: false, horizontal: false }, icon: "sparkle", axis: true },
16
- bar: { chart: { type: "bar", stacked: false, horizontal: false }, icon: "chart", axis: true },
17
- stacked: { chart: { type: "bar", stacked: true, horizontal: false }, icon: "stacked", axis: true },
18
- horizontal: { chart: { type: "bar", stacked: false, horizontal: true }, icon: "horizontal", axis: true },
19
- line: { chart: { type: "line", stacked: false, horizontal: false }, icon: "line", axis: true },
20
- area: { chart: { type: "area", stacked: false, horizontal: false }, icon: "area", axis: true },
21
- pie: { chart: { type: "pie", stacked: false, horizontal: false }, icon: "pie", axis: false },
22
- donut: { chart: { type: "donut", stacked: false, horizontal: false }, icon: "donut", axis: false },
23
- heatmap: { chart: { type: "heatmap", stacked: false, horizontal: false }, icon: "heatmap", axis: false }
24
- });
25
- var SLICE_TYPES = Object.freeze(["pie", "donut"]);
26
- var CHART_TYPE_NAMES = Object.freeze(Object.keys(CHART_TYPES));
27
- function chartTypeOf(chart2) {
28
- const found = CHART_TYPE_NAMES.find((name2) => {
29
- const c = CHART_TYPES[name2].chart;
30
- return c.type === chart2.type && c.stacked === Boolean(chart2.stacked) && c.horizontal === Boolean(chart2.horizontal);
31
- });
32
- if (found) {
33
- return found;
34
- }
35
- if (chart2.type === "bar") {
36
- return chart2.horizontal ? "horizontal" : "stacked";
37
- }
38
- return CHART_TYPE_NAMES.find((name2) => CHART_TYPES[name2].chart.type === chart2.type) ?? "bar";
39
- }
40
- function chartPlan(view, encoded) {
41
- const plan = corePlan(view, encoded);
42
- return { name: chartTypeOf(plan.chart), ...plan };
43
- }
44
- var MANY_SERIES = 8;
45
- var MAX_CATEGORIES = 50;
46
-
47
- // src/view-ops.js
48
- import { MAX_DATE_MS } from "pivotkit-core";
49
- import { LIMITS, aggregatorsFor, foldText, isFormat, swapAxes } from "pivotkit-core";
50
- var ZONES = Object.freeze(
51
- /** @type {Zone[]} */
52
- ["filters", "cols", "rows", "values"]
53
- );
54
- var clone = (view) => JSON.parse(JSON.stringify(view));
55
- var NEGATED = Object.freeze({ "=": "!=", between: "notBetween", equals: "notEquals", contains: "notContains", beginsWith: "notBeginsWith", endsWith: "notEndsWith" });
56
- var RULE_OPS = Object.freeze({
57
- text: Object.freeze(["equals", "notEquals", "contains", "notContains", "beginsWith", "notBeginsWith", "endsWith", "notEndsWith"]),
58
- compare: Object.freeze(["=", "!=", ">", ">=", "<", "<=", "between", "notBetween"])
59
- });
60
- var ruleOp = (f) => f.not && typeof f.op === "string" && Object.hasOwn(NEGATED, f.op) ? NEGATED[f.op] : String(f.op);
61
- var hiddenNot = (f) => Boolean(f.not) && !(typeof f.op === "string" && Object.hasOwn(NEGATED, f.op));
62
- function opOf(menuOp) {
63
- const positive = Object.keys(NEGATED).find((op) => NEGATED[op] === menuOp);
64
- return positive ? { op: positive, not: true } : { op: menuOp, not: false };
65
- }
66
- var pickFilter = (field, excluded) => ({ field, type: "in", items: excluded.filter((v) => v !== null), not: true, blanks: excluded.includes(null) ? "exclude" : "include" });
67
- var emptyPick = (field) => pickFilter(field, []);
68
- var isPick = (f) => f.type === "in";
69
- var isEmptyPick = (f) => isPick(f) && f.not === true && f.items.length === 0 && f.blanks === "include";
70
- var same = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
71
- function searchItems(items, query) {
72
- const q = foldText(query);
73
- return q ? items.filter((i) => foldText(i.label).includes(q)) : items;
74
- }
75
- var clamp = (i, n) => Number.isInteger(i) ? Math.max(0, Math.min(i, n)) : n;
76
- function filterZoneFields(view) {
77
- const seen = /* @__PURE__ */ new Set();
78
- const out = [];
79
- for (const f of view.filters) {
80
- const key = f.field.toLowerCase();
81
- if (!seen.has(key) && !view.rows.some((r) => same(r, f.field)) && !view.cols.some((c) => same(c, f.field))) {
82
- seen.add(key);
83
- out.push(f.field);
84
- }
85
- }
86
- return out;
87
- }
88
- function axisOf(view, field) {
89
- if (view.rows.some((r) => same(r, field))) {
90
- return "rows";
91
- }
92
- if (view.cols.some((c) => same(c, field))) {
93
- return "cols";
94
- }
95
- return null;
96
- }
97
- function defaultAgg(type, wanted) {
98
- if (typeof wanted === "string" && aggregatorsFor(type ?? "string").includes(wanted)) {
99
- return wanted;
100
- }
101
- return type === "number" && aggregatorsFor(type).includes("sum") ? "sum" : "count";
102
- }
103
- function tidy(view) {
104
- const used = new Set([...view.rows, ...view.cols, ...view.values.map((v) => v.field), ...view.filters.map((f) => f.field)].filter(Boolean).map((n) => n.toLowerCase()));
105
- view.derived = view.derived.filter((d) => used.has(d.name.toLowerCase()));
106
- view.sort = view.sort.filter((s) => used.has(s.field.toLowerCase()));
107
- return view;
108
- }
109
- function dropFromAxes(view, field) {
110
- view.rows = view.rows.filter((r) => !same(r, field));
111
- view.cols = view.cols.filter((c) => !same(c, field));
112
- }
113
- function resetCollapsed(view, before) {
114
- for (const axis of ["rows", "cols"]) {
115
- if (JSON.stringify(before[axis]) !== JSON.stringify(view[axis])) {
116
- view.collapsed[axis] = [];
117
- }
118
- }
119
- }
120
- function zoneOverLimit(view, limits) {
121
- for (
122
- const zone of
123
- /** @type {const} */
124
- ["rows", "cols", "values"]
125
- ) {
126
- const list = view && Array.isArray(view[zone]) ? view[zone] : [];
127
- const max = (
128
- /** @type {number} */
129
- zoneMax(zone, limits)
130
- );
131
- if (list.length > max) {
132
- return { zone, max };
133
- }
134
- }
135
- return null;
136
- }
137
- function zoneMax(zone, limits) {
138
- const name2 = zone === "values" ? "values" : zone === "rows" || zone === "cols" ? "axisFields" : null;
139
- if (!name2) {
140
- return null;
141
- }
142
- const own2 = limits?.[name2];
143
- return typeof own2 === "number" && Number.isInteger(own2) && own2 > 0 ? own2 : LIMITS[name2];
144
- }
145
- function addField(view, field, zone, options = {}) {
146
- if (options.dateUnit && zone !== "values") {
147
- const name2 = options.groupName ?? `${field} (${options.dateUnit})`;
148
- const placed = addField(removeField(view, name2), field, zone, { ...options, dateUnit: null, defaults: void 0 });
149
- return groupField(placed, field, options.dateUnit, { name: name2 }).view;
150
- }
151
- const next = clone(view);
152
- if (zone === "rows" || zone === "cols") {
153
- dropFromAxes(next, field);
154
- next[zone].splice(clamp(options.index, next[zone].length), 0, field);
155
- const order = options.defaults?.order;
156
- if (Array.isArray(order) && order.length > 0 && !next.sort.some((s) => same(s.field, field))) {
157
- next.sort.push({ field, by: "custom", order: "asc", items: [...order] });
158
- }
159
- } else if (zone === "values") {
160
- const wanted = options.defaults ?? {};
161
- const format = typeof wanted.format === "string" && isFormat(wanted.format) ? wanted.format : null;
162
- next.values.splice(clamp(options.index, next.values.length), 0, { field, agg: defaultAgg(options.type, wanted.agg), format, label: null, showAs: null, conditional: null });
163
- } else if (zone === "filters") {
164
- dropFromAxes(next, field);
165
- if (!next.filters.some((f) => same(f.field, field))) {
166
- next.filters.push(emptyPick(field));
167
- }
168
- }
169
- resetCollapsed(next, view);
170
- return tidy(next);
171
- }
172
- function removeAt(view, zone, index) {
173
- const next = clone(view);
174
- if (zone === "values") {
175
- next.values.splice(index, 1);
176
- } else {
177
- const list = zone === "filters" ? filterZoneFields(view) : view[zone];
178
- const field = list[index];
179
- if (field === void 0) {
180
- return view;
181
- }
182
- dropFromAxes(next, field);
183
- next.filters = next.filters.filter((f) => !same(f.field, field));
184
- }
185
- resetCollapsed(next, view);
186
- return tidy(next);
187
- }
188
- function removeField(view, field) {
189
- if (!axisOf(view, field) && !filterZoneFields(view).some((f) => same(f, field))) {
190
- return view;
191
- }
192
- const next = clone(view);
193
- dropFromAxes(next, field);
194
- next.filters = next.filters.filter((f) => !same(f.field, field));
195
- resetCollapsed(next, view);
196
- return tidy(next);
197
- }
198
- function fieldAt(view, zone, index) {
199
- if (zone === "values") {
200
- return view.values[index] ? view.values[index].field : void 0;
201
- }
202
- return (zone === "filters" ? filterZoneFields(view) : view[zone])[index];
203
- }
204
- function moveField(view, from, fromIndex, to, toIndex, options = {}) {
205
- if (from === to) {
206
- return reorder(view, from, fromIndex, toIndex);
207
- }
208
- const field = fieldAt(view, from, fromIndex);
209
- if (field === void 0 || field === null) {
210
- return view;
211
- }
212
- let next = clone(view);
213
- if (from === "values") {
214
- next.values.splice(fromIndex, 1);
215
- } else if (to !== "filters") {
216
- dropFromAxes(next, field);
217
- if (to === "values") {
218
- next.filters = next.filters.filter((f) => !same(f.field, field));
219
- }
220
- }
221
- next = addField(next, field, to, { ...options, index: toIndex });
222
- resetCollapsed(next, view);
223
- return tidy(next);
224
- }
225
- function reorder(view, zone, from, to) {
226
- const list = zone === "filters" ? null : zone === "values" ? view.values : view[zone];
227
- if (!list || from === to || from < 0 || from >= list.length) {
228
- return view;
229
- }
230
- const next = clone(view);
231
- const target = next[zone];
232
- const [item] = target.splice(from, 1);
233
- target.splice(clamp(to, target.length), 0, item);
234
- resetCollapsed(next, view);
235
- return next;
236
- }
237
- function numberRange(encoded, field) {
238
- const column = encoded.column(field);
239
- if (!column || column.type !== "number") {
240
- return null;
241
- }
242
- let min = Infinity;
243
- let max = -Infinity;
244
- for (const v of column.dict) {
245
- if (typeof v === "number" && Number.isFinite(v)) {
246
- min = Math.min(min, v);
247
- max = Math.max(max, v);
248
- }
249
- }
250
- return min <= max ? { min, max } : null;
251
- }
252
- var dateSpans = /* @__PURE__ */ new WeakMap();
253
- function dateSpan(encoded, field) {
254
- let spans = dateSpans.get(encoded);
255
- if (!spans) dateSpans.set(encoded, spans = /* @__PURE__ */ new Map());
256
- const key = field.toLowerCase();
257
- if (spans.has(key)) {
258
- const span2 = spans.get(key) ?? null;
259
- spans.delete(key);
260
- spans.set(key, span2);
261
- return span2;
262
- }
263
- const column = encoded.column(field);
264
- if (!column || column.type !== "date") {
265
- return null;
266
- }
267
- let min = Infinity;
268
- let max = -Infinity;
269
- for (const v of column.dict) {
270
- if (typeof v === "number" && Number.isFinite(v) && Math.abs(v) <= MAX_DATE_MS) {
271
- min = Math.min(min, v);
272
- max = Math.max(max, v);
273
- }
274
- }
275
- const span = min <= max ? { min, max } : null;
276
- spans.set(key, span);
277
- if (spans.size > LIMITS.cacheEntries) {
278
- const oldest = spans.keys().next().value;
279
- if (oldest !== void 0) spans.delete(oldest);
280
- }
281
- return span;
282
- }
283
- function groupField(view, field, unit, options = {}) {
284
- const spec = view.derived.find((d) => same(d.name, field));
285
- const source = spec ? spec.field : field;
286
- const axis = axisOf(view, field);
287
- const next = clone(view);
288
- let name2 = source;
289
- if (unit) {
290
- name2 = options.name ?? `${source} (${unit})`;
291
- const existing = next.derived.find((d) => same(d.name, name2));
292
- const origin = options.origin ?? (spec?.by === "bin" ? spec.origin ?? 0 : 0);
293
- const wanted = unit === "bin" ? { name: name2, field: source, by: unit, size: options.size, origin } : { name: name2, field: source, by: unit };
294
- if (existing) {
295
- Object.assign(existing, wanted);
296
- } else {
297
- next.derived.push(wanted);
298
- }
299
- }
300
- if (axis) {
301
- const other = axis === "rows" ? "cols" : "rows";
302
- if (!same(name2, field) && next[other].some((f) => same(f, name2))) {
303
- next[axis] = next[axis].filter((f) => !same(f, field));
304
- } else {
305
- const seen = /* @__PURE__ */ new Set();
306
- next[axis] = next[axis].map((f) => same(f, field) ? name2 : f).filter((f) => !seen.has(f.toLowerCase()) && seen.add(f.toLowerCase()));
307
- }
308
- }
309
- if (!same(name2, field)) {
310
- const inFilterZone = !axis && filterZoneFields(view).some((f) => same(f, field));
311
- next.filters = next.filters.filter((f) => !same(f.field, field));
312
- if (inFilterZone) {
313
- next.filters.push(emptyPick(name2));
314
- }
315
- }
316
- next.sort = next.sort.map((s) => same(s.field, field) ? { ...s, field: name2 } : s);
317
- resetCollapsed(next, view);
318
- return { view: tidy(next), field: name2 };
319
- }
320
- function groupingOf(view, field) {
321
- return view.derived.find((d) => same(d.name, field)) ?? null;
322
- }
323
- function sourceOf(view, field) {
324
- const spec = groupingOf(view, field);
325
- return spec ? spec.field : field;
326
- }
327
- function setSort(view, field, sort) {
328
- const next = clone(view);
329
- next.sort = next.sort.filter((s) => !same(s.field, field));
330
- if (sort) {
331
- next.sort.push({ field, ...sort });
332
- }
333
- return next;
334
- }
335
- function withHostOrders(view, orderOf) {
336
- const missing = [...view.rows, ...view.cols].filter((field) => !view.derived.some((d) => same(d.name, field)) && !view.sort.some((s) => same(s.field, field)));
337
- const added = missing.map((field) => ({ field, order: orderOf(field) })).filter(({ order }) => Array.isArray(order) && order.length > 0);
338
- if (!added.length) {
339
- return view;
340
- }
341
- const next = clone(view);
342
- for (const { field, order } of added) {
343
- next.sort.push({ field, by: "custom", order: "asc", items: [.../** @type {unknown[]} */
344
- order] });
345
- }
346
- return next;
347
- }
348
- function sortOf(view, field) {
349
- return view.sort.find((s) => same(s.field, field)) ?? null;
350
- }
351
- function sortEntry(spec, hostOrdered) {
352
- return spec.by === "label" && spec.order === "asc" && !hostOrdered ? null : spec;
353
- }
354
- function headerSortTarget(view, cell, typeOf) {
355
- if (cell.kind === "corner") {
356
- return cell.field && view.rows.some((f) => same(f, cell.field)) ? { field: cell.field } : null;
357
- }
358
- const spec = cell.kind === "colHeader" && cell.valueIndex !== void 0 && !cell.colPath?.length ? view.values[cell.valueIndex] : void 0;
359
- if (!spec || !view.rows.length || !numericResult(spec, spec.field ? typeOf(spec.field) ?? "string" : "number")) {
360
- return null;
361
- }
362
- return { field: view.rows[view.rows.length - 1], ref: { field: spec.field ?? null, agg: spec.agg } };
363
- }
364
- function headerSortState(view, target) {
365
- const s = sortOf(view, target.field);
366
- const word = (order) => order === "desc" ? "descending" : "ascending";
367
- if (target.ref) {
368
- return s?.by === "value" && sameRef(s.value, target.ref) ? { order: word(s.order), chosen: true } : { order: null, chosen: false };
369
- }
370
- if (!s) {
371
- return { order: "ascending", chosen: false };
372
- }
373
- return { order: s.by === "label" ? word(s.order) : s.by === "custom" ? "other" : null, chosen: s.by === "label" };
374
- }
375
- function nextHeaderSort(view, target, hostOrdered) {
376
- const s = sortOf(view, target.field);
377
- if (target.ref) {
378
- const mine = s?.by === "value" && sameRef(s.value, target.ref);
379
- return mine && s.order === "asc" ? null : { by: "value", order: mine ? "asc" : "desc", value: mine ? s.value : target.ref };
380
- }
381
- const desc = !s || s.by === "label" && s.order === "asc";
382
- return sortEntry({ by: "label", order: desc ? "desc" : "asc" }, hostOrdered);
383
- }
384
- function filtersOf(view, field, types) {
385
- return view.filters.filter((f) => same(f.field, field) && (!types || types.includes(f.type)));
386
- }
387
- function selectedItems(view, field, all) {
388
- let selected = all;
389
- for (const f of filtersOf(view, field, ["in"])) {
390
- const listed = new Set(f.items.map((v) => JSON.stringify(v)));
391
- const blank = f.blanks !== "exclude";
392
- selected = selected.filter((v) => v === null ? blank : f.blanks !== "only" && listed.has(JSON.stringify(v)) !== f.not);
393
- }
394
- return selected;
395
- }
396
- function numericResult(spec, type) {
397
- return spec.agg !== "listUnique" && !(["first", "last"].includes(spec.agg) && type !== "number") && !(type === "date" && ["average", "median", "min", "max"].includes(spec.agg));
398
- }
399
- function sameRef(a, b) {
400
- return Boolean(a && b) && a.agg === b.agg && (a.field === null || b.field === null ? a.field === b.field : same(a.field, b.field));
401
- }
402
- function isFiltered(view, field) {
403
- return filtersOf(view, field).some((f) => !isEmptyPick(f));
404
- }
405
- function toggleCollapsed(view, axis, path) {
406
- const next = clone(view);
407
- const key = JSON.stringify(path);
408
- const list = next.collapsed[axis];
409
- const at = list.findIndex((p) => JSON.stringify(p) === key);
410
- if (at === -1) {
411
- list.push(path);
412
- } else {
413
- list.splice(at, 1);
414
- }
415
- return next;
416
- }
417
- function rowFolding(view, outer) {
418
- const keys = new Set(view.collapsed.rows.map((p) => JSON.stringify(p)));
419
- const collapsed = outer.filter((p) => keys.has(JSON.stringify(p))).length;
420
- const open = view.rows.length < 2 ? 0 : outer.length - collapsed;
421
- const canExpand = view.collapsed.rows.length > 0;
422
- const canCollapse = open > 0;
423
- return {
424
- canExpand,
425
- canCollapse,
426
- collapsed: view.collapsed.rows.length,
427
- open,
428
- // keys of the menus' texts (menu-labels.js): Table settings and Chart settings show them
429
- why: {
430
- expand: canExpand ? null : view.rows.length < 2 ? "collapseNeedsRows" : "expandNothing",
431
- collapse: canCollapse ? null : view.rows.length < 2 ? "collapseNeedsRows" : "collapseAllDone"
432
- }
433
- };
434
- }
435
- function setCollapsed(view, axis, paths) {
436
- const next = clone(view);
437
- next.collapsed[axis] = paths ? paths : [];
438
- return next;
439
- }
440
- function setTotal(view, key, on) {
441
- const next = clone(view);
442
- next.totals[key] = Boolean(on);
443
- return next;
444
- }
445
- function setDisplay(view, display) {
446
- const next = clone(view);
447
- next.display = display;
448
- return next;
449
- }
450
- function setChart(view, name2) {
451
- const next = clone(view);
452
- next.chart = { ...next.chart, ...CHART_TYPES[name2].chart };
453
- next.display = "chart";
454
- return next;
455
- }
456
- function setChartDisplay(view, patch) {
457
- const next = clone(view);
458
- next.chart = { ...next.chart, ...patch };
459
- return next;
460
- }
461
- function hiddenAfter(hidden, name2, shown) {
462
- const rest = (hidden ?? []).filter((n) => n !== name2);
463
- return shown ? rest : [...rest, name2];
464
- }
465
- function isEmptyView(view) {
466
- return view.rows.length === 0 && view.cols.length === 0 && view.values.length === 0;
467
- }
468
-
469
- // src/names.js
470
- import { MAX_DATE_MS as MAX_DATE_MS2, fieldLabel, formatter, numberRepeats, relativeDateRange } from "pivotkit-core";
471
- var withNot = (f, text, labels) => hiddenNot(f) ? fill(labels.notRule, { rule: text }) : text;
472
- var valueLabels = (values, labels) => numberRepeats(values.map((v) => valueLabel(v, labels)));
473
- function valueLabel(spec, labels) {
474
- if (spec.label) {
475
- return spec.label;
476
- }
477
- const core = labels.core;
478
- let base;
479
- if (!spec.field) {
480
- base = core.countRows;
481
- } else {
482
- const agg = Object.hasOwn(core.aggregators, spec.agg) ? core.aggregators[spec.agg] : spec.agg;
483
- base = fill(core.valueName, { agg, field: fieldLabel(spec.field, core) });
484
- }
485
- if (!spec.showAs || !core.showAs || !core.showAsName) {
486
- return base;
487
- }
488
- const showAs = Object.hasOwn(core.showAs, spec.showAs.type) ? core.showAs[spec.showAs.type] : spec.showAs.type;
489
- return fill(core.showAsName, { showAs, value: spec.field && spec.agg === "sum" ? fieldLabel(spec.field, core) : base });
490
- }
491
- function refLabel(view, ref, labels) {
492
- const field = ref?.field ?? null;
493
- const sameField = (v) => field === null || v.field === null || v.field === void 0 ? (v.field ?? null) === field : v.field.toLowerCase() === field.toLowerCase();
494
- const spec = ref ? (view.values ?? []).find((v) => v.agg === ref.agg && sameField(v)) : void 0;
495
- if (!spec && field === null) {
496
- return labels.countOfRows;
497
- }
498
- return valueLabel({ ...spec ?? ref, showAs: null }, labels);
499
- }
500
- function sortText(view, sort, labels) {
501
- const desc = sort.order === "desc";
502
- if (sort.by === "value") {
503
- return fill(desc ? labels.sortValueDesc : labels.sortValueAsc, { value: refLabel(view, sort.value, labels) });
504
- }
505
- if (sort.by === "custom") {
506
- return desc ? labels.sortCustomDesc : labels.sortCustom;
507
- }
508
- return desc ? labels.sortLabelDesc : labels.sortLabelAsc;
509
- }
510
- var OP_SIGNS = Object.freeze({ "=": "=", "!=": "\u2260", ">": ">", ">=": "\u2265", "<": "<", "<=": "\u2264" });
511
- function valueConditionText(view, f, labels, locale) {
512
- const number = (x) => typeof x === "number" ? x.toLocaleString(locale, { maximumFractionDigits: 6 }) : "";
513
- const value = refLabel(view, f.by ?? (view.values?.[0] ? { field: view.values[0].field ?? null, agg: view.values[0].agg } : null), labels);
514
- const op = ruleOp(f);
515
- if (op === "between" || op === "notBetween") {
516
- const [from, to] = typeof f.value2 === "number" && f.value2 < f.value ? [f.value2, f.value] : [f.value, f.value2];
517
- return fill(labels.valueConditions[op], { value, from: number(from), to: number(to) });
518
- }
519
- return withNot(f, fill(labels.valueConditions.compare, { value, op: Object.hasOwn(OP_SIGNS, op) ? OP_SIGNS[op] : op, number: number(f.value) }), labels);
520
- }
521
- var dayPart = (iso) => iso.split("T")[0];
522
- var dayMs = (iso) => Date.parse(`${dayPart(iso)}T00:00Z`);
523
- var yearOf = (iso) => Number(iso.slice(0, iso.indexOf("-", 1)));
524
- var monthOf = (iso) => Number(dayPart(iso).slice(-5, -3));
525
- var isoYear = (y) => y >= 0 && y <= 9999 ? String(y).padStart(4, "0") : `${y < 0 ? "-" : "+"}${String(Math.abs(y)).padStart(6, "0")}`;
526
- var midYear = (y) => {
527
- const d = /* @__PURE__ */ new Date(0);
528
- d.setUTCFullYear(y, 6, 1);
529
- return d;
530
- };
531
- var yearText = (y, locale) => y >= 1 ? String(y) : midYear(y).toLocaleDateString(locale, { year: "numeric", era: "short", calendar: "gregory", timeZone: "UTC" });
532
- var monthText = (iso, locale) => {
533
- const y = yearOf(iso);
534
- const at = Math.max(dayMs(`${isoYear(y)}-${String(monthOf(iso)).padStart(2, "0")}-01`) || -MAX_DATE_MS2, -MAX_DATE_MS2);
535
- return new Date(at).toLocaleDateString(locale, { month: "short", year: "numeric", timeZone: "UTC", ...y < 1 ? { era: "short" } : {} });
536
- };
537
- var dayText = (iso, locale) => formatter("date", { locale })(dayMs(iso));
538
- var isoDay = (ms) => new Date(ms).toISOString().split("T")[0];
539
- var dayAfter = (iso, n = 1) => isoDay(dayMs(iso) + n * 864e5);
540
- function relativeDays(f, timeZone, now, latest, more = {}) {
541
- const range = datesOf(f, timeZone, now, latest, more);
542
- return range && range.from !== null ? { from: range.from, to: range.to } : null;
543
- }
544
- var todayIn = (timeZone, now) => relativeDays({ unit: "day" }, timeZone, now)?.from ?? isoDay(now === void 0 ? Date.now() : new Date(now).getTime());
545
- function namedUntil(range, span, today) {
546
- const [from, to] = [dayPart(range.from), dayPart(range.to)];
547
- const ended = dayMs(isoDay(span.max)) <= dayMs(today);
548
- return ended && dayMs(from) <= dayMs(today) && dayMs(today) <= dayMs(to) ? dayAfter(today, -1) : to;
549
- }
550
- var datesOf = (f, timeZone, now, latest, more = {}) => relativeDateRange(f.unit, f.count ?? 1, { timeZone, now, anchor: f.anchor, latest: latest ?? void 0, first: more.first ?? void 0, direction: f.direction, calendar: f.calendar, includeCurrent: f.includeCurrent, weekStart: more.weekStart });
551
- var plainRange = (f) => ["last", "this"].includes(f.direction ?? "last") && f.calendar !== false && (f.anchor === void 0 || f.anchor === "today" || f.anchor === "latest") && ["year", "quarter", "month", "week", "day"].includes(f.unit);
552
- function periodText(range, unit, locale) {
553
- const year = (iso) => yearText(yearOf(iso), locale);
554
- const quarter = (iso) => `Q${Math.floor((monthOf(iso) - 1) / 3) + 1} ${year(iso)}`;
555
- const text = unit === "year" ? year : unit === "quarter" ? quarter : unit === "month" ? (iso) => monthText(iso, locale) : (iso) => dayText(dayPart(iso), locale);
556
- const [from, to] = [text(range.from), text(range.to)];
557
- return from === to ? from : `${from}\u2013${to}`;
558
- }
559
- function rangeShare(range, unit, span, locale, today) {
560
- const grain = unit === "quarter" ? "month" : unit === "week" ? "day" : unit;
561
- range = { from: dayPart(range.from), to: dayPart(range.to) };
562
- const until = namedUntil(range, span, today);
563
- const [first, last] = [periodStart(isoDay(span.min), grain), periodEnd(isoDay(span.max), grain)];
564
- if (dayMs(first) <= dayMs(range.from) && dayMs(last) >= dayMs(until)) {
565
- return null;
566
- }
567
- const from = dayMs(range.from) > dayMs(first) ? range.from : first;
568
- const to = dayMs(range.to) < dayMs(last) ? range.to : last;
569
- if (dayMs(from) > dayMs(to)) {
570
- return dayMs(range.from) > dayMs(until) ? null : until === range.to ? { none: true } : { none: true, to: until };
571
- }
572
- const missing = [];
573
- let count = 0;
574
- const part = (a, b, dataYear) => {
575
- const years = [];
576
- const [ya, yb] = [yearOf(a), yearOf(b)];
577
- for (let y = ya; y <= yb; y++) {
578
- if (y !== dataYear) {
579
- years.push(y);
580
- }
581
- }
582
- if (years.length) {
583
- missing.push(years.length === 1 ? yearText(years[0], locale) : `${yearText(years[0], locale)}\u2013${yearText(years[years.length - 1], locale)}`);
584
- count += years.length;
585
- }
586
- if (ya <= dataYear && dataYear <= yb) {
587
- const yearFrom = `${isoYear(dataYear)}-01-01`;
588
- const yearTo = `${isoYear(dataYear)}-12-31`;
589
- const rest = { from: dayMs(a) > dayMs(yearFrom) ? a : yearFrom, to: dayMs(b) < dayMs(yearTo) ? b : yearTo };
590
- missing.push(periodText(rest, unit, locale));
591
- count += periodText({ from: rest.from, to: rest.from }, unit, locale) === periodText({ from: rest.to, to: rest.to }, unit, locale) ? 1 : 2;
592
- }
593
- };
594
- const before = dayMs(until) < dayMs(first) ? until : dayAfter(first, -1);
595
- if (dayMs(range.from) <= dayMs(before)) {
596
- part(range.from, before, yearOf(first));
597
- }
598
- if (dayMs(until) > dayMs(last)) {
599
- part(dayAfter(last), until, yearOf(last));
600
- }
601
- return missing.length ? { none: false, data: periodText({ from, to }, unit, locale), missing, count } : null;
602
- }
603
- var periodStart = (iso, unit) => unit === "year" ? `${isoYear(yearOf(iso))}-01-01` : unit === "month" ? `${iso.slice(0, -3)}-01` : iso;
604
- function periodEnd(iso, unit) {
605
- if (unit === "day") {
606
- return iso;
607
- }
608
- const [y, m] = [yearOf(iso), monthOf(iso)];
609
- const end = /* @__PURE__ */ new Date(0);
610
- end.setUTCFullYear(y, unit === "year" ? 11 : m, unit === "year" ? 31 : 0);
611
- return isoDay(Math.min(end.getTime(), MAX_DATE_MS2) || MAX_DATE_MS2);
612
- }
613
- function relativeText(f, labels, locale, timeZone, now, span, weekStart) {
614
- if (!plainRange(f)) {
615
- return otherRangeText(f, labels, locale, timeZone, now, span, weekStart);
616
- }
617
- const more = labels.relativeMore;
618
- const count = f.count ?? 1;
619
- const key = count === 1 ? f.unit : `${f.unit}s`;
620
- let text = f.direction === "this" ? more.this[f.unit] ?? f.unit : Object.hasOwn(labels.relative, key) ? fill(labels.relative[key], { count: count.toLocaleString(locale) }) : fill(plural(more.last[f.unit] ?? { other: f.unit }, count, { lang: labels.lang, locale }), { count: count.toLocaleString(locale) });
621
- const range = relativeDays(f, timeZone, now, span?.max, { weekStart });
622
- const latest = f.anchor === "latest";
623
- if (f.includeCurrent === false && f.direction !== "this" && !latest) {
624
- text = fill(more.withoutCurrent, { text });
625
- }
626
- if (!range) {
627
- return text;
628
- }
629
- if (latest) {
630
- text = fill(labels.relativeTo, { text, end: periodText({ from: range.to, to: range.to }, f.unit, locale) });
631
- }
632
- const share = span ? rangeShare(range, f.unit, span, locale, todayIn(timeZone, now)) : null;
633
- if (!share) {
634
- return latest ? text : fill(labels.withRange, { text, range: periodText(range, f.unit, locale) });
635
- }
636
- const lang = { lang: labels.lang, locale };
637
- if (share.none) {
638
- return fill(labels.withRange, { text, range: fill(plural(labels.noData, 1, lang), { range: periodText({ from: range.from, to: share.to ?? range.to }, f.unit, locale) }) });
639
- }
640
- return fill(labels.withShare, { text, range: share.data, missing: fill(plural(labels.noData, share.count, lang), { range: share.missing.join(", ") }) });
641
- }
642
- function otherRangeText(f, labels, locale, timeZone, now, span, weekStart) {
643
- const more = labels.relativeMore;
644
- const lang = { lang: labels.lang, locale };
645
- const direction = f.direction ?? "last";
646
- let text = direction === "this" ? more.this[f.unit] ?? f.unit : plural(more[direction]?.[f.unit] ?? { other: f.unit }, f.count ?? 1, lang);
647
- if (f.calendar === false && direction !== "this") {
648
- text = fill(more.rolling, { text });
649
- } else if (f.includeCurrent === false && direction !== "this") {
650
- text = fill(more.withoutCurrent, { text });
651
- }
652
- if (f.anchor === "latest") {
653
- text = fill(more.fromLatest, { text });
654
- } else if (f.anchor === "first") {
655
- text = fill(more.fromFirst, { text });
656
- } else if (f.anchor && f.anchor !== "today") {
657
- text = fill(more.fromDate, { text, date: pointText(f.anchor, locale) });
658
- }
659
- const range = datesOf(f, timeZone, now, span?.max, { first: span?.min, weekStart });
660
- if (!range) {
661
- return text;
662
- }
663
- const days = (range.from === null || range.from.endsWith("T00:00")) && range.to.endsWith("T00:00");
664
- const point = (iso) => pointText(days ? iso.slice(0, 10) : iso, locale);
665
- const to = point(range.to);
666
- return fill(labels.withRange, { text, range: range.from === null ? fill(more.until, { to }) : range.from === range.to ? to : `${point(range.from)} \u2013 ${to}` });
667
- }
668
- function precisionText(iso, precision, locale) {
669
- if (precision === "year" || precision === "quarter" || precision === "month") {
670
- if (precision === "month") {
671
- return monthText(iso, locale);
672
- }
673
- const year = yearText(yearOf(iso), locale);
674
- return precision === "year" ? year : `Q${Math.floor((monthOf(iso) - 1) / 3) + 1} ${year}`;
675
- }
676
- return pointText(iso, locale);
677
- }
678
- var pointText = (iso, locale) => iso.includes("T") ? formatter("datetime", { locale })(Date.parse(`${iso}Z`)) : dayText(iso, locale);
679
- function wholeYears(from, to) {
680
- const day = /^(?:\d{4}|[+-]\d{6})-\d{2}-\d{2}$/;
681
- const whole = typeof from === "string" && typeof to === "string" && day.test(from) && day.test(to) && (from.endsWith("-01-01") || from === isoDay(-MAX_DATE_MS2)) && (to.endsWith("-12-31") || to === isoDay(MAX_DATE_MS2));
682
- return whole ? [yearOf(from), yearOf(to)] : null;
683
- }
684
- function compareText(f, labels, locale, { date, labelOf }) {
685
- const shown = (v) => typeof v === "string" ? precisionText(v, f.precision, locale) : labelOf?.(v) ?? (date ? String(v) : v.toLocaleString(locale, { maximumFractionDigits: 6 }));
686
- const forms = labels.compareShort;
687
- const op = ruleOp(f);
688
- if (op === "between" || op === "notBetween") {
689
- const order = (v) => typeof v === "string" ? dayMs(v) : v;
690
- const [from, to] = f.value2 !== void 0 && order(f.value2) < order(f.value) ? [f.value2, f.value] : [f.value, f.value2];
691
- const years = wholeYears(from, to)?.map((y) => yearText(y, locale));
692
- if (years) {
693
- return years[0] === years[1] ? fill(forms[op === "between" ? "=" : "!="], { value: years[0] }) : fill(forms[op], { from: years[0], to: years[1] });
694
- }
695
- return fill(forms[op], { from: shown(from), to: shown(to) });
696
- }
697
- return withNot(f, date && Object.hasOwn(forms, op) ? fill(forms[op], { value: shown(f.value) }) : `${Object.hasOwn(OP_SIGNS, op) ? OP_SIGNS[op] : op} ${shown(f.value)}`, labels);
698
- }
699
- function itemRuleText(f, labels, locale, { timeZone, date, labelOf, span, weekStart }) {
700
- if (f.type === "relative") {
701
- return withNot(f, relativeText(
702
- /** @type {any} */
703
- f,
704
- labels,
705
- locale,
706
- timeZone,
707
- void 0,
708
- span,
709
- weekStart
710
- ), labels);
711
- }
712
- if (f.type === "compare") {
713
- return compareText(
714
- /** @type {any} */
715
- f,
716
- labels,
717
- locale,
718
- { date, labelOf }
719
- );
720
- }
721
- const op = ruleOp(f);
722
- return withNot(f, `${Object.hasOwn(labels.labelOps, op) ? labels.labelOps[op] : op} ${fill(labels.quote, { text: f.value })}`, labels);
723
- }
724
- function groupingName(source, unit, labels, size) {
725
- const inName = labels.unitInName && Object.hasOwn(labels.unitInName, unit) ? labels.unitInName[unit] : labels.units[unit];
726
- return unit === "bin" ? fill(labels.binsName, { field: source, size }) : fill(labels.derivedName, { field: source, unit: inName ?? unit });
727
- }
728
- var quickZone = (type) => type === "number" ? "values" : "rows";
729
- function fieldAction(field, type, zones, labels) {
730
- const zone = quickZone(type);
731
- const kind = zones.includes(zone) ? null : zone !== "values" && zones.some((z) => z === "cols" || z === "filters") ? "move" : "add";
732
- const name2 = zones.length ? `${field}, ${fill(labels.inZone, { zone: zones.map((z) => labels.zones[z] ?? z).join(", ") })}` : field;
733
- const description = kind === null ? "" : fill(kind === "move" ? labels.moveTo : labels.addTo, { zone: labels.zones[zone] });
734
- return { zone, kind, name: name2, description };
735
- }
736
- var SUMMARY_ORDER = Object.freeze(["rows", "cols", "values", "filters"]);
737
- function layoutSummary(entries, labels) {
738
- return SUMMARY_ORDER.filter((zone) => entries[zone] && entries[zone].length).map((zone) => ({ zone, title: labels.zones[zone], fields: entries[zone].map((e) => e.text).join(", ") }));
739
- }
740
-
741
- // src/drill.js
742
- import { cellRows } from "pivotkit-core";
743
- var DRILL_LIMIT = 1e3;
744
- function decodeRow(encoded, i) {
745
- const row = {};
746
- for (const column of encoded.columns) {
747
- const code = column.codes[i];
748
- const v = code < 0 ? null : column.dict[code];
749
- const value = column.type === "date" && typeof v === "number" ? new Date(v).toISOString().replace(/(T00:00:00)?\.000Z$/, "").replace(/:00$/, "") : v;
750
- Object.defineProperty(row, column.name, { value, enumerable: true, writable: true, configurable: true });
751
- }
752
- return row;
753
- }
754
- function drillRows(result, { rowPath = [], colPath = [], data = null, limit = DRILL_LIMIT }) {
755
- const all = cellRows(result, { row: rowPath, col: colPath });
756
- const indices = all.slice(0, Math.max(0, limit));
757
- const rows = new Array(indices.length);
758
- for (let k = 0; k < indices.length; k++) {
759
- rows[k] = data ? data[indices[k]] : decodeRow(result.encoded, indices[k]);
760
- }
761
- return { count: all.length, rows, indices };
762
- }
763
-
764
- // src/date-context.js
765
- import { isDateMs } from "pivotkit-core";
766
- import { CATALOG, fieldLabel as fieldLabel2 } from "pivotkit-core";
767
- var formatters = /* @__PURE__ */ new Map();
768
- function dateFormatter(locale, options) {
769
- const key = JSON.stringify([locale, options]);
770
- let fmt = formatters.get(key);
771
- if (!fmt) {
772
- fmt = new Intl.DateTimeFormat(locale, options);
773
- if (formatters.size >= 32) {
774
- const oldest = formatters.keys().next().value;
775
- if (oldest !== void 0) formatters.delete(oldest);
776
- }
777
- formatters.set(key, fmt);
778
- }
779
- return fmt;
780
- }
781
- function dateDisplayLocale(locale) {
782
- try {
783
- dateFormatter(locale, { year: "numeric", timeZone: "UTC" });
784
- return locale;
785
- } catch {
786
- return "en-US";
787
- }
788
- }
789
- function dateRangeText(span, locale) {
790
- if (!span || !isDateMs(span.min) || !isDateMs(span.max)) return "";
791
- const fmt = dateFormatter(locale, { year: "numeric", month: "short", day: "numeric", timeZone: "UTC", era: new Date(span.min).getUTCFullYear() <= 0 ? "short" : void 0 });
792
- return `${fmt.format(span.min)} \u2013 ${fmt.format(span.max)}`;
793
- }
794
- var YEAR_CONTEXT_LIMIT = 32;
795
- var YEAR_IN_ITEMS = ["month", "quarter"];
796
- var yearCache = /* @__PURE__ */ new WeakMap();
797
- function yearsOf(result, field) {
798
- let cached = yearCache.get(result);
799
- if (!cached) yearCache.set(result, cached = /* @__PURE__ */ new Map());
800
- const previous = cached.get(field);
801
- if (previous) return previous.years;
802
- const column = result.encoded.column(field);
803
- let truncated = false;
804
- const spans = /* @__PURE__ */ new Map();
805
- const months = /* @__PURE__ */ new Map();
806
- if (column?.type === "date") {
807
- const date = /* @__PURE__ */ new Date(0);
808
- for (const row of result.rows) {
809
- const code = column.codes[row];
810
- const value = column.dict[code];
811
- if (isDateMs(value)) {
812
- date.setTime(value);
813
- const year = date.getUTCFullYear();
814
- const month = date.getUTCMonth() + 1;
815
- const monthSpan = months.get(month);
816
- if (monthSpan) {
817
- monthSpan.min = Math.min(monthSpan.min, value);
818
- monthSpan.max = Math.max(monthSpan.max, value);
819
- } else months.set(month, { min: value, max: value });
820
- const span = spans.get(year);
821
- if (span) {
822
- span.min = Math.min(span.min, value);
823
- span.max = Math.max(span.max, value);
824
- } else if (spans.size < YEAR_CONTEXT_LIMIT) spans.set(year, { min: value, max: value });
825
- else truncated = true;
826
- }
827
- }
828
- }
829
- const sorted = [...spans.keys()].sort((a, b) => a - b);
830
- cached.set(field, { years: sorted, spans, months, truncated });
831
- return sorted;
832
- }
833
- function yearSetText(years, locale = "en-US") {
834
- const truncated = years.length > YEAR_CONTEXT_LIMIT;
835
- years = years.slice(0, YEAR_CONTEXT_LIMIT);
836
- const runs = [];
837
- for (let i = 0; i < years.length; i++) {
838
- const first = years[i];
839
- while (i + 1 < years.length && years[i + 1] === years[i] + 1) i++;
840
- runs.push(first === years[i] ? yearText(first, locale) : `${yearText(first, locale)}\u2013${yearText(years[i], locale)}`);
841
- }
842
- return runs.join(", ") + (truncated ? ", \u2026" : "");
843
- }
844
- function observedYears(result, field) {
845
- const years = yearsOf(result, field);
846
- const truncated = yearCache.get(result)?.get(field)?.truncated ?? false;
847
- const suffix = truncated ? ", \u2026" : "";
848
- const fmt = dateFormatter(result.locale, { year: "numeric", timeZone: "UTC", era: years[0] <= 0 ? "short" : void 0 });
849
- if (["gregory", "iso8601"].includes(fmt.resolvedOptions().calendar)) return { text: yearSetText(years, result.locale) + suffix, combined: truncated || years.length > 1 };
850
- const spans = yearCache.get(result)?.get(field)?.spans;
851
- const parts = [];
852
- let combined = truncated || years.length > 1;
853
- for (const year of years) {
854
- const span = spans?.get(year);
855
- if (!span) continue;
856
- const first = fmt.format(span.min), last = fmt.format(span.max);
857
- combined ||= first !== last;
858
- const previous = parts[parts.length - 1];
859
- if (previous && previous.last === first) previous.last = last;
860
- else parts.push({ first, last });
861
- }
862
- return { text: parts.map(({ first, last }) => first === last ? first : `${first}\u2013${last}`).join(", ") + suffix, combined };
863
- }
864
- function dateContext(result, labels) {
865
- if (!result) return { result, labels, ranges: [], titles: /* @__PURE__ */ new Map() };
866
- const { view, encoded, locale } = result;
867
- const fields = { ...labels.core.fields };
868
- const single = /* @__PURE__ */ new Map();
869
- const titles = /* @__PURE__ */ new Map();
870
- const observedMonths = /* @__PURE__ */ new Map();
871
- const used = /* @__PURE__ */ new Set([...view.rows, ...view.cols, ...filterZoneFields(view)]);
872
- const combinedMonths = /* @__PURE__ */ new Set();
873
- for (const d of view.derived) {
874
- if (!used.has(d.name) || !CATALOG.cyclicUnits.includes(d.by)) continue;
875
- const years = yearsOf(result, d.field);
876
- const observed = observedYears(result, d.field);
877
- const titled = (words) => {
878
- const title = `${fieldLabel2(d.name, labels.core)} \xB7 ${fill(words, { years: observed.text })}`;
879
- titles.set(d.name, title);
880
- Object.defineProperty(fields, d.name, { value: title, enumerable: true, configurable: true, writable: true });
881
- };
882
- if (observed.combined) {
883
- if (d.by === "month") combinedMonths.add(d.name);
884
- titled(labels.dateYearsCombined);
885
- } else if (years.length === 1 && YEAR_IN_ITEMS.includes(d.by)) {
886
- single.set(d.name, observed.text);
887
- if (d.by === "month") {
888
- const months = yearCache.get(result)?.get(d.field)?.months;
889
- if (months) observedMonths.set(d.name, months);
890
- }
891
- } else if (years.length === 1) {
892
- titled(labels.dateYearOnly);
893
- }
894
- }
895
- const decorated = { ...result, label: (axis, node, core) => {
896
- const text = result.label(axis, node, core);
897
- const field = (axis === "rows" ? result.rowFields : result.colFields)[node.depth - 1];
898
- if (node.parent && typeof node.key === "number" && combinedMonths.has(field)) {
899
- return dateFormatter(locale, { calendar: "gregory", month: "short", timeZone: "UTC" }).format(Date.UTC(2e3, node.key - 1, 1));
900
- }
901
- const span = typeof node.key === "number" ? observedMonths.get(field)?.get(node.key) : void 0;
902
- if (node.parent && span) {
903
- const fmt = dateFormatter(locale, { month: "short", year: "numeric", timeZone: "UTC", era: new Date(span.min).getUTCFullYear() <= 0 ? "short" : void 0 });
904
- if (!["gregory", "iso8601"].includes(fmt.resolvedOptions().calendar)) {
905
- const first = fmt.format(span.min), last = fmt.format(span.max);
906
- return first === last ? first : `${first} \u2013 ${last}`;
907
- }
908
- }
909
- return node.parent && node.key !== null && single.has(field) ? `${text} ${single.get(field)}` : text;
910
- } };
911
- const active = [...new Set([...view.rows, ...view.cols, ...filterZoneFields(view)].map((f) => sourceOf(view, f)))];
912
- const ranges = active.flatMap((field) => {
913
- const text = dateRangeText(dateSpan(encoded, field), locale);
914
- return text ? [{ field, text }] : [];
915
- });
916
- return { result: decorated, labels: { ...labels, core: { ...labels.core, fields } }, ranges, titles };
917
- }
918
-
919
- // src/field-info.js
920
- import { fieldDefaultsFromSchema, isIdentifierName } from "pivotkit-core";
921
- var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
922
- var own = (o, k) => isObject(o) && Object.hasOwn(o, k) ? o[k] : void 0;
923
- var TYPES = Object.freeze(["string", "number", "date", "boolean"]);
924
- function fieldInfoOf(fieldDefaults) {
925
- const map = /* @__PURE__ */ new Map();
926
- if (!isObject(fieldDefaults)) {
927
- return map;
928
- }
929
- const properties = {};
930
- for (const name2 of Object.keys(
931
- /** @type {object} */
932
- fieldDefaults
933
- )) {
934
- const d = own(fieldDefaults, name2);
935
- const title = own(d, "label");
936
- const description = own(d, "description");
937
- const href = own(d, "href");
938
- if (title !== void 0 || description !== void 0 || href !== void 0) {
939
- Object.defineProperty(properties, name2, { value: { title, description, externalDocs: { url: href } }, enumerable: true });
940
- }
941
- }
942
- if (Object.keys(properties).length === 0) {
943
- return map;
944
- }
945
- const clean = fieldDefaultsFromSchema({ properties }).defaults;
946
- for (const name2 of Object.keys(clean)) {
947
- const { label, description, href } = clean[name2];
948
- const info = {};
949
- if (label) {
950
- info.label = label;
951
- }
952
- if (description) {
953
- info.description = description;
954
- if (href) {
955
- info.href = href;
956
- }
957
- }
958
- if (Object.keys(info).length) {
959
- map.set(name2.toLowerCase(), info);
960
- }
961
- }
962
- return map;
963
- }
964
- function displayNames(info, fieldNames = []) {
965
- const spelling = new Map(fieldNames.map((n) => [String(n).toLowerCase(), String(n)]));
966
- const uses = /* @__PURE__ */ new Map();
967
- for (const entry of info.values()) {
968
- if (entry.label) {
969
- const l = entry.label.toLowerCase();
970
- uses.set(l, (uses.get(l) ?? 0) + 1);
971
- }
972
- }
973
- const out = {};
974
- for (const [key, entry] of info) {
975
- if (!entry.label) {
976
- continue;
977
- }
978
- const l = entry.label.toLowerCase();
979
- const clash = uses.get(l) > 1 || spelling.has(l) && l !== key;
980
- const value = clash ? `${entry.label} (${spelling.get(key) ?? key})` : entry.label;
981
- Object.defineProperty(out, key, { value, enumerable: true });
982
- }
983
- return Object.keys(out).length ? out : null;
984
- }
985
- function typesOf(fieldDefaults) {
986
- if (!isObject(fieldDefaults)) {
987
- return null;
988
- }
989
- const out = {};
990
- for (const name2 of Object.keys(
991
- /** @type {object} */
992
- fieldDefaults
993
- )) {
994
- const type = own(own(fieldDefaults, name2), "type");
995
- if (typeof type === "string" && TYPES.includes(type)) {
996
- Object.defineProperty(out, name2, { value: type, enumerable: true });
997
- }
998
- }
999
- return Object.keys(out).length ? out : null;
1000
- }
1001
- function fieldMatches(field, query, info) {
1002
- if (!query) {
1003
- return true;
1004
- }
1005
- return [field, info?.label, info?.description].some((t) => typeof t === "string" && t.toLowerCase().includes(query));
1006
- }
1007
- function matchingFields(fields, query, info) {
1008
- const q = query.trim().toLowerCase();
1009
- return q ? fields.filter((f) => fieldMatches(f.name, q, info.get(f.name.toLowerCase()))) : fields;
1010
- }
1011
- var identifierColumns = /* @__PURE__ */ new WeakMap();
1012
- function isIdentifier(column) {
1013
- if (!column || column.type !== "number" || column.derived || !isIdentifierName(column.name)) {
1014
- return false;
1015
- }
1016
- const known = identifierColumns.get(column);
1017
- if (known !== void 0) {
1018
- return known;
1019
- }
1020
- let whole = true;
1021
- for (let i = 0; i < column.dict.length && whole; i++) {
1022
- whole = Number.isInteger(column.dict[i]);
1023
- }
1024
- identifierColumns.set(column, whole);
1025
- return whole;
1026
- }
1027
- function fieldDefaultsFor(fieldDefaults, field, column) {
1028
- const key = isObject(fieldDefaults) ? Object.keys(
1029
- /** @type {object} */
1030
- fieldDefaults
1031
- ).find((k) => k.toLowerCase() === String(field).toLowerCase()) : void 0;
1032
- const host = key === void 0 ? void 0 : own(fieldDefaults, key);
1033
- const set = ["agg", "format", "drillFormat"].some((k) => own(host, k) !== void 0);
1034
- if (set || !isIdentifier(column)) {
1035
- return isObject(host) ? host : void 0;
1036
- }
1037
- return { ...isObject(host) ? host : {}, agg: "count", drillFormat: "text" };
1038
- }
1039
-
1040
- // src/clear-input.jsx
1041
- import React, { useRef } from "react";
1042
- function emptyField(el) {
1043
- el.focus({ preventScroll: true });
1044
- let done;
1045
- try {
1046
- el.select();
1047
- const doc = (
1048
- /** @type {Document & { execCommand?: (cmd: string) => boolean }} */
1049
- el.ownerDocument
1050
- );
1051
- done = typeof doc.execCommand === "function" && doc.execCommand("delete") && el.value === "";
1052
- } catch {
1053
- done = false;
1054
- }
1055
- if (!done) {
1056
- const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
1057
- Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(el, "");
1058
- el.dispatchEvent(new Event("input", { bubbles: true }));
1059
- }
1060
- }
1061
- function ClearInput({ value, onChange, onClear, clearLabel, multiline = false, className, inputRef, ...rest }) {
1062
- const own2 = useRef(
1063
- /** @type {HTMLInputElement | HTMLTextAreaElement | null} */
1064
- null
1065
- );
1066
- const name2 = useFormName();
1067
- const ref = inputRef ?? own2;
1068
- const clear = () => {
1069
- if (ref.current) {
1070
- emptyField(ref.current);
1071
- }
1072
- onClear?.();
1073
- };
1074
- const onKeyDown = (e) => {
1075
- rest.onKeyDown?.(e);
1076
- if (e.key === "Escape" && value !== "" && !e.defaultPrevented) {
1077
- e.preventDefault();
1078
- e.stopPropagation();
1079
- clear();
1080
- }
1081
- };
1082
- const Tag = multiline ? "textarea" : "input";
1083
- return /* @__PURE__ */ React.createElement("span", { className: `pk-clear-input${multiline ? " pk-clear-multi" : ""}${className ? ` ${className}` : ""}` }, /* @__PURE__ */ React.createElement(Tag, { name: name2, ...rest, ref, value, onChange: (e) => onChange(e.target.value), onKeyDown }), value !== "" ? /* @__PURE__ */ React.createElement(
1084
- "button",
1085
- {
1086
- type: "button",
1087
- className: "pk-clear-x",
1088
- "aria-label": clearLabel,
1089
- title: clearLabel,
1090
- onPointerDown: (e) => e.preventDefault(),
1091
- onMouseDown: (e) => e.preventDefault(),
1092
- onClick: clear,
1093
- "data-testid": "clear-input"
1094
- },
1095
- /* @__PURE__ */ React.createElement(Icon, { name: "x", size: 14 })
1096
- ) : null);
1097
- }
1098
-
1099
- // src/info.jsx
1100
- import React2, { useCallback, useEffect, useId, useRef as useRef2, useState } from "react";
1101
- var LEAVE_DELAY = 250;
1102
- var WAY_TIME = 1500;
1103
- function FieldDescription({ info, labels, link = true, className = "pk-field-desc" }) {
1104
- return /* @__PURE__ */ React2.createElement("p", { className }, /* @__PURE__ */ React2.createElement("span", null, info.description), link && info.href ? /* @__PURE__ */ React2.createElement(React2.Fragment, null, " ", /* @__PURE__ */ React2.createElement("a", { href: info.href, target: "_blank", rel: "noopener noreferrer", className: "pk-learn-more" }, labels.learnMore)) : null);
1105
- }
1106
- function InfoButton({ info, name: name2, labels, className, testId = "field-info", label: named, tabIndex, slot }) {
1107
- const [mode, setMode] = useState(
1108
- /** @type {null | "peek" | "open"} */
1109
- null
1110
- );
1111
- const ref = useRef2(
1112
- /** @type {HTMLButtonElement | null} */
1113
- null
1114
- );
1115
- const quiet = useRef2(false);
1116
- const leaving = useRef2(
1117
- /** @type {ReturnType<typeof setTimeout> | null} */
1118
- null
1119
- );
1120
- const id = useId();
1121
- const textId = useId();
1122
- const pointer = useRef2(
1123
- /** @type {{ x: number, y: number } | null} */
1124
- null
1125
- );
1126
- const muted = useRef2(false);
1127
- const muteIfHovered = () => {
1128
- muted.current = Boolean(ref.current?.matches(":hover"));
1129
- };
1130
- const stay = () => {
1131
- if (leaving.current) {
1132
- clearTimeout(leaving.current);
1133
- leaving.current = null;
1134
- }
1135
- };
1136
- const hovered = (onItsWay) => {
1137
- const button = ref.current;
1138
- const root = (
1139
- /** @type {Document | ShadowRoot | null} */
1140
- button?.getRootNode() ?? null
1141
- );
1142
- const pop = root && "getElementById" in root ? root.getElementById(id) : null;
1143
- return Boolean(
1144
- button?.matches(":hover") || pop?.matches(":hover") || onItsWay && button && pop && onTheWay(button.getBoundingClientRect(), pop.getBoundingClientRect(), pointer.current)
1145
- );
1146
- };
1147
- const leaveSoon = () => {
1148
- stay();
1149
- const left = Date.now();
1150
- const check = () => {
1151
- if (hovered(Date.now() - left < WAY_TIME)) {
1152
- leaving.current = setTimeout(check, LEAVE_DELAY);
1153
- return;
1154
- }
1155
- leaving.current = null;
1156
- setMode((m) => m === "peek" ? null : m);
1157
- };
1158
- leaving.current = setTimeout(check, LEAVE_DELAY);
1159
- };
1160
- useEffect(() => stay, []);
1161
- useEffect(() => {
1162
- const doc = ref.current?.ownerDocument;
1163
- if (mode !== "peek" || !doc) {
1164
- return void 0;
1165
- }
1166
- const follow = (e) => {
1167
- pointer.current = { x: e.clientX, y: e.clientY };
1168
- };
1169
- const gone = (e) => {
1170
- if (!e.relatedTarget) {
1171
- pointer.current = null;
1172
- }
1173
- };
1174
- doc.addEventListener("pointermove", follow, { capture: true, passive: true });
1175
- doc.addEventListener("pointerout", gone, { capture: true, passive: true });
1176
- return () => {
1177
- doc.removeEventListener("pointermove", follow, { capture: true });
1178
- doc.removeEventListener("pointerout", gone, { capture: true });
1179
- pointer.current = null;
1180
- };
1181
- }, [mode]);
1182
- const close = useCallback(() => {
1183
- quiet.current = true;
1184
- muteIfHovered();
1185
- setMode(null);
1186
- requestAnimationFrame(() => {
1187
- quiet.current = false;
1188
- });
1189
- }, []);
1190
- const label = named ?? fill(labels.aboutField, { field: name2 });
1191
- return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(
1192
- "button",
1193
- {
1194
- ref,
1195
- type: "button",
1196
- className: `pk-info${className ? ` ${className}` : ""}`,
1197
- "aria-label": label,
1198
- "aria-describedby": textId,
1199
- "aria-expanded": mode === "open",
1200
- "aria-controls": mode ? id : void 0,
1201
- "aria-haspopup": "dialog",
1202
- tabIndex,
1203
- "data-pk-slot": slot,
1204
- "data-testid": testId,
1205
- onPointerMove: (e) => {
1206
- if (e.pointerType === "mouse" && !muted.current) {
1207
- stay();
1208
- setMode((m) => m ?? "peek");
1209
- }
1210
- },
1211
- onPointerLeave: (e) => {
1212
- muted.current = false;
1213
- if (e.pointerType === "mouse" && mode === "peek") {
1214
- leaveSoon();
1215
- }
1216
- },
1217
- onFocus: () => {
1218
- if (mode === null && !quiet.current) {
1219
- setMode("peek");
1220
- }
1221
- },
1222
- onBlur: (e) => {
1223
- const to = (
1224
- /** @type {Element | null} */
1225
- e.relatedTarget
1226
- );
1227
- if (mode === "peek" && !(to && to.closest?.(".pk-info-pop"))) {
1228
- setMode(null);
1229
- }
1230
- },
1231
- onClick: () => {
1232
- stay();
1233
- if (mode === "open") {
1234
- muteIfHovered();
1235
- }
1236
- setMode(mode === "open" ? null : "open");
1237
- }
1238
- },
1239
- /* @__PURE__ */ React2.createElement(Icon, { name: "info", size: 14 })
1240
- ), /* @__PURE__ */ React2.createElement("span", { id: textId, hidden: true }, info.description), /* @__PURE__ */ React2.createElement(
1241
- Popover,
1242
- {
1243
- key: mode ?? "closed",
1244
- open: mode !== null,
1245
- passive: mode === "peek",
1246
- anchor: ref,
1247
- onClose: close,
1248
- label,
1249
- role: mode === "peek" ? "tooltip" : "dialog",
1250
- className: "pk-info-pop",
1251
- id,
1252
- onPointerEnter: stay,
1253
- onPointerLeave: (e) => {
1254
- if (e.pointerType === "mouse" && mode === "peek") {
1255
- leaveSoon();
1256
- }
1257
- }
1258
- },
1259
- /* @__PURE__ */ React2.createElement(FieldDescription, { info, labels })
1260
- ));
1261
- }
1262
-
1263
- // src/help.js
1264
- import { createContext } from "react";
1265
- var HelpContext = createContext(
1266
- /** @type {Help} */
1267
- { explain: true, labels: null }
1268
- );
1269
-
1270
- // src/share.js
1271
- import { VIEW_FILE_LIMITS, fromViewFile, linkFragment, normalize, outsideLimits, withLinkFragment } from "pivotkit-core";
1272
- var linkModule = null;
1273
- var linkLoaded = null;
1274
- function loadLink() {
1275
- linkModule ??= import("pivotkit-core/link").then((m) => {
1276
- linkLoaded = m;
1277
- return m;
1278
- });
1279
- return linkModule;
1280
- }
1281
- var linkNow = () => linkLoaded;
1282
- var readLinkParam = (hash, key) => linkFragment(hash, key);
1283
- var withLinkParam = (url, key, encoded) => withLinkFragment(url, key, encoded);
1284
- function shareBase(shareLink, here) {
1285
- if (shareLink === true) {
1286
- if (!here) {
1287
- return null;
1288
- }
1289
- try {
1290
- const url = new URL(here);
1291
- return `${url.origin}${url.pathname}${url.hash}`;
1292
- } catch {
1293
- return null;
1294
- }
1295
- }
1296
- return typeof shareLink === "string" && shareLink.trim() ? shareLink.trim() : null;
1297
- }
1298
- var viewStorageName = (key) => `pivotkit:view:${key ?? ""}`;
1299
- function readStoredView(key, storage) {
1300
- if (!storage) {
1301
- return null;
1302
- }
1303
- try {
1304
- return storage.getItem(viewStorageName(key));
1305
- } catch {
1306
- return null;
1307
- }
1308
- }
1309
- function writeStoredView(key, storage, view) {
1310
- if (!storage) {
1311
- return;
1312
- }
1313
- try {
1314
- storage.setItem(viewStorageName(key), JSON.stringify(view));
1315
- } catch {
1316
- }
1317
- }
1318
- var VIEW_TEXT_MAX = VIEW_FILE_LIMITS.text;
1319
- var quoteNames = (names, labels) => {
1320
- const shown = names.slice(0, 5).map((n) => fill(labels.quote, { text: n.length > 60 ? `${n.slice(0, 59)}\u2026` : n })).join(", ");
1321
- return names.length > 5 ? `${shown} \u2026` : shown;
1322
- };
1323
- var FAILED = Object.freeze({ newerFormat: "newer", newerView: "newer" });
1324
- function viewFromText(text, encoded, options = {}) {
1325
- return viewFromObject(text, encoded, options);
1326
- }
1327
- function viewFromObject(input, encoded, options = {}) {
1328
- const file = fromViewFile(input, { data: encoded, sourceId: options.sourceId });
1329
- if (file.failed || !file.view) {
1330
- const failed = file.failed ?? "notView";
1331
- return { view: null, issues: file.issues, failed: Object.hasOwn(FAILED, failed) ? FAILED[failed] : failed, file };
1332
- }
1333
- const { view, issues } = normalize(file.view, encoded, { limits: outsideLimits(options.limits) });
1334
- if (issues.some((i) => i.path === "version")) {
1335
- return { view: null, issues, failed: "newer", file };
1336
- }
1337
- return { view, issues, failed: null, file };
1338
- }
1339
- function loadCheck(loaded2, labels, sources = []) {
1340
- const fit = loaded2.file?.compatible;
1341
- if (!loaded2.view || !fit || fit.ok) {
1342
- return null;
1343
- }
1344
- const lines2 = [];
1345
- const fileSource = loaded2.file?.source;
1346
- const target = fit.source === "other" && fileSource?.id ? sources.find((s) => s && s.id === fileSource.id) : void 0;
1347
- if (fit.source === "other") {
1348
- const name2 = target?.name || fileSource?.name || fileSource?.id;
1349
- lines2.push(name2 ? fill(labels.loadCheckSource, { source: name2 }) : labels.loadCheckOtherSource);
1350
- }
1351
- if (fit.missing.length) {
1352
- lines2.push(fill(labels.loadCheckMissing, { fields: quoteNames(fit.missing, labels) }));
1353
- }
1354
- if (fit.changed.length) {
1355
- lines2.push(fill(labels.loadCheckChanged, { fields: quoteNames(fit.changed.map((c) => c.name), labels) }));
1356
- }
1357
- return { lines: lines2, switchTo: target ? { id: target.id, name: target.name || target.id } : null };
1358
- }
1359
-
1360
- // src/storage.js
1361
- function localStore() {
1362
- try {
1363
- return typeof window !== "undefined" && window.localStorage ? window.localStorage : null;
1364
- } catch {
1365
- return null;
1366
- }
1367
- }
1368
- function readItem(name2, storage) {
1369
- try {
1370
- return storage ? storage.getItem(name2) : null;
1371
- } catch {
1372
- return null;
1373
- }
1374
- }
1375
- var listeners = /* @__PURE__ */ new Map();
1376
- function subscribeItem(name2, callback) {
1377
- const set = listeners.get(name2) ?? /* @__PURE__ */ new Set();
1378
- set.add(callback);
1379
- listeners.set(name2, set);
1380
- const onStorage = (e) => {
1381
- if (e.key === null || e.key === name2) {
1382
- callback();
1383
- }
1384
- };
1385
- const win = typeof window !== "undefined" ? window : null;
1386
- win?.addEventListener("storage", onStorage);
1387
- return () => {
1388
- set.delete(callback);
1389
- if (set.size === 0) {
1390
- listeners.delete(name2);
1391
- }
1392
- win?.removeEventListener("storage", onStorage);
1393
- };
1394
- }
1395
- function writeItem(name2, storage, text) {
1396
- let ok = false;
1397
- if (storage) {
1398
- try {
1399
- if (text === null) {
1400
- storage.removeItem(name2);
1401
- } else {
1402
- storage.setItem(name2, text);
1403
- }
1404
- ok = true;
1405
- } catch {
1406
- }
1407
- }
1408
- for (const callback of [...listeners.get(name2) ?? []]) {
1409
- callback();
1410
- }
1411
- return ok;
1412
- }
1413
-
1414
- // src/tips.js
1415
- import { CATALOG as CATALOG2, fieldLabel as fieldLabel3, suggestDateUnit } from "pivotkit-core";
1416
- var TIP_LIMIT = 1;
1417
- var TIP_THRESHOLDS = Object.freeze({
1418
- /** columns of an ungrouped date on Columns from which grouping it is suggested */
1419
- dateColumns: 12,
1420
- /** rows of an ungrouped date on Rows from which grouping it is suggested */
1421
- dateRows: 60,
1422
- /** columns from which swapping rows and columns is suggested (when there are fewer rows) */
1423
- manyColumns: 20,
1424
- /** changes of the view in this session after which saving it as a template is suggested */
1425
- changesBeforeSave: 5,
1426
- /** changes after the first drag during which the Undo and menu tip stays */
1427
- afterDragChanges: 3,
1428
- /** slices from which a pie or a donut suggests bars: a circle reads well up to about 7 parts */
1429
- pieSlices: 7
1430
- });
1431
- var PERCENT_SHOW_AS = Object.freeze(["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal", "percentOfParentRow", "percentOfParentColumn", "percentRunningTotal", "percentDifferenceFromPrevious"]);
1432
- var name = (ctx, field) => fieldLabel3(field, { fields: ctx.fields });
1433
- var derivedBy = (ctx, field) => ctx.view.derived.find((d) => d.name.toLowerCase() === String(field).toLowerCase())?.by ?? "";
1434
- var isRawDate = (ctx, field) => ctx.typeOf(field) === "date" && sourceOf(ctx.view, field).toLowerCase() === String(field).toLowerCase();
1435
- var table = (ctx) => !ctx.failed && !ctx.empty && ctx.view.display === "table";
1436
- var chart = (ctx) => !ctx.failed && ctx.view.display === "chart" && ctx.series !== null && ctx.view.values.length > 0;
1437
- var seriesOf = (ctx) => (
1438
- /** @type {NonNullable<TipContext["series"]>} */
1439
- ctx.series
1440
- );
1441
- var axisChart = (ctx) => chart(ctx) && CHART_TYPES[ctx.chartPlan.name].axis;
1442
- var lines = (ctx) => ["line", "area"].includes(ctx.chartPlan.name);
1443
- var sliceChart = (ctx) => chart(ctx) && SLICE_TYPES.includes(ctx.chartPlan.name);
1444
- var dateOn = (ctx, axis) => ctx.view[axis].some((f) => ctx.typeOf(f) === "date");
1445
- var datesAcross = (ctx) => axisChart(ctx) && !ctx.chartPlan.swap && lines(ctx) && dateOn(ctx, "cols") && !dateOn(ctx, "rows");
1446
- var TIPS = Object.freeze([
1447
- {
1448
- // a filter that leaves nothing: say so instead of an empty table
1449
- id: "filterEmpty",
1450
- kind: "notice",
1451
- icon: "filter",
1452
- action: "removeFilters",
1453
- when: (ctx) => !ctx.failed && !ctx.empty && ctx.dataRows > 0 && ctx.matched === 0 && ctx.view.filters.some((f) => isFiltered(ctx.view, f.field)) ? {} : null
1454
- },
1455
- {
1456
- // top N changes what totals mean
1457
- id: "top",
1458
- kind: "notice",
1459
- icon: "top",
1460
- when: (ctx) => {
1461
- if (ctx.failed || ctx.empty) {
1462
- return null;
1463
- }
1464
- for (const field of [...ctx.view.rows, ...ctx.view.cols]) {
1465
- const top = filtersOf(ctx.view, field, ["top"])[0];
1466
- if (top) {
1467
- return { field: name(ctx, field), count: top.count, bottom: Boolean(top.bottom) };
1468
- }
1469
- }
1470
- return null;
1471
- }
1472
- },
1473
- {
1474
- id: "chartCapped",
1475
- kind: "notice",
1476
- when: (ctx) => chart(ctx) && seriesOf(ctx).categoryCount > seriesOf(ctx).categories.length ? { shown: seriesOf(ctx).categories.length, total: seriesOf(ctx).categoryCount } : null
1477
- },
1478
- {
1479
- // "% of row total": what 100 % is
1480
- id: "showAs",
1481
- icon: "sigma",
1482
- when: (ctx) => {
1483
- if (ctx.failed || ctx.empty) {
1484
- return null;
1485
- }
1486
- const spec = ctx.view.values.find((v) => v.showAs && PERCENT_SHOW_AS.includes(v.showAs.type));
1487
- return spec ? { type: spec.showAs.type } : null;
1488
- }
1489
- },
1490
- {
1491
- // column subtotals with two or more fields in Columns: what a Total column next to the
1492
- // others adds up (people read "1 Critical Total" as one more status)
1493
- id: "colSubtotals",
1494
- icon: "sigma",
1495
- action: "colSubtotalsOff",
1496
- when: (ctx) => table(ctx) && ctx.view.values.length > 0 && ctx.view.totals.colSubtotals && ctx.view.cols.length >= 2 && ctx.colSubtotalShown ? {} : null
1497
- },
1498
- {
1499
- // a type the user chose for data over time: lines show it (automatic draws them)
1500
- id: "chartOverTime",
1501
- icon: "line",
1502
- action: "auto",
1503
- when: (ctx) => {
1504
- if (!chart(ctx) || ctx.chartPlan.auto || lines(ctx) || ctx.chartPlan.name === "heatmap") {
1505
- return null;
1506
- }
1507
- if (chartPlan({ ...ctx.view, chart: { ...ctx.view.chart, type: "auto" } }, ctx.encoded).name !== "line") {
1508
- return null;
1509
- }
1510
- const field = [...ctx.view.rows, ...ctx.view.cols].find((f) => ctx.typeOf(f) === "date" && !CATALOG2.cyclicUnits.includes(derivedBy(ctx, f)));
1511
- return field ? { field: name(ctx, field) } : null;
1512
- }
1513
- },
1514
- {
1515
- // a pie of many slices: the small ones cannot be told apart
1516
- id: "pieSlices",
1517
- icon: "chart",
1518
- action: "bars",
1519
- when: (ctx) => sliceChart(ctx) && seriesOf(ctx).categories.length > TIP_THRESHOLDS.pieSlices ? { count: seriesOf(ctx).categories.length, max: TIP_THRESHOLDS.pieSlices } : null
1520
- },
1521
- {
1522
- // a pie draws one slice per row: the columns are added up
1523
- id: "pieColumns",
1524
- icon: "info",
1525
- action: "bars",
1526
- when: (ctx) => sliceChart(ctx) && ctx.view.cols.length > 0 ? { fields: ctx.view.cols.map((f) => name(ctx, f)).join(", ") } : null
1527
- },
1528
- {
1529
- id: "chartDates",
1530
- action: "swap",
1531
- when: (ctx) => datesAcross(ctx) ? {} : null
1532
- },
1533
- {
1534
- // a line or an area over categories without an order (countries, teams) draws a trend
1535
- // between things that follow no line: bars fit better. Dates, number ranges and a custom
1536
- // order (seasons) are an order
1537
- id: "chartTrend",
1538
- icon: "chart",
1539
- action: "bars",
1540
- when: (ctx) => {
1541
- if (!axisChart(ctx) || ctx.chartPlan.auto || datesAcross(ctx) || !lines(ctx) || ctx.view.rows.length === 0) {
1542
- return null;
1543
- }
1544
- const field = ctx.view.rows[ctx.view.rows.length - 1];
1545
- const ordered = ["date", "number"].includes(ctx.typeOf(field)) || ctx.view.sort.some((s) => s.by === "custom" && String(s.field).toLowerCase() === String(field).toLowerCase());
1546
- return ordered ? null : {};
1547
- }
1548
- },
1549
- {
1550
- id: "chartSeries",
1551
- action: "swap",
1552
- // the dates tip says the same (swap) more precisely; lines over time drawn automatically
1553
- // would draw the same lines after a swap
1554
- when: (ctx) => axisChart(ctx) && !datesAcross(ctx) && !(ctx.chartPlan.auto && lines(ctx)) && seriesOf(ctx).series.length > MANY_SERIES ? { count: seriesOf(ctx).series.length } : null
1555
- },
1556
- {
1557
- // a text field in Values is counted: say so, and what a sum needs
1558
- id: "textValue",
1559
- icon: "sigma",
1560
- when: (ctx) => {
1561
- if (ctx.failed || ctx.empty) {
1562
- return null;
1563
- }
1564
- const spec = ctx.view.values.find((v) => v.field && !v.label && ["string", "boolean"].includes(ctx.typeOf(v.field)));
1565
- return spec ? { field: name(ctx, spec.field) } : null;
1566
- }
1567
- },
1568
- {
1569
- // a date without grouping makes a column per day (or per instant)
1570
- id: "dateUngrouped",
1571
- icon: "date",
1572
- action: "groupDate",
1573
- when: (ctx) => {
1574
- if (!table(ctx)) {
1575
- return null;
1576
- }
1577
- const onCols = ctx.colLeaves > TIP_THRESHOLDS.dateColumns ? ctx.view.cols.find((f) => isRawDate(ctx, f)) : void 0;
1578
- const field = onCols ?? (ctx.rowLeaves > TIP_THRESHOLDS.dateRows ? ctx.view.rows.find((f) => isRawDate(ctx, f)) : void 0);
1579
- if (!field) {
1580
- return null;
1581
- }
1582
- const column = ctx.encoded.column(field);
1583
- const suggested = suggestDateUnit(ctx.encoded, field);
1584
- const unit = !suggested || suggested === "day" && column?.dateOnly ? "yearMonth" : suggested;
1585
- return { field: name(ctx, field), source: field, unit };
1586
- }
1587
- },
1588
- {
1589
- id: "manyColumns",
1590
- icon: "swap",
1591
- action: "swap",
1592
- when: (ctx) => table(ctx) && ctx.view.cols.length > 0 && ctx.colLeaves > TIP_THRESHOLDS.manyColumns && ctx.rowLeaves < ctx.colLeaves ? { count: ctx.colLeaves } : null
1593
- },
1594
- {
1595
- // once after the first drag: Undo and the menus (before the next step: it goes after a few changes)
1596
- id: "afterDrag",
1597
- icon: "undo",
1598
- when: (ctx) => !ctx.failed && ctx.dragAt !== null && ctx.changes - ctx.dragAt <= TIP_THRESHOLDS.afterDragChanges ? {} : null
1599
- },
1600
- {
1601
- // rows without values show no numbers
1602
- id: "values",
1603
- icon: "sigma",
1604
- when: (ctx) => table(ctx) && ctx.view.values.length === 0 ? {} : null
1605
- },
1606
- {
1607
- id: "saveTemplate",
1608
- icon: "bookmark",
1609
- action: "saveTemplate",
1610
- // after a save it waits for as many changes again
1611
- when: (ctx) => ctx.canSave && !ctx.failed && !ctx.empty && ctx.changes - ctx.savedAt >= TIP_THRESHOLDS.changesBeforeSave ? {} : null
1612
- },
1613
- {
1614
- // the empty report: every field has a menu, and Undo is there
1615
- id: "menus",
1616
- icon: "sparkle",
1617
- when: (ctx) => !ctx.failed && ctx.empty && ctx.view.display === "table" && ctx.dragAt === null ? {} : null
1618
- },
1619
- {
1620
- id: "cells",
1621
- icon: "info",
1622
- when: (ctx) => table(ctx) && ctx.tableShown && ctx.view.values.length > 0 && !ctx.drilled ? {} : null
1623
- }
1624
- ]);
1625
- var TIP_IDS = Object.freeze(TIPS.filter((t) => t.kind !== "notice").map((t) => t.id));
1626
- var NOTICE_IDS = Object.freeze(TIPS.filter((t) => t.kind === "notice").map((t) => t.id));
1627
- var ALL_TIPS = "*";
1628
- var NO_EXPLANATIONS = "-explanations";
1629
- var FIELDS_COLLAPSED = "-fields";
1630
- var SWITCHES = Object.freeze([ALL_TIPS, NO_EXPLANATIONS, FIELDS_COLLAPSED]);
1631
- function fieldsCollapsed(session, forced, dismissed) {
1632
- return session ?? (forced === "collapsed" || forced === "open" ? forced === "collapsed" : dismissed.includes(FIELDS_COLLAPSED));
1633
- }
1634
- var keptOnReset = (id) => SWITCHES.includes(id);
1635
- function helpSwitch(forced, dismissed, off = NO_EXPLANATIONS) {
1636
- if (forced === "on" || forced === "off") {
1637
- return { on: forced === "on", user: false };
1638
- }
1639
- return { on: !dismissed.includes(off), user: true };
1640
- }
1641
- var SHORTCUTS = Object.freeze([
1642
- { keys: ["Mod", "Z"], text: "undo" },
1643
- { keys: ["Mod", "Shift", "Z"], text: "redo" },
1644
- { keys: ["Arrow keys"], text: "move" },
1645
- { keys: ["Enter"], text: "open" },
1646
- { keys: ["Space"], text: "drag" },
1647
- { keys: ["Escape"], text: "close" },
1648
- { keys: ["Arrow keys"], text: "fields" },
1649
- { keys: ["Shift", "F10"], text: "fieldMenu" }
1650
- ]);
1651
- function expandedGroup(nodes, depth, collapsed) {
1652
- const shut = new Set(collapsed.map((path) => JSON.stringify(path)));
1653
- const open = (path) => path.every((_, i) => !shut.has(JSON.stringify(path.slice(0, i + 1))));
1654
- return nodes.some((node) => node.depth > 0 && node.depth < depth && node.children.length > 1 && open(node.path));
1655
- }
1656
- function tipContext({ view, result, encoded, failed, empty, typeOf, fields, series = null, tableShown = false, drilled = false, changes = 0, dragAt = null, canSave = false, savedAt = 0, chartPlan: chartPlan2 = { name: "bar", auto: true, swap: false } }) {
1657
- const leaves = (nodes, depth) => result && depth > 0 ? nodes.reduce((n, node) => n + (node.depth === depth ? 1 : 0), 0) : 1;
1658
- return {
1659
- view,
1660
- empty,
1661
- failed: failed || !result,
1662
- typeOf,
1663
- encoded,
1664
- fields,
1665
- rowLeaves: result ? leaves(result.rowNodes, result.rowFields.length) : 0,
1666
- colLeaves: result ? leaves(result.colNodes, result.colFields.length) : 0,
1667
- colSubtotalShown: result ? expandedGroup(result.colNodes, result.colFields.length, view.collapsed?.cols ?? []) : false,
1668
- matched: result ? result.rows.length : 0,
1669
- dataRows: encoded.length,
1670
- series,
1671
- tableShown,
1672
- drilled,
1673
- changes,
1674
- dragAt,
1675
- canSave,
1676
- savedAt,
1677
- chartPlan: chartPlan2
1678
- };
1679
- }
1680
- function activeTips(ctx, { allowed, dismissed, limit = TIP_LIMIT }) {
1681
- const gone = new Set(dismissed);
1682
- const tipsOff = allowed === "off" || gone.has(ALL_TIPS);
1683
- const out = [];
1684
- let tips = 0;
1685
- for (const entry of TIPS) {
1686
- const notice = entry.kind === "notice";
1687
- if (!notice && (tipsOff || tips >= limit || Array.isArray(allowed) && !allowed.includes(entry.id) || gone.has(entry.id))) {
1688
- continue;
1689
- }
1690
- const params = entry.when(ctx);
1691
- if (params) {
1692
- out.push({ id: entry.id, params, entry });
1693
- tips += notice ? 0 : 1;
1694
- }
1695
- }
1696
- return out;
1697
- }
1698
- function tipText(id, params, labels, locale) {
1699
- const texts = labels.tips;
1700
- const values = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, typeof v === "number" ? v.toLocaleString(locale) : v]));
1701
- if (id === "showAs") {
1702
- const per = texts.showAs;
1703
- return Object.hasOwn(per, params.type) ? per[params.type] : "";
1704
- }
1705
- if (id === "top") {
1706
- return fill(params.bottom ? texts.bottom : texts.top, values);
1707
- }
1708
- if (id === "dateUngrouped") {
1709
- return fill(texts.dateUngrouped, { ...values, unit: labels.units[params.unit] ?? params.unit });
1710
- }
1711
- return Object.hasOwn(texts, id) && typeof texts[id] === "string" ? fill(texts[id], values) : "";
1712
- }
1713
- function tipActionText(entry, params, labels) {
1714
- if (!entry.action) {
1715
- return "";
1716
- }
1717
- const text = Object.hasOwn(labels.tipActions, entry.action) ? labels.tipActions[entry.action] : "";
1718
- return fill(text, { unit: labels.units[params.unit] ?? params.unit ?? "" });
1719
- }
1720
- function allowedTips(value) {
1721
- if (value === "off" || value === false) {
1722
- return "off";
1723
- }
1724
- const list = typeof value === "string" && value.trim() !== "on" && value.trim() !== "" ? value.split(",") : Array.isArray(value) ? value : null;
1725
- if (!list) {
1726
- return "on";
1727
- }
1728
- return list.map((id) => String(id).trim()).filter((id) => TIP_IDS.includes(id));
1729
- }
1730
- function cleanDismissed(value) {
1731
- return Array.isArray(value) ? [...new Set(value.filter((id) => typeof id === "string" && (SWITCHES.includes(id) || TIP_IDS.includes(id))))] : [];
1732
- }
1733
- var storageName = (key) => `pivotkit:tips:${key}`;
1734
- function readStored(key, storage) {
1735
- return key ? readItem(storageName(key), storage) : null;
1736
- }
1737
- function parseStored(raw) {
1738
- if (!raw) {
1739
- return [];
1740
- }
1741
- try {
1742
- return cleanDismissed(JSON.parse(raw));
1743
- } catch {
1744
- return [];
1745
- }
1746
- }
1747
- function subscribeStored(key, callback) {
1748
- return key ? subscribeItem(storageName(key), callback) : () => {
1749
- };
1750
- }
1751
- function writeDismissed(key, storage, dismissed) {
1752
- if (key && storage) {
1753
- writeItem(storageName(key), storage, dismissed.length ? JSON.stringify(dismissed) : null);
1754
- }
1755
- }
1756
- function withoutFilters(view) {
1757
- return { ...view, filters: filterZoneFields(view).map(emptyPick) };
1758
- }
1759
-
1760
- // src/lazy-import.js
1761
- var pending = null;
1762
- var loaded = null;
1763
- function loadImport() {
1764
- pending ??= import("../import-ui.js").then(
1765
- (m) => loaded = m,
1766
- (error) => {
1767
- pending = null;
1768
- throw error;
1769
- }
1770
- );
1771
- return pending;
1772
- }
1773
- var importNow = () => loaded;
1774
-
1775
- export {
1776
- CHART_TYPES,
1777
- SLICE_TYPES,
1778
- CHART_TYPE_NAMES,
1779
- chartTypeOf,
1780
- chartPlan,
1781
- MAX_CATEGORIES,
1782
- swapAxes,
1783
- ZONES,
1784
- clone,
1785
- RULE_OPS,
1786
- ruleOp,
1787
- hiddenNot,
1788
- opOf,
1789
- pickFilter,
1790
- emptyPick,
1791
- isEmptyPick,
1792
- same,
1793
- searchItems,
1794
- filterZoneFields,
1795
- axisOf,
1796
- zoneOverLimit,
1797
- zoneMax,
1798
- addField,
1799
- removeAt,
1800
- moveField,
1801
- reorder,
1802
- numberRange,
1803
- dateSpan,
1804
- groupField,
1805
- groupingOf,
1806
- sourceOf,
1807
- setSort,
1808
- withHostOrders,
1809
- sortOf,
1810
- sortEntry,
1811
- headerSortTarget,
1812
- headerSortState,
1813
- nextHeaderSort,
1814
- filtersOf,
1815
- selectedItems,
1816
- numericResult,
1817
- sameRef,
1818
- toggleCollapsed,
1819
- rowFolding,
1820
- setCollapsed,
1821
- setTotal,
1822
- setDisplay,
1823
- setChart,
1824
- setChartDisplay,
1825
- hiddenAfter,
1826
- isEmptyView,
1827
- valueLabels,
1828
- valueLabel,
1829
- refLabel,
1830
- sortText,
1831
- valueConditionText,
1832
- dayMs,
1833
- yearOf,
1834
- isoYear,
1835
- yearText,
1836
- dayText,
1837
- isoDay,
1838
- todayIn,
1839
- namedUntil,
1840
- plainRange,
1841
- periodText,
1842
- rangeShare,
1843
- relativeText,
1844
- wholeYears,
1845
- itemRuleText,
1846
- groupingName,
1847
- fieldAction,
1848
- layoutSummary,
1849
- DRILL_LIMIT,
1850
- decodeRow,
1851
- drillRows,
1852
- dateFormatter,
1853
- dateDisplayLocale,
1854
- dateRangeText,
1855
- dateContext,
1856
- fieldInfoOf,
1857
- displayNames,
1858
- typesOf,
1859
- matchingFields,
1860
- fieldDefaultsFor,
1861
- ClearInput,
1862
- InfoButton,
1863
- HelpContext,
1864
- loadLink,
1865
- linkNow,
1866
- readLinkParam,
1867
- withLinkParam,
1868
- shareBase,
1869
- readStoredView,
1870
- writeStoredView,
1871
- viewFromText,
1872
- viewFromObject,
1873
- loadCheck,
1874
- localStore,
1875
- readItem,
1876
- subscribeItem,
1877
- writeItem,
1878
- ALL_TIPS,
1879
- NO_EXPLANATIONS,
1880
- FIELDS_COLLAPSED,
1881
- fieldsCollapsed,
1882
- keptOnReset,
1883
- helpSwitch,
1884
- SHORTCUTS,
1885
- tipContext,
1886
- activeTips,
1887
- tipText,
1888
- tipActionText,
1889
- allowedTips,
1890
- cleanDismissed,
1891
- readStored,
1892
- parseStored,
1893
- subscribeStored,
1894
- writeDismissed,
1895
- withoutFilters,
1896
- loadImport,
1897
- importNow
1898
- };