pivotkit-react 0.0.0-stage → 0.2.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 (89) hide show
  1. package/CHANGELOG.md +442 -0
  2. package/LICENSE +21 -0
  3. package/README.md +77 -2
  4. package/dist/chunks/chunk-53ZMK4BH.js +177 -0
  5. package/dist/chunks/chunk-F6MVUAQD.js +741 -0
  6. package/dist/chunks/chunk-LQCWFJBS.js +310 -0
  7. package/dist/chunks/chunk-OYY4BKIL.js +93 -0
  8. package/dist/chunks/chunk-QBD4FOBB.js +254 -0
  9. package/dist/chunks/chunk-X7H7BAVT.js +1752 -0
  10. package/dist/chunks/unused-texts-YTNJCFFC.js +10 -0
  11. package/dist/chunks/unused-texts-de-SGOHV4N7.js +6 -0
  12. package/dist/echarts.js +347 -0
  13. package/dist/index.js +3482 -0
  14. package/dist/labels.js +21 -0
  15. package/dist/menu-texts-de.js +6 -0
  16. package/dist/menus.js +1681 -0
  17. package/dist/styles.css +2529 -0
  18. package/package.json +70 -4
  19. package/types/PivotReport.d.ts +20 -0
  20. package/types/all-labels.d.ts +5 -0
  21. package/types/chart-decorate.d.ts +16 -0
  22. package/types/chart-layout.d.ts +111 -0
  23. package/types/chart-options.d.ts +23 -0
  24. package/types/chart-summary.d.ts +12 -0
  25. package/types/chart-tooltip.d.ts +38 -0
  26. package/types/chart-types.d.ts +61 -0
  27. package/types/chart.d.ts +39 -0
  28. package/types/chip-menus.d.ts +32 -0
  29. package/types/clear-input.d.ts +20 -0
  30. package/types/dnd-moves.d.ts +45 -0
  31. package/types/dnd.d.ts +101 -0
  32. package/types/dom.d.ts +52 -0
  33. package/types/drill-export.d.ts +42 -0
  34. package/types/drill-panel.d.ts +22 -0
  35. package/types/drill-table.d.ts +71 -0
  36. package/types/drill.d.ts +26 -0
  37. package/types/echarts.d.ts +4 -0
  38. package/types/export-run.d.ts +59 -0
  39. package/types/field-info.d.ts +34 -0
  40. package/types/fields.d.ts +32 -0
  41. package/types/files.d.ts +27 -0
  42. package/types/filter.d.ts +21 -0
  43. package/types/help.d.ts +21 -0
  44. package/types/icons.d.ts +80 -0
  45. package/types/index.d.ts +536 -0
  46. package/types/info.d.ts +34 -0
  47. package/types/iso.d.ts +2 -0
  48. package/types/labels.d.ts +663 -0
  49. package/types/lazy-menus.d.ts +28 -0
  50. package/types/menu-labels-de.d.ts +2 -0
  51. package/types/menu-labels.d.ts +317 -0
  52. package/types/menu-ops.d.ts +145 -0
  53. package/types/menu-texts.d.ts +2 -0
  54. package/types/menus.d.ts +7 -0
  55. package/types/names.d.ts +80 -0
  56. package/types/numbers.d.ts +13 -0
  57. package/types/overflow.d.ts +62 -0
  58. package/types/place.d.ts +43 -0
  59. package/types/popover.d.ts +93 -0
  60. package/types/rove.d.ts +20 -0
  61. package/types/section.d.ts +25 -0
  62. package/types/sections.d.ts +2 -0
  63. package/types/share-actions.d.ts +99 -0
  64. package/types/share.d.ts +114 -0
  65. package/types/skeleton.d.ts +9 -0
  66. package/types/storage.d.ts +24 -0
  67. package/types/table.d.ts +29 -0
  68. package/types/templates.d.ts +46 -0
  69. package/types/theme.d.ts +24 -0
  70. package/types/tip-list.d.ts +20 -0
  71. package/types/tips.d.ts +300 -0
  72. package/types/toasts.d.ts +26 -0
  73. package/types/toolbar-panels.d.ts +93 -0
  74. package/types/toolbar.d.ts +5 -0
  75. package/types/unused-load.d.ts +23 -0
  76. package/types/unused-texts-de.d.ts +2 -0
  77. package/types/unused-texts.d.ts +130 -0
  78. package/types/unused.d.ts +22 -0
  79. package/types/use-big-result.d.ts +29 -0
  80. package/types/use-export.d.ts +7 -0
  81. package/types/use-theme.d.ts +11 -0
  82. package/types/use-view-history.d.ts +37 -0
  83. package/types/version.d.ts +2 -0
  84. package/types/view-history.d.ts +106 -0
  85. package/types/view-ops.d.ts +293 -0
  86. package/types/view-save.d.ts +76 -0
  87. package/types/view-store.d.ts +59 -0
  88. package/types/virtual.d.ts +44 -0
  89. package/types/zones.d.ts +42 -0
@@ -0,0 +1,1752 @@
1
+ import {
2
+ fill
3
+ } from "./chunk-F6MVUAQD.js";
4
+
5
+ // src/chart-types.js
6
+ import { autoChartType } from "pivotkit-core";
7
+ var CHART_TYPES = Object.freeze({
8
+ auto: { chart: { type: "auto", stacked: false, horizontal: false }, icon: "sparkle", axis: true },
9
+ bar: { chart: { type: "bar", stacked: false, horizontal: false }, icon: "chart", axis: true },
10
+ stacked: { chart: { type: "bar", stacked: true, horizontal: false }, icon: "stacked", axis: true },
11
+ horizontal: { chart: { type: "bar", stacked: false, horizontal: true }, icon: "horizontal", axis: true },
12
+ line: { chart: { type: "line", stacked: false, horizontal: false }, icon: "line", axis: true },
13
+ area: { chart: { type: "area", stacked: false, horizontal: false }, icon: "area", axis: true },
14
+ pie: { chart: { type: "pie", stacked: false, horizontal: false }, icon: "pie", axis: false },
15
+ donut: { chart: { type: "donut", stacked: false, horizontal: false }, icon: "donut", axis: false },
16
+ heatmap: { chart: { type: "heatmap", stacked: false, horizontal: false }, icon: "heatmap", axis: false }
17
+ });
18
+ var SLICE_TYPES = Object.freeze(["pie", "donut"]);
19
+ var CHART_TYPE_NAMES = Object.freeze(Object.keys(CHART_TYPES));
20
+ function chartTypeOf(chart2) {
21
+ const found = CHART_TYPE_NAMES.find((name2) => {
22
+ const c = CHART_TYPES[name2].chart;
23
+ return c.type === chart2.type && c.stacked === Boolean(chart2.stacked) && c.horizontal === Boolean(chart2.horizontal);
24
+ });
25
+ if (found) {
26
+ return found;
27
+ }
28
+ if (chart2.type === "bar") {
29
+ return chart2.horizontal ? "horizontal" : "stacked";
30
+ }
31
+ return CHART_TYPE_NAMES.find((name2) => CHART_TYPES[name2].chart.type === chart2.type) ?? "bar";
32
+ }
33
+ function chartPlan(view, encoded) {
34
+ if (view.chart.type !== "auto") {
35
+ const name3 = chartTypeOf(view.chart);
36
+ return { name: name3, auto: false, swap: false, chart: { type: view.chart.type, stacked: Boolean(view.chart.stacked), horizontal: Boolean(view.chart.horizontal) } };
37
+ }
38
+ const own = autoChartType(
39
+ /** @type {any} */
40
+ view,
41
+ encoded
42
+ );
43
+ const swap = own === "bar" && view.cols.length > 0 && autoChartType(
44
+ /** @type {any} */
45
+ { ...view, rows: view.cols },
46
+ encoded
47
+ ) === "line";
48
+ const name2 = own === "line" || swap ? "line" : "bar";
49
+ return { name: name2, auto: true, swap, chart: { ...CHART_TYPES[name2].chart } };
50
+ }
51
+ var MANY_SERIES = 8;
52
+ var MAX_CATEGORIES = 50;
53
+
54
+ // src/names.js
55
+ import { fieldLabel } from "pivotkit-core";
56
+ function valueLabel(spec, labels) {
57
+ if (spec.label) {
58
+ return spec.label;
59
+ }
60
+ const core = labels.core;
61
+ let base;
62
+ if (!spec.field) {
63
+ base = core.countRows;
64
+ } else {
65
+ const agg = Object.hasOwn(core.aggregators, spec.agg) ? core.aggregators[spec.agg] : spec.agg;
66
+ base = fill(core.valueName, { agg, field: fieldLabel(spec.field, core) });
67
+ }
68
+ if (!spec.showAs || !core.showAs || !core.showAsName) {
69
+ return base;
70
+ }
71
+ const showAs = Object.hasOwn(core.showAs, spec.showAs.type) ? core.showAs[spec.showAs.type] : spec.showAs.type;
72
+ return fill(core.showAsName, { showAs, value: spec.field && spec.agg === "sum" ? fieldLabel(spec.field, core) : base });
73
+ }
74
+ function refLabel(view, ref, labels) {
75
+ if (!ref) {
76
+ return labels.core.countRows;
77
+ }
78
+ const sameField = (v) => ref.field === null || v.field === null || v.field === void 0 ? (v.field ?? null) === ref.field : v.field.toLowerCase() === ref.field.toLowerCase();
79
+ const spec = (view.values ?? []).find((v) => v.agg === ref.agg && sameField(v));
80
+ return valueLabel({ ...spec ?? ref, showAs: null }, labels);
81
+ }
82
+ function sortText(view, sort, labels) {
83
+ const desc = sort.order === "desc";
84
+ if (sort.by === "value") {
85
+ return fill(desc ? labels.sortValueDesc : labels.sortValueAsc, { value: refLabel(view, sort.value, labels) });
86
+ }
87
+ if (sort.by === "custom") {
88
+ return desc ? labels.sortCustomDesc : labels.sortCustom;
89
+ }
90
+ return desc ? labels.sortLabelDesc : labels.sortLabelAsc;
91
+ }
92
+ var OP_SIGNS = Object.freeze({ "=": "=", "!=": "\u2260", ">": ">", ">=": "\u2265", "<": "<", "<=": "\u2264" });
93
+ function valueConditionText(view, f, labels, locale) {
94
+ const number = (x) => typeof x === "number" ? x.toLocaleString(locale, { maximumFractionDigits: 6 }) : "";
95
+ const value = refLabel(view, f.by ?? (view.values?.[0] ? { field: view.values[0].field ?? null, agg: view.values[0].agg } : null), labels);
96
+ if (f.op === "between" || f.op === "notBetween") {
97
+ const [from, to] = typeof f.value2 === "number" && f.value2 < f.value ? [f.value2, f.value] : [f.value, f.value2];
98
+ return fill(labels.valueConditions[f.op], { value, from: number(from), to: number(to) });
99
+ }
100
+ return fill(labels.valueConditions.compare, { value, op: Object.hasOwn(OP_SIGNS, f.op) ? OP_SIGNS[f.op] : f.op, number: number(f.value) });
101
+ }
102
+ function groupingName(source, unit, labels, size) {
103
+ const inName = labels.unitInName && Object.hasOwn(labels.unitInName, unit) ? labels.unitInName[unit] : labels.units[unit];
104
+ return unit === "bin" ? fill(labels.binsName, { field: source, size }) : fill(labels.derivedName, { field: source, unit: inName ?? unit });
105
+ }
106
+ var quickZone = (type) => type === "number" ? "values" : "rows";
107
+ function fieldAction(field, type, zones, labels) {
108
+ const zone = quickZone(type);
109
+ const kind = zones.includes(zone) ? null : zone !== "values" && zones.some((z) => z === "cols" || z === "filters") ? "move" : "add";
110
+ const name2 = zones.length ? `${field}, ${fill(labels.inZone, { zone: zones.map((z) => labels.zones[z] ?? z).join(", ") })}` : field;
111
+ const description = kind === null ? "" : fill(kind === "move" ? labels.moveTo : labels.addTo, { zone: labels.zones[zone] });
112
+ return { zone, kind, name: name2, description };
113
+ }
114
+ var SUMMARY_ORDER = Object.freeze(["rows", "cols", "values", "filters"]);
115
+ function layoutSummary(entries2, labels) {
116
+ return SUMMARY_ORDER.filter((zone) => entries2[zone] && entries2[zone].length).map((zone) => ({ zone, title: labels.zones[zone], fields: entries2[zone].map((e) => e.text).join(", ") }));
117
+ }
118
+
119
+ // src/drill.js
120
+ import { cellRows } from "pivotkit-core";
121
+ var DRILL_LIMIT = 1e3;
122
+ function decodeRow(encoded, i) {
123
+ const row = {};
124
+ for (const column of encoded.columns) {
125
+ const code = column.codes[i];
126
+ const v = code < 0 ? null : column.dict[code];
127
+ const value = column.type === "date" && typeof v === "number" ? new Date(v).toISOString().replace(/(T00:00:00)?\.000Z$/, "").replace(/:00$/, "") : v;
128
+ Object.defineProperty(row, column.name, { value, enumerable: true, writable: true, configurable: true });
129
+ }
130
+ return row;
131
+ }
132
+ function drillRows(result, { rowPath = [], colPath = [], data = null, limit = DRILL_LIMIT }) {
133
+ const all = cellRows(result, { row: rowPath, col: colPath });
134
+ const indices = all.slice(0, Math.max(0, limit));
135
+ const rows = new Array(indices.length);
136
+ for (let k = 0; k < indices.length; k++) {
137
+ rows[k] = data ? data[indices[k]] : decodeRow(result.encoded, indices[k]);
138
+ }
139
+ return { count: all.length, rows, indices };
140
+ }
141
+
142
+ // src/icons.jsx
143
+ import React from "react";
144
+ var PATHS = {
145
+ grip: "M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01",
146
+ text: "M4 18 8.5 6h1L14 18M5.6 14h6.8M17 11.5c.6-.7 1.4-1 2.3-1 1.5 0 2.2.9 2.2 2.3V18m0-3.4c-.8-.4-1.6-.5-2.5-.5-1.4 0-2.3.7-2.3 1.9 0 1.1.8 1.8 2 1.8 1.2 0 2.1-.6 2.8-1.6",
147
+ number: "M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",
148
+ date: "M7 3v3M17 3v3M4 8h16M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1ZM8 12h2M14 12h2M8 16h2M14 16h2",
149
+ boolean: "M8 7h8a5 5 0 0 1 0 10H8A5 5 0 0 1 8 7ZM16 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",
150
+ search: "M11 18a7 7 0 1 0 0-14 7 7 0 0 0 0 14ZM20 20l-4-4",
151
+ x: "M6 6l12 12M18 6 6 18",
152
+ chevronDown: "m6 9 6 6 6-6",
153
+ chevronRight: "m9 6 6 6-6 6",
154
+ arrowUp: "M12 19V5M6 11l6-6 6 6",
155
+ arrowDown: "M12 5v14M6 13l6 6 6-6",
156
+ undo: "M9 14 4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11",
157
+ redo: "m15 14 5-5-5-5M20 9H9.5a5.5 5.5 0 0 0 0 11H13",
158
+ reset: "M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5",
159
+ table: "M4 5h16v14H4zM4 10h16M4 15h16M10 5v14",
160
+ chart: "M4 20h16M7 16v-5M12 16V6M17 16v-8",
161
+ stacked: "M4 20h16M7 16v-3M7 13v-3M12 16v-4M12 12V6M17 16v-2M17 14V9",
162
+ horizontal: "M4 4v16M8 7h7M8 12h11M8 17h5",
163
+ line: "M4 18 9 12l4 3 7-9M4 20h16",
164
+ area: "M4 18 9 11l4 3 7-8v14H4Z",
165
+ pie: "M12 3a9 9 0 1 0 9 9h-9Z M15 3.5A9 9 0 0 1 20.5 9H15Z",
166
+ donut: "M12 3a9 9 0 1 0 9 9h-4a5 5 0 1 1-5-5Z M14.5 3.4A9 9 0 0 1 20.6 9.5h-4.1a5 5 0 0 0-2-2Z",
167
+ heatmap: "M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z",
168
+ download: "M12 4v11M7 10l5 5 5-5M5 20h14",
169
+ bookmark: "M7 4h10a1 1 0 0 1 1 1v15l-6-4-6 4V5a1 1 0 0 1 1-1Z",
170
+ sliders: "M4 7h10M18 7h2M4 17h4M12 17h8M16 5v4M10 15v4",
171
+ filter: "M4 5h16l-6 7.5V19l-4-2v-4.5Z",
172
+ more: "M12 6h.01M12 12h.01M12 18h.01",
173
+ plus: "M12 5v14M5 12h14",
174
+ check: "m5 12 5 5 9-10",
175
+ sortAsc: "M7 4v16M3 8l4-4 4 4M14 6h7M14 12h5M14 18h3",
176
+ sortDesc: "M7 4v16M3 16l4 4 4-4M14 6h3M14 12h5M14 18h7",
177
+ panel: "M4 5h16v14H4zM9 5v14",
178
+ layout: "M4 5h7v6H4zM13 5h7v6h-7zM4 13h7v6H4zM13 13h7v6h-7z",
179
+ trash: "M5 7h14M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3",
180
+ save: "M5 4h11l3 3v13H5zM8 4v5h7V4M8 20v-6h8v6",
181
+ sparkle: "M12 4l1.8 4.6L18 10l-4.2 1.4L12 16l-1.8-4.6L6 10l4.2-1.4Z",
182
+ rows: "M4 6h16M4 12h16M4 18h16",
183
+ cols: "M6 4v16M12 4v16M18 4v16",
184
+ sigma: "M18 5H6l6 7-6 7h12",
185
+ info: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM12 11v5M12 8h.01",
186
+ warn: "M12 4 2.8 20h18.4ZM12 10v4.5M12 17.5h.01",
187
+ image: "M4 5h16v14H4zM4 16l5-5 4 4 3-3 4 4M15 9h.01",
188
+ file: "M6 3h8l4 4v14H6zM14 3v4h4",
189
+ newFile: "M6 3h8l4 4v14H6zM14 3v4h4M12 11v6M9 14h6",
190
+ swap: "M7 4 3 8l4 4M3 8h14M17 20l4-4-4-4M21 16H7",
191
+ top: "M4 20v-6h5v6M9 20V8h6v12M15 20v-9h5v9M3 20h18",
192
+ link: "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",
193
+ copy: "M8 8h11v12H8zM5 16V4h11",
194
+ upload: "M12 16V5M7 10l5-5 5 5M5 20h14",
195
+ drag: "M12 3v18M3 12h18M12 3l-3 3M12 3l3 3M12 21l-3-3M12 21l3-3M3 12l3-3M3 12l3 3M21 12l-3-3M21 12l-3 3",
196
+ enlarge: "M14 4h6v6M10 20H4v-6M20 4l-7 7M4 20l7-7",
197
+ fullScreen: "M3 8V3h5M21 8V3h-5M3 16v5h5M21 16v5h-5"
198
+ };
199
+ function Icon({ name: name2, size = 16, className }) {
200
+ return /* @__PURE__ */ React.createElement("svg", { className: className ? `pk-icon ${className}` : "pk-icon", width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false" }, /* @__PURE__ */ React.createElement("path", { d: PATHS[name2] ?? PATHS.info }));
201
+ }
202
+ var TYPE_ICON = { string: "text", number: "number", date: "date", boolean: "boolean", null: "text" };
203
+ var ZONE_ICON = { rows: "rows", cols: "cols", values: "sigma", filters: "filter" };
204
+
205
+ // src/clear-input.jsx
206
+ import React2, { useRef } from "react";
207
+ function emptyField(el) {
208
+ el.focus({ preventScroll: true });
209
+ let done;
210
+ try {
211
+ el.select();
212
+ const doc = (
213
+ /** @type {Document & { execCommand?: (cmd: string) => boolean }} */
214
+ el.ownerDocument
215
+ );
216
+ done = typeof doc.execCommand === "function" && doc.execCommand("delete") && el.value === "";
217
+ } catch {
218
+ done = false;
219
+ }
220
+ if (!done) {
221
+ const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
222
+ Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(el, "");
223
+ el.dispatchEvent(new Event("input", { bubbles: true }));
224
+ }
225
+ }
226
+ function ClearInput({ value, onChange, onClear, clearLabel, multiline = false, className, inputRef, ...rest }) {
227
+ const own = useRef(
228
+ /** @type {HTMLInputElement | HTMLTextAreaElement | null} */
229
+ null
230
+ );
231
+ const ref = inputRef ?? own;
232
+ const clear = () => {
233
+ if (ref.current) {
234
+ emptyField(ref.current);
235
+ }
236
+ onClear?.();
237
+ };
238
+ const onKeyDown = (e) => {
239
+ rest.onKeyDown?.(e);
240
+ if (e.key === "Escape" && value !== "" && !e.defaultPrevented) {
241
+ e.preventDefault();
242
+ e.stopPropagation();
243
+ clear();
244
+ }
245
+ };
246
+ const Tag = multiline ? "textarea" : "input";
247
+ return /* @__PURE__ */ React2.createElement("span", { className: `pk-clear-input${multiline ? " pk-clear-multi" : ""}${className ? ` ${className}` : ""}` }, /* @__PURE__ */ React2.createElement(Tag, { ...rest, ref, value, onChange: (e) => onChange(e.target.value), onKeyDown }), value !== "" ? /* @__PURE__ */ React2.createElement(
248
+ "button",
249
+ {
250
+ type: "button",
251
+ className: "pk-clear-x",
252
+ "aria-label": clearLabel,
253
+ title: clearLabel,
254
+ onPointerDown: (e) => e.preventDefault(),
255
+ onMouseDown: (e) => e.preventDefault(),
256
+ onClick: clear,
257
+ "data-testid": "clear-input"
258
+ },
259
+ /* @__PURE__ */ React2.createElement(Icon, { name: "x", size: 14 })
260
+ ) : null);
261
+ }
262
+
263
+ // src/dom.js
264
+ import { useEffect, useRef as useRef2 } from "react";
265
+ var FOCUSABLE = "button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex='-1'])";
266
+ function rootOf(node) {
267
+ const root = node && typeof node.getRootNode === "function" ? node.getRootNode() : null;
268
+ if (root && (root.nodeType === 9 || root.nodeType === 11)) {
269
+ return (
270
+ /** @type {Document | ShadowRoot} */
271
+ root
272
+ );
273
+ }
274
+ return typeof document !== "undefined" ? document : null;
275
+ }
276
+ function activeIn(node) {
277
+ return rootOf(node)?.activeElement ?? null;
278
+ }
279
+ function eventWithin(event, elements) {
280
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [];
281
+ return elements.some((el) => el && (path.includes(el) || event.target instanceof Node && el.contains(event.target)));
282
+ }
283
+ function tabbables(container) {
284
+ return (
285
+ /** @type {HTMLElement[]} */
286
+ [...container.querySelectorAll(FOCUSABLE)].filter((el) => !el.closest("[inert]") && el.getClientRects().length > 0)
287
+ );
288
+ }
289
+ function trapTab(event, container) {
290
+ if (event.key !== "Tab" || !container) {
291
+ return;
292
+ }
293
+ const list = tabbables(container);
294
+ if (list.length === 0) {
295
+ event.preventDefault();
296
+ return;
297
+ }
298
+ const first = list[0];
299
+ const last = list[list.length - 1];
300
+ const active = activeIn(container);
301
+ if (event.shiftKey && (active === first || !container.contains(active))) {
302
+ event.preventDefault();
303
+ last.focus();
304
+ } else if (!event.shiftKey && (active === last || !container.contains(active))) {
305
+ event.preventDefault();
306
+ first.focus();
307
+ }
308
+ }
309
+ var layers = [];
310
+ function useEscapeLayer(open, onClose) {
311
+ const close = useRef2(onClose);
312
+ useEffect(() => {
313
+ close.current = onClose;
314
+ });
315
+ useEffect(() => {
316
+ if (!open || typeof document === "undefined") {
317
+ return void 0;
318
+ }
319
+ const token = {};
320
+ layers.push(token);
321
+ const onKey = (e) => {
322
+ if (e.key === "Escape" && layers[layers.length - 1] === token && !e.defaultPrevented) {
323
+ e.preventDefault();
324
+ close.current();
325
+ }
326
+ };
327
+ document.addEventListener("keydown", onKey);
328
+ return () => {
329
+ document.removeEventListener("keydown", onKey);
330
+ layers.splice(layers.indexOf(token), 1);
331
+ };
332
+ }, [open]);
333
+ }
334
+ function useModal(ref, open, onClose, opener) {
335
+ useEscapeLayer(open, onClose);
336
+ useEffect(() => {
337
+ const el = ref.current;
338
+ if (!open || !el) {
339
+ return void 0;
340
+ }
341
+ const was = activeIn(el);
342
+ const plain = !was || was === el.ownerDocument.body || was.classList.contains("pk-root");
343
+ const back = plain && opener ? el.closest(".pk-root")?.querySelector(opener) ?? was : was;
344
+ const t = requestAnimationFrame(() => {
345
+ const first = (
346
+ /** @type {HTMLElement | null} */
347
+ el.querySelector("[data-autofocus]") ?? tabbables(el)[0] ?? el
348
+ );
349
+ first.focus({ preventScroll: true });
350
+ });
351
+ return () => {
352
+ cancelAnimationFrame(t);
353
+ const target = (
354
+ /** @type {HTMLElement | null} */
355
+ back
356
+ );
357
+ const now = activeIn(el);
358
+ if (target && target.isConnected && (!now || el.contains(now) || now === el.ownerDocument.body)) {
359
+ target.focus({ preventScroll: true });
360
+ }
361
+ };
362
+ }, [ref, open, opener]);
363
+ return { onKeyDown: (e) => trapTab(e, ref.current) };
364
+ }
365
+
366
+ // src/iso.js
367
+ import { useEffect as useEffect2, useLayoutEffect } from "react";
368
+ var useIsoLayoutEffect = typeof window !== "undefined" && typeof document !== "undefined" ? useLayoutEffect : useEffect2;
369
+
370
+ // src/popover.jsx
371
+ import React3, { createContext, useCallback, useContext, useEffect as useEffect3, useId, useRef as useRef3, useState } from "react";
372
+ import { createPortal } from "react-dom";
373
+
374
+ // src/place.js
375
+ var MARGIN = 8;
376
+ var GAP = 6;
377
+ function placePopover(anchor, size, viewport, align = "start", { fill: fill2 = false } = {}) {
378
+ const below = viewport.height - anchor.bottom - GAP - MARGIN;
379
+ const above = anchor.top - GAP - MARGIN;
380
+ const wanted = align === "end" ? anchor.right - size.width : anchor.left;
381
+ const left = Math.max(MARGIN, Math.min(wanted, viewport.width - size.width - MARGIN));
382
+ const most = Math.max(0, viewport.height - 2 * MARGIN);
383
+ if (fill2 && size.height > below && size.height > above) {
384
+ const height2 = Math.min(size.height, most);
385
+ const side2 = below >= above ? "below" : "above";
386
+ const near = side2 === "below" ? anchor.bottom + GAP : anchor.top - GAP - height2;
387
+ return { top: Math.max(MARGIN, Math.min(near, viewport.height - MARGIN - height2)), left, maxHeight: most, side: side2 };
388
+ }
389
+ const side = size.height <= below || below >= above ? "below" : "above";
390
+ const room = side === "below" ? below : above;
391
+ const height = Math.min(size.height, room);
392
+ const top = side === "below" ? anchor.bottom + GAP : anchor.top - GAP - height;
393
+ return { top: Math.max(MARGIN, top), left, maxHeight: Math.max(120, room), side };
394
+ }
395
+ function fromOrigin(place, origin) {
396
+ return { ...place, top: place.top - origin.top, left: place.left - origin.left };
397
+ }
398
+
399
+ // src/popover.jsx
400
+ var LayerContext = createContext({ layer: (
401
+ /** @type {HTMLElement | null} */
402
+ null
403
+ ), size: "wide" });
404
+ var OPTION = "[data-pk-option]:not([disabled])";
405
+ function wheelScrollsInside(path, popover, dx, dy) {
406
+ for (const node of path) {
407
+ if (!(node instanceof Element)) {
408
+ continue;
409
+ }
410
+ const style = node.ownerDocument.defaultView?.getComputedStyle(node);
411
+ const scrolls = (overflow) => overflow === "auto" || overflow === "scroll";
412
+ if (style && scrolls(style.overflowY) && (dy < 0 && node.scrollTop > 0 || dy > 0 && node.scrollTop + node.clientHeight < node.scrollHeight - 1)) {
413
+ return true;
414
+ }
415
+ if (style && scrolls(style.overflowX) && (dx < 0 && node.scrollLeft > 0 || dx > 0 && node.scrollLeft + node.clientWidth < node.scrollWidth - 1)) {
416
+ return true;
417
+ }
418
+ if (node === popover) {
419
+ return false;
420
+ }
421
+ }
422
+ return false;
423
+ }
424
+ function Popover({ open, anchor, onClose, label, role = "dialog", align = "start", className, id, passive = false, fill: fill2 = false, onPointerEnter, onPointerLeave, children }) {
425
+ const { layer, size } = useContext(LayerContext);
426
+ const ref = useRef3(
427
+ /** @type {HTMLDivElement | null} */
428
+ null
429
+ );
430
+ const [pos, setPos] = useState(
431
+ /** @type {null | { top: number, left: number, maxHeight: number, side: string }} */
432
+ null
433
+ );
434
+ const sheet = size === "narrow" && !passive;
435
+ useIsoLayoutEffect(() => {
436
+ if (!open) {
437
+ setPos(null);
438
+ return void 0;
439
+ }
440
+ const place = () => {
441
+ const el2 = ref.current;
442
+ const a = anchor.current;
443
+ if (!el2 || !a || sheet) {
444
+ return;
445
+ }
446
+ const r = a.getBoundingClientRect();
447
+ const place2 = placePopover(r, { width: el2.offsetWidth, height: el2.scrollHeight }, { width: window.innerWidth, height: window.innerHeight }, align, { fill: fill2 });
448
+ const probe = layer?.querySelector(".pk-origin");
449
+ setPos(probe ? fromOrigin(place2, probe.getBoundingClientRect()) : place2);
450
+ };
451
+ place();
452
+ const el = ref.current;
453
+ const ro = typeof ResizeObserver === "function" && el ? new ResizeObserver(place) : null;
454
+ if (ro && el) {
455
+ ro.observe(el);
456
+ }
457
+ window.addEventListener("resize", place);
458
+ window.addEventListener("scroll", place, true);
459
+ return () => {
460
+ ro?.disconnect();
461
+ window.removeEventListener("resize", place);
462
+ window.removeEventListener("scroll", place, true);
463
+ };
464
+ }, [open, anchor, align, sheet, layer, fill2]);
465
+ useEscapeLayer(open, onClose);
466
+ const closeRef = useRef3(onClose);
467
+ useEffect3(() => {
468
+ closeRef.current = onClose;
469
+ });
470
+ useEffect3(() => {
471
+ if (!open || passive) {
472
+ return void 0;
473
+ }
474
+ const el = ref.current;
475
+ const shown = (o) => o.getClientRects().length > 0;
476
+ const first = el?.querySelector("[data-autofocus]") ?? [...el?.querySelectorAll(OPTION) ?? []].find(shown) ?? [...el?.querySelectorAll(FOCUSABLE) ?? []].find(shown);
477
+ const t = requestAnimationFrame(() => (
478
+ /** @type {HTMLElement | null} */
479
+ first?.focus({ preventScroll: true })
480
+ ));
481
+ const onDown = (e) => {
482
+ if (!eventWithin(e, [el, anchor.current])) {
483
+ closeRef.current();
484
+ }
485
+ };
486
+ const doc = el?.ownerDocument ?? document;
487
+ doc.addEventListener("pointerdown", onDown, true);
488
+ const onWheel = (e) => {
489
+ if (el && !e.ctrlKey && !wheelScrollsInside(e.composedPath(), el, e.deltaX, e.deltaY)) {
490
+ e.preventDefault();
491
+ }
492
+ };
493
+ el?.addEventListener("wheel", onWheel, { passive: false });
494
+ const button = anchor.current;
495
+ return () => {
496
+ cancelAnimationFrame(t);
497
+ doc.removeEventListener("pointerdown", onDown, true);
498
+ el?.removeEventListener("wheel", onWheel);
499
+ const now = activeIn(button);
500
+ if (button && button.isConnected && (!now || now === doc.body || el?.contains(now) || !now.isConnected)) {
501
+ button.focus({ preventScroll: true });
502
+ }
503
+ };
504
+ }, [open, anchor, passive]);
505
+ if (!open || !layer) {
506
+ return null;
507
+ }
508
+ const onKeyDown = (e) => {
509
+ if (role === "menu" && e.key === "Tab") {
510
+ e.preventDefault();
511
+ onClose();
512
+ return;
513
+ }
514
+ if (sheet) {
515
+ trapTab(e, ref.current);
516
+ }
517
+ if (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Home" || e.key === "End") {
518
+ const options = (
519
+ /** @type {HTMLElement[]} */
520
+ [...ref.current?.querySelectorAll(OPTION) ?? []].filter((o) => o.getClientRects().length > 0)
521
+ );
522
+ if (options.length === 0 || e.target instanceof HTMLInputElement && e.target.type !== "checkbox") {
523
+ return;
524
+ }
525
+ e.preventDefault();
526
+ const at = options.indexOf(
527
+ /** @type {HTMLElement} */
528
+ activeIn(ref.current)
529
+ );
530
+ const next = e.key === "Home" ? 0 : e.key === "End" ? options.length - 1 : (at + (e.key === "ArrowDown" ? 1 : -1) + options.length) % options.length;
531
+ options[next].focus();
532
+ }
533
+ };
534
+ const onBlur = (e) => {
535
+ const to = (
536
+ /** @type {Node | null} */
537
+ e.relatedTarget
538
+ );
539
+ if (to && !ref.current?.contains(to) && !anchor.current?.contains(to)) {
540
+ onClose();
541
+ }
542
+ };
543
+ const style = sheet ? void 0 : pos ? { top: pos.top, left: pos.left, maxHeight: pos.maxHeight } : { top: 0, left: 0, visibility: (
544
+ /** @type {const} */
545
+ "hidden"
546
+ ) };
547
+ return createPortal(
548
+ /* @__PURE__ */ React3.createElement(React3.Fragment, null, sheet ? /* @__PURE__ */ React3.createElement("div", { className: "pk-scrim", onClick: onClose, "aria-hidden": "true" }) : null, /* @__PURE__ */ React3.createElement(
549
+ "div",
550
+ {
551
+ ref,
552
+ id,
553
+ role,
554
+ "aria-label": passive ? void 0 : label,
555
+ "aria-modal": sheet && role === "dialog" ? true : void 0,
556
+ className: `pk-popover${sheet ? " pk-sheet" : ""}${pos?.side === "above" ? " pk-above" : ""}${className ? ` ${className}` : ""}`,
557
+ style,
558
+ onKeyDown,
559
+ onBlur: sheet || passive ? void 0 : onBlur,
560
+ onPointerEnter,
561
+ onPointerLeave,
562
+ tabIndex: passive ? void 0 : -1
563
+ },
564
+ children
565
+ )),
566
+ layer
567
+ );
568
+ }
569
+ function MenuButton({ label, icon, text, showText = true, className, role = "menu", align, popoverClass, disabled, title, children, testId, buttonRef, name: name2, tabIndex, slot, fill: fill2, mark }) {
570
+ const [open, setOpen] = useState(false);
571
+ const own = useRef3(
572
+ /** @type {HTMLButtonElement | null} */
573
+ null
574
+ );
575
+ const ref = buttonRef ?? own;
576
+ const id = useId();
577
+ const close = useCallback(() => setOpen(false), []);
578
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(
579
+ "button",
580
+ {
581
+ ref,
582
+ type: "button",
583
+ className: className ?? "pk-btn",
584
+ "aria-haspopup": role === "menu" ? "menu" : "dialog",
585
+ "aria-expanded": open,
586
+ "aria-controls": open ? id : void 0,
587
+ "aria-label": name2 ?? (showText && text ? void 0 : label),
588
+ title: title ?? (showText && text ? void 0 : label),
589
+ disabled,
590
+ tabIndex,
591
+ "data-pk-slot": slot,
592
+ "data-testid": testId,
593
+ onClick: () => setOpen((o) => !o)
594
+ },
595
+ icon ? /* @__PURE__ */ React3.createElement(Icon, { name: (
596
+ /** @type {any} */
597
+ icon
598
+ ) }) : null,
599
+ showText && text ? /* @__PURE__ */ React3.createElement("span", { className: "pk-btn-text" }, text) : null,
600
+ mark,
601
+ showText && text ? /* @__PURE__ */ React3.createElement(Icon, { name: "chevronDown", size: 14, className: "pk-caret" }) : null
602
+ ), /* @__PURE__ */ React3.createElement(Popover, { open, anchor: ref, onClose: close, label, role, align, className: popoverClass, id, fill: fill2 }, children(close)));
603
+ }
604
+ function Option({ onSelect, icon, checked, children, hint, reason, inMenu = false, disabled, danger, tone, testId, current }) {
605
+ const second = disabled && reason ? reason : hint;
606
+ const role = inMenu ? checked === void 0 ? "menuitem" : "menuitemradio" : void 0;
607
+ return /* @__PURE__ */ React3.createElement(
608
+ "button",
609
+ {
610
+ type: "button",
611
+ role,
612
+ "aria-checked": inMenu && checked !== void 0 ? checked : void 0,
613
+ "aria-pressed": !inMenu && checked !== void 0 ? checked : void 0,
614
+ "aria-current": current ? "true" : void 0,
615
+ className: `pk-option${checked ? " pk-checked" : ""}${danger ? " pk-danger" : ""}${tone === "accent" ? " pk-accent" : ""}`,
616
+ "data-pk-option": "",
617
+ "data-testid": testId,
618
+ disabled,
619
+ onClick: onSelect
620
+ },
621
+ /* @__PURE__ */ React3.createElement("span", { className: "pk-option-icon" }, checked || current ? /* @__PURE__ */ React3.createElement(Icon, { name: "check" }) : icon ? /* @__PURE__ */ React3.createElement(Icon, { name: (
622
+ /** @type {any} */
623
+ icon
624
+ ) }) : null),
625
+ /* @__PURE__ */ React3.createElement("span", { className: "pk-option-text" }, children, second ? /* @__PURE__ */ React3.createElement("span", { className: "pk-option-hint" }, second) : null)
626
+ );
627
+ }
628
+
629
+ // src/info.jsx
630
+ import React4, { useCallback as useCallback2, useEffect as useEffect4, useId as useId2, useRef as useRef4, useState as useState2 } from "react";
631
+ var LEAVE_DELAY = 250;
632
+ function FieldDescription({ info, labels, link = true, className = "pk-field-desc" }) {
633
+ return /* @__PURE__ */ React4.createElement("p", { className }, /* @__PURE__ */ React4.createElement("span", null, info.description), link && info.href ? /* @__PURE__ */ React4.createElement(React4.Fragment, null, " ", /* @__PURE__ */ React4.createElement("a", { href: info.href, target: "_blank", rel: "noopener noreferrer", className: "pk-learn-more" }, labels.learnMore)) : null);
634
+ }
635
+ function InfoButton({ info, name: name2, labels, className, testId = "field-info", label: named, tabIndex, slot }) {
636
+ const [mode, setMode] = useState2(
637
+ /** @type {null | "peek" | "open"} */
638
+ null
639
+ );
640
+ const ref = useRef4(
641
+ /** @type {HTMLButtonElement | null} */
642
+ null
643
+ );
644
+ const quiet = useRef4(false);
645
+ const leaving = useRef4(
646
+ /** @type {ReturnType<typeof setTimeout> | null} */
647
+ null
648
+ );
649
+ const id = useId2();
650
+ const textId = useId2();
651
+ const stay = () => {
652
+ if (leaving.current) {
653
+ clearTimeout(leaving.current);
654
+ leaving.current = null;
655
+ }
656
+ };
657
+ const leaveSoon = () => {
658
+ stay();
659
+ leaving.current = setTimeout(() => setMode((m) => m === "peek" ? null : m), LEAVE_DELAY);
660
+ };
661
+ useEffect4(() => stay, []);
662
+ const close = useCallback2(() => {
663
+ quiet.current = true;
664
+ setMode(null);
665
+ requestAnimationFrame(() => {
666
+ quiet.current = false;
667
+ });
668
+ }, []);
669
+ const label = named ?? fill(labels.aboutField, { field: name2 });
670
+ return /* @__PURE__ */ React4.createElement(React4.Fragment, null, /* @__PURE__ */ React4.createElement(
671
+ "button",
672
+ {
673
+ ref,
674
+ type: "button",
675
+ className: `pk-info${className ? ` ${className}` : ""}`,
676
+ "aria-label": label,
677
+ "aria-describedby": textId,
678
+ "aria-expanded": mode === "open",
679
+ "aria-controls": mode ? id : void 0,
680
+ "aria-haspopup": "dialog",
681
+ tabIndex,
682
+ "data-pk-slot": slot,
683
+ "data-testid": testId,
684
+ onPointerEnter: (e) => {
685
+ if (e.pointerType === "mouse") {
686
+ stay();
687
+ setMode((m) => m ?? "peek");
688
+ }
689
+ },
690
+ onPointerLeave: (e) => {
691
+ if (e.pointerType === "mouse" && mode === "peek") {
692
+ leaveSoon();
693
+ }
694
+ },
695
+ onFocus: () => {
696
+ if (mode === null && !quiet.current) {
697
+ setMode("peek");
698
+ }
699
+ },
700
+ onBlur: (e) => {
701
+ const to = (
702
+ /** @type {Element | null} */
703
+ e.relatedTarget
704
+ );
705
+ if (mode === "peek" && !(to && to.closest?.(".pk-info-pop"))) {
706
+ setMode(null);
707
+ }
708
+ },
709
+ onClick: () => {
710
+ stay();
711
+ setMode(mode === "open" ? null : "open");
712
+ }
713
+ },
714
+ /* @__PURE__ */ React4.createElement(Icon, { name: "info", size: 14 })
715
+ ), /* @__PURE__ */ React4.createElement("span", { id: textId, hidden: true }, info.description), /* @__PURE__ */ React4.createElement(
716
+ Popover,
717
+ {
718
+ key: mode ?? "closed",
719
+ open: mode !== null,
720
+ passive: mode === "peek",
721
+ anchor: ref,
722
+ onClose: close,
723
+ label,
724
+ role: mode === "peek" ? "tooltip" : "dialog",
725
+ className: "pk-info-pop",
726
+ id,
727
+ onPointerEnter: stay,
728
+ onPointerLeave: (e) => {
729
+ if (e.pointerType === "mouse" && mode === "peek") {
730
+ leaveSoon();
731
+ }
732
+ }
733
+ },
734
+ /* @__PURE__ */ React4.createElement(FieldDescription, { info, labels })
735
+ ));
736
+ }
737
+
738
+ // src/view-ops.js
739
+ import { LIMITS, aggregatorsFor, isFormat } from "pivotkit-core";
740
+ var ZONES = Object.freeze(
741
+ /** @type {Zone[]} */
742
+ ["filters", "cols", "rows", "values"]
743
+ );
744
+ var clone = (view) => JSON.parse(JSON.stringify(view));
745
+ var same = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
746
+ var clamp = (i, n) => Number.isInteger(i) ? Math.max(0, Math.min(i, n)) : n;
747
+ function filterZoneFields(view) {
748
+ const seen = /* @__PURE__ */ new Set();
749
+ const out = [];
750
+ for (const f of view.filters) {
751
+ const key = f.field.toLowerCase();
752
+ if (!seen.has(key) && !view.rows.some((r) => same(r, f.field)) && !view.cols.some((c) => same(c, f.field))) {
753
+ seen.add(key);
754
+ out.push(f.field);
755
+ }
756
+ }
757
+ return out;
758
+ }
759
+ function axisOf(view, field) {
760
+ if (view.rows.some((r) => same(r, field))) {
761
+ return "rows";
762
+ }
763
+ if (view.cols.some((c) => same(c, field))) {
764
+ return "cols";
765
+ }
766
+ return null;
767
+ }
768
+ function defaultAgg(type, wanted) {
769
+ if (typeof wanted === "string" && aggregatorsFor(type ?? "string").includes(wanted)) {
770
+ return wanted;
771
+ }
772
+ return type === "number" && aggregatorsFor(type).includes("sum") ? "sum" : "count";
773
+ }
774
+ function tidy(view) {
775
+ 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()));
776
+ view.derived = view.derived.filter((d) => used.has(d.name.toLowerCase()));
777
+ view.sort = view.sort.filter((s) => used.has(s.field.toLowerCase()));
778
+ return view;
779
+ }
780
+ function dropFromAxes(view, field) {
781
+ view.rows = view.rows.filter((r) => !same(r, field));
782
+ view.cols = view.cols.filter((c) => !same(c, field));
783
+ }
784
+ function resetCollapsed(view, before) {
785
+ for (const axis of ["rows", "cols"]) {
786
+ if (JSON.stringify(before[axis]) !== JSON.stringify(view[axis])) {
787
+ view.collapsed[axis] = [];
788
+ }
789
+ }
790
+ }
791
+ function zoneOverLimit(view, limits) {
792
+ const limit = (name2) => limits && Number.isInteger(limits[name2]) && limits[name2] > 0 ? limits[name2] : LIMITS[name2];
793
+ for (
794
+ const [zone, name2] of
795
+ /** @type {const} */
796
+ [["rows", "axisFields"], ["cols", "axisFields"], ["values", "values"]]
797
+ ) {
798
+ const list = view && Array.isArray(view[zone]) ? view[zone] : [];
799
+ if (list.length > limit(name2)) {
800
+ return { zone, max: limit(name2) };
801
+ }
802
+ }
803
+ return null;
804
+ }
805
+ function addField(view, field, zone, options = {}) {
806
+ if (options.dateUnit && zone !== "values") {
807
+ const name2 = options.groupName ?? `${field} (${options.dateUnit})`;
808
+ const placed = addField(removeField(view, name2), field, zone, { ...options, dateUnit: null, defaults: void 0 });
809
+ return groupField(placed, field, options.dateUnit, { name: name2 }).view;
810
+ }
811
+ const next = clone(view);
812
+ if (zone === "rows" || zone === "cols") {
813
+ dropFromAxes(next, field);
814
+ next[zone].splice(clamp(options.index, next[zone].length), 0, field);
815
+ const order = options.defaults?.order;
816
+ if (Array.isArray(order) && order.length > 0 && !next.sort.some((s) => same(s.field, field))) {
817
+ next.sort.push({ field, by: "custom", order: "asc", items: [...order] });
818
+ }
819
+ } else if (zone === "values") {
820
+ const wanted = options.defaults ?? {};
821
+ const format = typeof wanted.format === "string" && isFormat(wanted.format) ? wanted.format : null;
822
+ next.values.splice(clamp(options.index, next.values.length), 0, { field, agg: defaultAgg(options.type, wanted.agg), format, label: null, showAs: null, conditional: null });
823
+ } else if (zone === "filters") {
824
+ dropFromAxes(next, field);
825
+ if (!next.filters.some((f) => same(f.field, field))) {
826
+ next.filters.push({ field, type: "exclude", items: [] });
827
+ }
828
+ }
829
+ resetCollapsed(next, view);
830
+ return tidy(next);
831
+ }
832
+ function removeAt(view, zone, index) {
833
+ const next = clone(view);
834
+ if (zone === "values") {
835
+ next.values.splice(index, 1);
836
+ } else {
837
+ const list = zone === "filters" ? filterZoneFields(view) : view[zone];
838
+ const field = list[index];
839
+ if (field === void 0) {
840
+ return view;
841
+ }
842
+ dropFromAxes(next, field);
843
+ next.filters = next.filters.filter((f) => !same(f.field, field));
844
+ }
845
+ resetCollapsed(next, view);
846
+ return tidy(next);
847
+ }
848
+ function removeField(view, field) {
849
+ if (!axisOf(view, field) && !filterZoneFields(view).some((f) => same(f, field))) {
850
+ return view;
851
+ }
852
+ const next = clone(view);
853
+ dropFromAxes(next, field);
854
+ next.filters = next.filters.filter((f) => !same(f.field, field));
855
+ resetCollapsed(next, view);
856
+ return tidy(next);
857
+ }
858
+ function fieldAt(view, zone, index) {
859
+ if (zone === "values") {
860
+ return view.values[index] ? view.values[index].field : void 0;
861
+ }
862
+ return (zone === "filters" ? filterZoneFields(view) : view[zone])[index];
863
+ }
864
+ function moveField(view, from, fromIndex, to, toIndex, options = {}) {
865
+ if (from === to) {
866
+ return reorder(view, from, fromIndex, toIndex);
867
+ }
868
+ const field = fieldAt(view, from, fromIndex);
869
+ if (field === void 0 || field === null) {
870
+ return view;
871
+ }
872
+ let next = clone(view);
873
+ if (from === "values") {
874
+ next.values.splice(fromIndex, 1);
875
+ } else if (to !== "filters") {
876
+ dropFromAxes(next, field);
877
+ if (to === "values") {
878
+ next.filters = next.filters.filter((f) => !same(f.field, field));
879
+ }
880
+ }
881
+ next = addField(next, field, to, { ...options, index: toIndex });
882
+ resetCollapsed(next, view);
883
+ return tidy(next);
884
+ }
885
+ function reorder(view, zone, from, to) {
886
+ const list = zone === "filters" ? null : zone === "values" ? view.values : view[zone];
887
+ if (!list || from === to || from < 0 || from >= list.length) {
888
+ return view;
889
+ }
890
+ const next = clone(view);
891
+ const target = next[zone];
892
+ const [item] = target.splice(from, 1);
893
+ target.splice(clamp(to, target.length), 0, item);
894
+ resetCollapsed(next, view);
895
+ return next;
896
+ }
897
+ function numberRange(encoded, field) {
898
+ const column = encoded.column(field);
899
+ if (!column || column.type !== "number") {
900
+ return null;
901
+ }
902
+ let min = Infinity;
903
+ let max = -Infinity;
904
+ for (const v of column.dict) {
905
+ if (typeof v === "number" && Number.isFinite(v)) {
906
+ min = Math.min(min, v);
907
+ max = Math.max(max, v);
908
+ }
909
+ }
910
+ return min <= max ? { min, max } : null;
911
+ }
912
+ function groupField(view, field, unit, options = {}) {
913
+ const spec = view.derived.find((d) => same(d.name, field));
914
+ const source = spec ? spec.field : field;
915
+ const axis = axisOf(view, field);
916
+ const next = clone(view);
917
+ let name2 = source;
918
+ if (unit) {
919
+ name2 = options.name ?? `${source} (${unit})`;
920
+ const existing = next.derived.find((d) => same(d.name, name2));
921
+ const origin = options.origin ?? (spec?.by === "bin" ? spec.origin ?? 0 : 0);
922
+ const wanted = unit === "bin" ? { name: name2, field: source, by: unit, size: options.size, origin } : { name: name2, field: source, by: unit };
923
+ if (existing) {
924
+ Object.assign(existing, wanted);
925
+ } else {
926
+ next.derived.push(wanted);
927
+ }
928
+ }
929
+ if (axis) {
930
+ const other = axis === "rows" ? "cols" : "rows";
931
+ if (!same(name2, field) && next[other].some((f) => same(f, name2))) {
932
+ next[axis] = next[axis].filter((f) => !same(f, field));
933
+ } else {
934
+ const seen = /* @__PURE__ */ new Set();
935
+ next[axis] = next[axis].map((f) => same(f, field) ? name2 : f).filter((f) => !seen.has(f.toLowerCase()) && seen.add(f.toLowerCase()));
936
+ }
937
+ }
938
+ if (!same(name2, field)) {
939
+ const inFilterZone = !axis && filterZoneFields(view).some((f) => same(f, field));
940
+ next.filters = next.filters.filter((f) => !same(f.field, field));
941
+ if (inFilterZone) {
942
+ next.filters.push({ field: name2, type: "exclude", items: [] });
943
+ }
944
+ }
945
+ next.sort = next.sort.map((s) => same(s.field, field) ? { ...s, field: name2 } : s);
946
+ resetCollapsed(next, view);
947
+ return { view: tidy(next), field: name2 };
948
+ }
949
+ function groupingOf(view, field) {
950
+ return view.derived.find((d) => same(d.name, field)) ?? null;
951
+ }
952
+ function sourceOf(view, field) {
953
+ const spec = groupingOf(view, field);
954
+ return spec ? spec.field : field;
955
+ }
956
+ function setSort(view, field, sort) {
957
+ const next = clone(view);
958
+ next.sort = next.sort.filter((s) => !same(s.field, field));
959
+ if (sort) {
960
+ next.sort.push({ field, ...sort });
961
+ }
962
+ return next;
963
+ }
964
+ function withHostOrders(view, orderOf) {
965
+ const missing = [...view.rows, ...view.cols].filter((field) => !view.derived.some((d) => same(d.name, field)) && !view.sort.some((s) => same(s.field, field)));
966
+ const added = missing.map((field) => ({ field, order: orderOf(field) })).filter(({ order }) => Array.isArray(order) && order.length > 0);
967
+ if (!added.length) {
968
+ return view;
969
+ }
970
+ const next = clone(view);
971
+ for (const { field, order } of added) {
972
+ next.sort.push({ field, by: "custom", order: "asc", items: [.../** @type {unknown[]} */
973
+ order] });
974
+ }
975
+ return next;
976
+ }
977
+ function sortOf(view, field) {
978
+ return view.sort.find((s) => same(s.field, field)) ?? null;
979
+ }
980
+ function sortEntry(spec, hostOrdered) {
981
+ return spec.by === "label" && spec.order === "asc" && !hostOrdered ? null : spec;
982
+ }
983
+ function headerSortTarget(view, cell, typeOf) {
984
+ if (cell.kind === "corner") {
985
+ return cell.field && view.rows.some((f) => same(f, cell.field)) ? { field: cell.field } : null;
986
+ }
987
+ const spec = cell.kind === "colHeader" && cell.valueIndex !== void 0 && !cell.colPath?.length ? view.values[cell.valueIndex] : void 0;
988
+ if (!spec || !view.rows.length || !numericResult(spec, spec.field ? typeOf(spec.field) ?? "string" : "number")) {
989
+ return null;
990
+ }
991
+ return { field: view.rows[view.rows.length - 1], ref: { field: spec.field ?? null, agg: spec.agg } };
992
+ }
993
+ function headerSortState(view, target) {
994
+ const s = sortOf(view, target.field);
995
+ const word = (order) => order === "desc" ? "descending" : "ascending";
996
+ if (target.ref) {
997
+ return s?.by === "value" && sameRef(s.value, target.ref) ? { order: word(s.order), chosen: true } : { order: null, chosen: false };
998
+ }
999
+ if (!s) {
1000
+ return { order: "ascending", chosen: false };
1001
+ }
1002
+ return { order: s.by === "label" ? word(s.order) : s.by === "custom" ? "other" : null, chosen: s.by === "label" };
1003
+ }
1004
+ function nextHeaderSort(view, target, hostOrdered) {
1005
+ const s = sortOf(view, target.field);
1006
+ if (target.ref) {
1007
+ const mine = s?.by === "value" && sameRef(s.value, target.ref);
1008
+ return mine && s.order === "asc" ? null : { by: "value", order: mine ? "asc" : "desc", value: mine ? s.value : target.ref };
1009
+ }
1010
+ const desc = !s || s.by === "label" && s.order === "asc";
1011
+ return sortEntry({ by: "label", order: desc ? "desc" : "asc" }, hostOrdered);
1012
+ }
1013
+ function filtersOf(view, field, types) {
1014
+ return view.filters.filter((f) => same(f.field, field) && (!types || types.includes(f.type)));
1015
+ }
1016
+ function selectedItems(view, field, all) {
1017
+ let selected = all;
1018
+ for (const f of filtersOf(view, field, ["include", "exclude"])) {
1019
+ const listed = new Set(f.items.map((v) => JSON.stringify(v)));
1020
+ selected = selected.filter((v) => listed.has(JSON.stringify(v)) === (f.type === "include"));
1021
+ }
1022
+ return selected;
1023
+ }
1024
+ function numericResult(spec, type) {
1025
+ return spec.agg !== "listUnique" && !(["first", "last"].includes(spec.agg) && type !== "number") && !(type === "date" && ["average", "median", "min", "max"].includes(spec.agg));
1026
+ }
1027
+ function sameRef(a, b) {
1028
+ return Boolean(a && b) && a.agg === b.agg && (a.field === null || b.field === null ? a.field === b.field : same(a.field, b.field));
1029
+ }
1030
+ function isFiltered(view, field) {
1031
+ return filtersOf(view, field).some((f) => f.type !== "exclude" || f.items.length > 0);
1032
+ }
1033
+ function toggleCollapsed(view, axis, path) {
1034
+ const next = clone(view);
1035
+ const key = JSON.stringify(path);
1036
+ const list = next.collapsed[axis];
1037
+ const at = list.findIndex((p) => JSON.stringify(p) === key);
1038
+ if (at === -1) {
1039
+ list.push(path);
1040
+ } else {
1041
+ list.splice(at, 1);
1042
+ }
1043
+ return next;
1044
+ }
1045
+ function rowFolding(view, outer) {
1046
+ const keys = new Set(view.collapsed.rows.map((p) => JSON.stringify(p)));
1047
+ const collapsed = outer.filter((p) => keys.has(JSON.stringify(p))).length;
1048
+ const open = view.rows.length < 2 ? 0 : outer.length - collapsed;
1049
+ const canExpand = view.collapsed.rows.length > 0;
1050
+ const canCollapse = open > 0;
1051
+ return {
1052
+ canExpand,
1053
+ canCollapse,
1054
+ collapsed: view.collapsed.rows.length,
1055
+ open,
1056
+ // keys of the menus' texts (menu-labels.js): the Options menu shows them with its labels
1057
+ why: {
1058
+ expand: canExpand ? null : "expandNothing",
1059
+ collapse: canCollapse ? null : view.rows.length < 2 ? "collapseNeedsRows" : "collapseAllDone"
1060
+ }
1061
+ };
1062
+ }
1063
+ function setCollapsed(view, axis, paths) {
1064
+ const next = clone(view);
1065
+ next.collapsed[axis] = paths ? paths : [];
1066
+ return next;
1067
+ }
1068
+ function setTotal(view, key, on) {
1069
+ const next = clone(view);
1070
+ next.totals[key] = Boolean(on);
1071
+ return next;
1072
+ }
1073
+ function setDisplay(view, display) {
1074
+ const next = clone(view);
1075
+ next.display = display;
1076
+ return next;
1077
+ }
1078
+ function setChart(view, name2) {
1079
+ const next = clone(view);
1080
+ next.chart = { ...next.chart, ...CHART_TYPES[name2].chart };
1081
+ next.display = "chart";
1082
+ return next;
1083
+ }
1084
+ function setChartDisplay(view, patch) {
1085
+ const next = clone(view);
1086
+ next.chart = { ...next.chart, ...patch };
1087
+ return next;
1088
+ }
1089
+ function swapAxes(view) {
1090
+ const next = clone(view);
1091
+ [next.rows, next.cols] = [next.cols, next.rows];
1092
+ next.collapsed = { rows: next.collapsed.cols, cols: next.collapsed.rows };
1093
+ for (const v of next.values) {
1094
+ if (v.showAs && v.showAs.axis) {
1095
+ v.showAs = { ...v.showAs, axis: v.showAs.axis === "rows" ? "cols" : "rows" };
1096
+ }
1097
+ }
1098
+ const swapped = { percentOfRowTotal: "percentOfColumnTotal", percentOfColumnTotal: "percentOfRowTotal", percentOfParentRow: "percentOfParentColumn", percentOfParentColumn: "percentOfParentRow" };
1099
+ for (const v of next.values) {
1100
+ if (v.showAs && Object.hasOwn(swapped, v.showAs.type)) {
1101
+ v.showAs = { ...v.showAs, type: swapped[v.showAs.type] };
1102
+ }
1103
+ }
1104
+ return next;
1105
+ }
1106
+ function isEmptyView(view) {
1107
+ return view.rows.length === 0 && view.cols.length === 0 && view.values.length === 0;
1108
+ }
1109
+
1110
+ // src/help.js
1111
+ import { createContext as createContext2 } from "react";
1112
+ var HelpContext = createContext2(
1113
+ /** @type {Help} */
1114
+ { explain: true, isOpen: () => true, setOpen: () => {
1115
+ }, labels: null }
1116
+ );
1117
+
1118
+ // src/storage.js
1119
+ function localStore() {
1120
+ try {
1121
+ return typeof window !== "undefined" && window.localStorage ? window.localStorage : null;
1122
+ } catch {
1123
+ return null;
1124
+ }
1125
+ }
1126
+ function readItem(name2, storage) {
1127
+ try {
1128
+ return storage ? storage.getItem(name2) : null;
1129
+ } catch {
1130
+ return null;
1131
+ }
1132
+ }
1133
+ var listeners = /* @__PURE__ */ new Map();
1134
+ function subscribeItem(name2, callback) {
1135
+ const set = listeners.get(name2) ?? /* @__PURE__ */ new Set();
1136
+ set.add(callback);
1137
+ listeners.set(name2, set);
1138
+ const onStorage = (e) => {
1139
+ if (e.key === null || e.key === name2) {
1140
+ callback();
1141
+ }
1142
+ };
1143
+ const win = typeof window !== "undefined" ? window : null;
1144
+ win?.addEventListener("storage", onStorage);
1145
+ return () => {
1146
+ set.delete(callback);
1147
+ if (set.size === 0) {
1148
+ listeners.delete(name2);
1149
+ }
1150
+ win?.removeEventListener("storage", onStorage);
1151
+ };
1152
+ }
1153
+ function writeItem(name2, storage, text) {
1154
+ let ok = false;
1155
+ if (storage) {
1156
+ try {
1157
+ if (text === null) {
1158
+ storage.removeItem(name2);
1159
+ } else {
1160
+ storage.setItem(name2, text);
1161
+ }
1162
+ ok = true;
1163
+ } catch {
1164
+ }
1165
+ }
1166
+ for (const callback of [...listeners.get(name2) ?? []]) {
1167
+ callback();
1168
+ }
1169
+ return ok;
1170
+ }
1171
+
1172
+ // src/tips.js
1173
+ import { CATALOG, fieldLabel as fieldLabel2, suggestDateUnit } from "pivotkit-core";
1174
+ var TIP_LIMIT = 1;
1175
+ var TIP_THRESHOLDS = Object.freeze({
1176
+ /** columns of an ungrouped date on Columns from which grouping it is suggested */
1177
+ dateColumns: 12,
1178
+ /** rows of an ungrouped date on Rows from which grouping it is suggested */
1179
+ dateRows: 60,
1180
+ /** columns from which swapping rows and columns is suggested (when there are fewer rows) */
1181
+ manyColumns: 20,
1182
+ /** changes of the view in this session after which saving it as a template is suggested */
1183
+ changesBeforeSave: 5,
1184
+ /** changes after the first drag during which the Undo and menu tip stays */
1185
+ afterDragChanges: 3,
1186
+ /** slices from which a pie or a donut suggests bars: a circle reads well up to about 7 parts */
1187
+ pieSlices: 7
1188
+ });
1189
+ var PERCENT_SHOW_AS = Object.freeze(["percentOfGrandTotal", "percentOfRowTotal", "percentOfColumnTotal", "percentOfParentRow", "percentOfParentColumn", "percentRunningTotal", "percentDifferenceFromPrevious"]);
1190
+ var name = (ctx, field) => fieldLabel2(field, { fields: ctx.fields });
1191
+ var derivedBy = (ctx, field) => ctx.view.derived.find((d) => d.name.toLowerCase() === String(field).toLowerCase())?.by ?? "";
1192
+ var isRawDate = (ctx, field) => ctx.typeOf(field) === "date" && sourceOf(ctx.view, field).toLowerCase() === String(field).toLowerCase();
1193
+ var table = (ctx) => !ctx.failed && !ctx.empty && ctx.view.display === "table";
1194
+ var chart = (ctx) => !ctx.failed && ctx.view.display === "chart" && ctx.series !== null && ctx.view.values.length > 0;
1195
+ var seriesOf = (ctx) => (
1196
+ /** @type {NonNullable<TipContext["series"]>} */
1197
+ ctx.series
1198
+ );
1199
+ var axisChart = (ctx) => chart(ctx) && CHART_TYPES[ctx.chartPlan.name].axis;
1200
+ var lines = (ctx) => ["line", "area"].includes(ctx.chartPlan.name);
1201
+ var sliceChart = (ctx) => chart(ctx) && SLICE_TYPES.includes(ctx.chartPlan.name);
1202
+ var dateOn = (ctx, axis) => ctx.view[axis].some((f) => ctx.typeOf(f) === "date");
1203
+ var datesAcross = (ctx) => axisChart(ctx) && !ctx.chartPlan.swap && lines(ctx) && dateOn(ctx, "cols") && !dateOn(ctx, "rows");
1204
+ var TIPS = Object.freeze([
1205
+ {
1206
+ // a filter that leaves nothing: say so instead of an empty table
1207
+ id: "filterEmpty",
1208
+ kind: "notice",
1209
+ icon: "filter",
1210
+ action: "removeFilters",
1211
+ when: (ctx) => !ctx.failed && !ctx.empty && ctx.dataRows > 0 && ctx.matched === 0 && ctx.view.filters.some((f) => isFiltered(ctx.view, f.field)) ? {} : null
1212
+ },
1213
+ {
1214
+ // top N changes what totals mean
1215
+ id: "top",
1216
+ kind: "notice",
1217
+ icon: "top",
1218
+ when: (ctx) => {
1219
+ if (ctx.failed || ctx.empty) {
1220
+ return null;
1221
+ }
1222
+ for (const field of [...ctx.view.rows, ...ctx.view.cols]) {
1223
+ const top = filtersOf(ctx.view, field, ["top"])[0];
1224
+ if (top) {
1225
+ return { field: name(ctx, field), count: top.count, bottom: Boolean(top.bottom) };
1226
+ }
1227
+ }
1228
+ return null;
1229
+ }
1230
+ },
1231
+ {
1232
+ id: "chartCapped",
1233
+ kind: "notice",
1234
+ when: (ctx) => chart(ctx) && seriesOf(ctx).categoryCount > seriesOf(ctx).categories.length ? { shown: seriesOf(ctx).categories.length, total: seriesOf(ctx).categoryCount } : null
1235
+ },
1236
+ {
1237
+ // "% of row total": what 100 % is
1238
+ id: "showAs",
1239
+ icon: "sigma",
1240
+ when: (ctx) => {
1241
+ if (ctx.failed || ctx.empty) {
1242
+ return null;
1243
+ }
1244
+ const spec = ctx.view.values.find((v) => v.showAs && PERCENT_SHOW_AS.includes(v.showAs.type));
1245
+ return spec ? { type: spec.showAs.type } : null;
1246
+ }
1247
+ },
1248
+ {
1249
+ // a type the user chose for data over time: lines show it (automatic draws them)
1250
+ id: "chartOverTime",
1251
+ icon: "line",
1252
+ action: "auto",
1253
+ when: (ctx) => {
1254
+ if (!chart(ctx) || ctx.chartPlan.auto || lines(ctx) || ctx.chartPlan.name === "heatmap") {
1255
+ return null;
1256
+ }
1257
+ if (chartPlan({ ...ctx.view, chart: { ...ctx.view.chart, type: "auto" } }, ctx.encoded).name !== "line") {
1258
+ return null;
1259
+ }
1260
+ const field = [...ctx.view.rows, ...ctx.view.cols].find((f) => ctx.typeOf(f) === "date" && !CATALOG.cyclicUnits.includes(derivedBy(ctx, f)));
1261
+ return field ? { field: name(ctx, field) } : null;
1262
+ }
1263
+ },
1264
+ {
1265
+ // a pie of many slices: the small ones cannot be told apart
1266
+ id: "pieSlices",
1267
+ icon: "chart",
1268
+ action: "bars",
1269
+ when: (ctx) => sliceChart(ctx) && seriesOf(ctx).categories.length > TIP_THRESHOLDS.pieSlices ? { count: seriesOf(ctx).categories.length, max: TIP_THRESHOLDS.pieSlices } : null
1270
+ },
1271
+ {
1272
+ // a pie draws one slice per row: the columns are added up
1273
+ id: "pieColumns",
1274
+ icon: "info",
1275
+ action: "bars",
1276
+ when: (ctx) => sliceChart(ctx) && ctx.view.cols.length > 0 ? { fields: ctx.view.cols.map((f) => name(ctx, f)).join(", ") } : null
1277
+ },
1278
+ {
1279
+ id: "chartDates",
1280
+ action: "swap",
1281
+ when: (ctx) => datesAcross(ctx) ? {} : null
1282
+ },
1283
+ {
1284
+ // a line or an area over categories without an order (countries, teams) draws a trend
1285
+ // between things that follow no line: bars fit better. Dates, number ranges and a custom
1286
+ // order (seasons) are an order
1287
+ id: "chartTrend",
1288
+ icon: "chart",
1289
+ action: "bars",
1290
+ when: (ctx) => {
1291
+ if (!axisChart(ctx) || ctx.chartPlan.auto || datesAcross(ctx) || !lines(ctx) || ctx.view.rows.length === 0) {
1292
+ return null;
1293
+ }
1294
+ const field = ctx.view.rows[ctx.view.rows.length - 1];
1295
+ const ordered = ["date", "number"].includes(ctx.typeOf(field)) || ctx.view.sort.some((s) => s.by === "custom" && String(s.field).toLowerCase() === String(field).toLowerCase());
1296
+ return ordered ? null : {};
1297
+ }
1298
+ },
1299
+ {
1300
+ id: "chartSeries",
1301
+ action: "swap",
1302
+ // the dates tip says the same (swap) more precisely; lines over time drawn automatically
1303
+ // would draw the same lines after a swap
1304
+ when: (ctx) => axisChart(ctx) && !datesAcross(ctx) && !(ctx.chartPlan.auto && lines(ctx)) && seriesOf(ctx).series.length > MANY_SERIES ? { count: seriesOf(ctx).series.length } : null
1305
+ },
1306
+ {
1307
+ // a text field in Values is counted: say so, and what a sum needs
1308
+ id: "textValue",
1309
+ icon: "sigma",
1310
+ when: (ctx) => {
1311
+ if (ctx.failed || ctx.empty) {
1312
+ return null;
1313
+ }
1314
+ const spec = ctx.view.values.find((v) => v.field && !v.label && ["string", "boolean"].includes(ctx.typeOf(v.field)));
1315
+ return spec ? { field: name(ctx, spec.field) } : null;
1316
+ }
1317
+ },
1318
+ {
1319
+ // a date without grouping makes a column per day (or per instant)
1320
+ id: "dateUngrouped",
1321
+ icon: "date",
1322
+ action: "groupDate",
1323
+ when: (ctx) => {
1324
+ if (!table(ctx)) {
1325
+ return null;
1326
+ }
1327
+ const onCols = ctx.colLeaves > TIP_THRESHOLDS.dateColumns ? ctx.view.cols.find((f) => isRawDate(ctx, f)) : void 0;
1328
+ const field = onCols ?? (ctx.rowLeaves > TIP_THRESHOLDS.dateRows ? ctx.view.rows.find((f) => isRawDate(ctx, f)) : void 0);
1329
+ if (!field) {
1330
+ return null;
1331
+ }
1332
+ const column = ctx.encoded.column(field);
1333
+ const suggested = suggestDateUnit(ctx.encoded, field);
1334
+ const unit = !suggested || suggested === "day" && column?.dateOnly ? "yearMonth" : suggested;
1335
+ return { field: name(ctx, field), source: field, unit };
1336
+ }
1337
+ },
1338
+ {
1339
+ id: "manyColumns",
1340
+ icon: "swap",
1341
+ action: "swap",
1342
+ when: (ctx) => table(ctx) && ctx.view.cols.length > 0 && ctx.colLeaves > TIP_THRESHOLDS.manyColumns && ctx.rowLeaves < ctx.colLeaves ? { count: ctx.colLeaves } : null
1343
+ },
1344
+ {
1345
+ // once after the first drag: Undo and the menus (before the next step: it goes after a few changes)
1346
+ id: "afterDrag",
1347
+ icon: "undo",
1348
+ when: (ctx) => !ctx.failed && ctx.dragAt !== null && ctx.changes - ctx.dragAt <= TIP_THRESHOLDS.afterDragChanges ? {} : null
1349
+ },
1350
+ {
1351
+ // rows without values show no numbers
1352
+ id: "values",
1353
+ icon: "sigma",
1354
+ when: (ctx) => table(ctx) && ctx.view.values.length === 0 ? {} : null
1355
+ },
1356
+ {
1357
+ id: "saveTemplate",
1358
+ icon: "bookmark",
1359
+ action: "saveTemplate",
1360
+ // after a save it waits for as many changes again
1361
+ when: (ctx) => ctx.canSave && !ctx.failed && !ctx.empty && ctx.changes - ctx.savedAt >= TIP_THRESHOLDS.changesBeforeSave ? {} : null
1362
+ },
1363
+ {
1364
+ // the empty report: every field has a menu, and Undo is there
1365
+ id: "menus",
1366
+ icon: "sparkle",
1367
+ when: (ctx) => !ctx.failed && ctx.empty && ctx.view.display === "table" && ctx.dragAt === null ? {} : null
1368
+ },
1369
+ {
1370
+ id: "cells",
1371
+ icon: "info",
1372
+ when: (ctx) => table(ctx) && ctx.tableShown && ctx.view.values.length > 0 && !ctx.drilled ? {} : null
1373
+ }
1374
+ ]);
1375
+ var TIP_IDS = Object.freeze(TIPS.filter((t) => t.kind !== "notice").map((t) => t.id));
1376
+ var NOTICE_IDS = Object.freeze(TIPS.filter((t) => t.kind === "notice").map((t) => t.id));
1377
+ var ALL_TIPS = "*";
1378
+ var NO_EXPLANATIONS = "-explanations";
1379
+ var FIELDS_COLLAPSED = "-fields";
1380
+ var SWITCHES = Object.freeze([ALL_TIPS, NO_EXPLANATIONS, FIELDS_COLLAPSED]);
1381
+ function fieldsCollapsed(session, forced, dismissed) {
1382
+ return session ?? (forced === "collapsed" || forced === "open" ? forced === "collapsed" : dismissed.includes(FIELDS_COLLAPSED));
1383
+ }
1384
+ var SECTIONS = Object.freeze({
1385
+ // a value's menu
1386
+ summarize: true,
1387
+ showAs: true,
1388
+ format: false,
1389
+ highlight: false,
1390
+ move: false,
1391
+ // a field's menu on Rows or Columns
1392
+ sort: true,
1393
+ groupBy: true,
1394
+ bins: true,
1395
+ topN: true,
1396
+ filters: true,
1397
+ // the toolbar's menus
1398
+ totals: true,
1399
+ help: true,
1400
+ // the Export menus (the toolbar's and the drill-down's)
1401
+ exportDownload: true,
1402
+ exportCopy: true,
1403
+ thisView: true,
1404
+ sharedViews: true,
1405
+ myViews: true,
1406
+ share: false,
1407
+ chartType: true,
1408
+ chartDisplay: false
1409
+ });
1410
+ function sectionOpen(id, dismissed) {
1411
+ if (dismissed.includes(`open:${id}`)) {
1412
+ return true;
1413
+ }
1414
+ if (dismissed.includes(`closed:${id}`)) {
1415
+ return false;
1416
+ }
1417
+ return Object.hasOwn(SECTIONS, id) ? SECTIONS[id] : true;
1418
+ }
1419
+ function withSection(dismissed, id, open) {
1420
+ const rest = dismissed.filter((d) => d !== `open:${id}` && d !== `closed:${id}`);
1421
+ const def = Object.hasOwn(SECTIONS, id) ? SECTIONS[id] : true;
1422
+ return open === def ? rest : [...rest, `${open ? "open" : "closed"}:${id}`];
1423
+ }
1424
+ var isSection = (id) => /^(open|closed):/.test(id) && Object.hasOwn(SECTIONS, id.slice(id.indexOf(":") + 1));
1425
+ var keptOnReset = (id) => SWITCHES.includes(id) || isSection(id);
1426
+ function helpSwitch(forced, dismissed, off = NO_EXPLANATIONS) {
1427
+ if (forced === "on" || forced === "off") {
1428
+ return { on: forced === "on", user: false };
1429
+ }
1430
+ return { on: !dismissed.includes(off), user: true };
1431
+ }
1432
+ var SHORTCUTS = Object.freeze([
1433
+ { keys: ["Mod", "Z"], text: "undo" },
1434
+ { keys: ["Mod", "Shift", "Z"], text: "redo" },
1435
+ { keys: ["Arrow keys"], text: "move" },
1436
+ { keys: ["Enter"], text: "open" },
1437
+ { keys: ["Space"], text: "drag" },
1438
+ { keys: ["Escape"], text: "close" },
1439
+ { keys: ["Arrow keys"], text: "fields" },
1440
+ { keys: ["Shift", "F10"], text: "fieldMenu" }
1441
+ ]);
1442
+ 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 } }) {
1443
+ const leaves = (nodes, depth) => result && depth > 0 ? nodes.reduce((n, node) => n + (node.depth === depth ? 1 : 0), 0) : 1;
1444
+ return {
1445
+ view,
1446
+ empty,
1447
+ failed: failed || !result,
1448
+ typeOf,
1449
+ encoded,
1450
+ fields,
1451
+ rowLeaves: result ? leaves(result.rowNodes, result.rowFields.length) : 0,
1452
+ colLeaves: result ? leaves(result.colNodes, result.colFields.length) : 0,
1453
+ matched: result ? result.rows.length : 0,
1454
+ dataRows: encoded.length,
1455
+ series,
1456
+ tableShown,
1457
+ drilled,
1458
+ changes,
1459
+ dragAt,
1460
+ canSave,
1461
+ savedAt,
1462
+ chartPlan: chartPlan2
1463
+ };
1464
+ }
1465
+ function activeTips(ctx, { allowed, dismissed, limit = TIP_LIMIT }) {
1466
+ const gone = new Set(dismissed);
1467
+ const tipsOff = allowed === "off" || gone.has(ALL_TIPS);
1468
+ const out = [];
1469
+ let tips = 0;
1470
+ for (const entry of TIPS) {
1471
+ const notice = entry.kind === "notice";
1472
+ if (!notice && (tipsOff || tips >= limit || Array.isArray(allowed) && !allowed.includes(entry.id) || gone.has(entry.id))) {
1473
+ continue;
1474
+ }
1475
+ const params = entry.when(ctx);
1476
+ if (params) {
1477
+ out.push({ id: entry.id, params, entry });
1478
+ tips += notice ? 0 : 1;
1479
+ }
1480
+ }
1481
+ return out;
1482
+ }
1483
+ function tipText(id, params, labels, locale) {
1484
+ const texts = labels.tips;
1485
+ const values = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, typeof v === "number" ? v.toLocaleString(locale) : v]));
1486
+ if (id === "showAs") {
1487
+ const per = texts.showAs;
1488
+ return Object.hasOwn(per, params.type) ? per[params.type] : "";
1489
+ }
1490
+ if (id === "top") {
1491
+ return fill(params.bottom ? texts.bottom : texts.top, values);
1492
+ }
1493
+ if (id === "dateUngrouped") {
1494
+ return fill(texts.dateUngrouped, { ...values, unit: labels.units[params.unit] ?? params.unit });
1495
+ }
1496
+ return Object.hasOwn(texts, id) && typeof texts[id] === "string" ? fill(texts[id], values) : "";
1497
+ }
1498
+ function tipActionText(entry, params, labels) {
1499
+ if (!entry.action) {
1500
+ return "";
1501
+ }
1502
+ const text = Object.hasOwn(labels.tipActions, entry.action) ? labels.tipActions[entry.action] : "";
1503
+ return fill(text, { unit: labels.units[params.unit] ?? params.unit ?? "" });
1504
+ }
1505
+ function allowedTips(value) {
1506
+ if (value === "off" || value === false) {
1507
+ return "off";
1508
+ }
1509
+ const list = typeof value === "string" && value.trim() !== "on" && value.trim() !== "" ? value.split(",") : Array.isArray(value) ? value : null;
1510
+ if (!list) {
1511
+ return "on";
1512
+ }
1513
+ return list.map((id) => String(id).trim()).filter((id) => TIP_IDS.includes(id));
1514
+ }
1515
+ function cleanDismissed(value) {
1516
+ return Array.isArray(value) ? [...new Set(value.filter((id) => typeof id === "string" && (SWITCHES.includes(id) || TIP_IDS.includes(id) || isSection(id))))] : [];
1517
+ }
1518
+ var storageName = (key) => `pivotkit:tips:${key}`;
1519
+ function readStored(key, storage) {
1520
+ return key ? readItem(storageName(key), storage) : null;
1521
+ }
1522
+ function parseStored(raw) {
1523
+ if (!raw) {
1524
+ return [];
1525
+ }
1526
+ try {
1527
+ return cleanDismissed(JSON.parse(raw));
1528
+ } catch {
1529
+ return [];
1530
+ }
1531
+ }
1532
+ function subscribeStored(key, callback) {
1533
+ return key ? subscribeItem(storageName(key), callback) : () => {
1534
+ };
1535
+ }
1536
+ function writeDismissed(key, storage, dismissed) {
1537
+ if (key && storage) {
1538
+ writeItem(storageName(key), storage, dismissed.length ? JSON.stringify(dismissed) : null);
1539
+ }
1540
+ }
1541
+ function withoutFilters(view) {
1542
+ return { ...view, filters: filterZoneFields(view).map((field) => ({ field, type: "exclude", items: [] })) };
1543
+ }
1544
+
1545
+ // src/share.js
1546
+ import { VIEW_FILE_LIMITS, fromViewFile, normalize } from "pivotkit-core";
1547
+ var linkModule = null;
1548
+ var linkLoaded = null;
1549
+ function loadLink() {
1550
+ linkModule ??= import("pivotkit-core/link").then((m) => {
1551
+ linkLoaded = m;
1552
+ return m;
1553
+ });
1554
+ return linkModule;
1555
+ }
1556
+ var linkNow = () => linkLoaded;
1557
+ function linkParam(storageKey) {
1558
+ return storageKey ? `pivot-${storageKey}` : "pivot";
1559
+ }
1560
+ var entries = (fragment) => fragment ? fragment.split("&") : [];
1561
+ var isEntry = (entry, param) => entry.startsWith(`${encodeURIComponent(param)}=`);
1562
+ function readLinkParam(hash, param) {
1563
+ const text = typeof hash === "string" ? hash.replace(/^#/, "") : "";
1564
+ const entry = entries(text).find((e) => isEntry(e, param));
1565
+ const value = entry ? entry.slice(encodeURIComponent(param).length + 1) : "";
1566
+ return value ? value : null;
1567
+ }
1568
+ function withLinkParam(url, param, encoded) {
1569
+ const at = url.indexOf("#");
1570
+ const base = at === -1 ? url : url.slice(0, at);
1571
+ const kept = entries(at === -1 ? "" : url.slice(at + 1)).filter((e) => !isEntry(e, param));
1572
+ const next = encoded ? [...kept, `${encodeURIComponent(param)}=${encoded}`] : kept;
1573
+ return next.length ? `${base}#${next.join("&")}` : base;
1574
+ }
1575
+ function shareBase(shareLink, here) {
1576
+ if (shareLink === true) {
1577
+ if (!here) {
1578
+ return null;
1579
+ }
1580
+ try {
1581
+ const url = new URL(here);
1582
+ return `${url.origin}${url.pathname}${url.hash}`;
1583
+ } catch {
1584
+ return null;
1585
+ }
1586
+ }
1587
+ return typeof shareLink === "string" && shareLink.trim() ? shareLink.trim() : null;
1588
+ }
1589
+ var viewStorageName = (key) => `pivotkit:view:${key ?? ""}`;
1590
+ function readStoredView(key, storage) {
1591
+ if (!storage) {
1592
+ return null;
1593
+ }
1594
+ try {
1595
+ return storage.getItem(viewStorageName(key));
1596
+ } catch {
1597
+ return null;
1598
+ }
1599
+ }
1600
+ function writeStoredView(key, storage, view) {
1601
+ if (!storage) {
1602
+ return;
1603
+ }
1604
+ try {
1605
+ storage.setItem(viewStorageName(key), JSON.stringify(view));
1606
+ } catch {
1607
+ }
1608
+ }
1609
+ var VIEW_TEXT_MAX = VIEW_FILE_LIMITS.text;
1610
+ var quoteNames = (names) => {
1611
+ const shown = names.slice(0, 5).map((n) => `\u201C${n.length > 60 ? `${n.slice(0, 59)}\u2026` : n}\u201D`).join(", ");
1612
+ return names.length > 5 ? `${shown} \u2026` : shown;
1613
+ };
1614
+ var FAILED = Object.freeze({ newerFormat: "newer", newerView: "newer" });
1615
+ function viewFromText(text, encoded, options = {}) {
1616
+ return viewFromObject(text, encoded, options);
1617
+ }
1618
+ function viewFromObject(input, encoded, options = {}) {
1619
+ const file = fromViewFile(input, { data: encoded, sourceId: options.sourceId });
1620
+ if (file.failed || !file.view) {
1621
+ const failed = file.failed ?? "notView";
1622
+ return { view: null, issues: file.issues, failed: Object.hasOwn(FAILED, failed) ? FAILED[failed] : failed, file };
1623
+ }
1624
+ const { view, issues } = normalize(file.view, encoded, options.limits ? { limits: options.limits } : void 0);
1625
+ if (issues.some((i) => i.path === "version")) {
1626
+ return { view: null, issues, failed: "newer", file };
1627
+ }
1628
+ return { view, issues, failed: null, file };
1629
+ }
1630
+ function loadCheck(loaded, labels, sources = []) {
1631
+ const fit = loaded.file?.compatible;
1632
+ if (!loaded.view || !fit || fit.ok) {
1633
+ return null;
1634
+ }
1635
+ const lines2 = [];
1636
+ const fileSource = loaded.file?.source;
1637
+ const target = fit.source === "other" && fileSource?.id ? sources.find((s) => s && s.id === fileSource.id) : void 0;
1638
+ if (fit.source === "other") {
1639
+ const name2 = target?.name || fileSource?.name || fileSource?.id;
1640
+ lines2.push(name2 ? fill(labels.loadCheckSource, { source: name2 }) : labels.loadCheckOtherSource);
1641
+ }
1642
+ if (fit.missing.length) {
1643
+ lines2.push(fill(labels.loadCheckMissing, { fields: quoteNames(fit.missing) }));
1644
+ }
1645
+ if (fit.changed.length) {
1646
+ lines2.push(fill(labels.loadCheckChanged, { fields: quoteNames(fit.changed.map((c) => c.name)) }));
1647
+ }
1648
+ return { lines: lines2, switchTo: target ? { id: target.id, name: target.name || target.id } : null };
1649
+ }
1650
+
1651
+ export {
1652
+ CHART_TYPES,
1653
+ SLICE_TYPES,
1654
+ CHART_TYPE_NAMES,
1655
+ chartTypeOf,
1656
+ chartPlan,
1657
+ MAX_CATEGORIES,
1658
+ valueLabel,
1659
+ refLabel,
1660
+ sortText,
1661
+ valueConditionText,
1662
+ groupingName,
1663
+ fieldAction,
1664
+ layoutSummary,
1665
+ DRILL_LIMIT,
1666
+ decodeRow,
1667
+ drillRows,
1668
+ Icon,
1669
+ TYPE_ICON,
1670
+ ZONE_ICON,
1671
+ ClearInput,
1672
+ rootOf,
1673
+ activeIn,
1674
+ useModal,
1675
+ useIsoLayoutEffect,
1676
+ LayerContext,
1677
+ Popover,
1678
+ MenuButton,
1679
+ Option,
1680
+ InfoButton,
1681
+ ZONES,
1682
+ clone,
1683
+ same,
1684
+ filterZoneFields,
1685
+ axisOf,
1686
+ zoneOverLimit,
1687
+ addField,
1688
+ removeAt,
1689
+ moveField,
1690
+ reorder,
1691
+ numberRange,
1692
+ groupField,
1693
+ groupingOf,
1694
+ sourceOf,
1695
+ setSort,
1696
+ withHostOrders,
1697
+ sortOf,
1698
+ sortEntry,
1699
+ headerSortTarget,
1700
+ headerSortState,
1701
+ nextHeaderSort,
1702
+ filtersOf,
1703
+ selectedItems,
1704
+ numericResult,
1705
+ sameRef,
1706
+ toggleCollapsed,
1707
+ rowFolding,
1708
+ setCollapsed,
1709
+ setTotal,
1710
+ setDisplay,
1711
+ setChart,
1712
+ setChartDisplay,
1713
+ swapAxes,
1714
+ isEmptyView,
1715
+ HelpContext,
1716
+ localStore,
1717
+ readItem,
1718
+ subscribeItem,
1719
+ writeItem,
1720
+ ALL_TIPS,
1721
+ NO_EXPLANATIONS,
1722
+ FIELDS_COLLAPSED,
1723
+ fieldsCollapsed,
1724
+ sectionOpen,
1725
+ withSection,
1726
+ isSection,
1727
+ keptOnReset,
1728
+ helpSwitch,
1729
+ SHORTCUTS,
1730
+ tipContext,
1731
+ activeTips,
1732
+ tipText,
1733
+ tipActionText,
1734
+ allowedTips,
1735
+ cleanDismissed,
1736
+ readStored,
1737
+ parseStored,
1738
+ subscribeStored,
1739
+ writeDismissed,
1740
+ withoutFilters,
1741
+ loadLink,
1742
+ linkNow,
1743
+ linkParam,
1744
+ readLinkParam,
1745
+ withLinkParam,
1746
+ shareBase,
1747
+ readStoredView,
1748
+ writeStoredView,
1749
+ viewFromText,
1750
+ viewFromObject,
1751
+ loadCheck
1752
+ };