pivotkit-react 0.0.0-stage → 0.1.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 (71) hide show
  1. package/CHANGELOG.md +300 -0
  2. package/LICENSE +21 -0
  3. package/README.md +327 -2
  4. package/dist/chunks/chunk-C32TYSHG.js +441 -0
  5. package/dist/chunks/chunk-ILHFIV2P.js +784 -0
  6. package/dist/chunks/chunk-KKJO36W5.js +1833 -0
  7. package/dist/chunks/chunk-XYP47DJ3.js +123 -0
  8. package/dist/echarts.js +262 -0
  9. package/dist/index.js +3390 -0
  10. package/dist/labels.js +12 -0
  11. package/dist/menus.js +1085 -0
  12. package/dist/styles.css +2447 -0
  13. package/package.json +70 -4
  14. package/types/PivotReport.d.ts +20 -0
  15. package/types/all-labels.d.ts +5 -0
  16. package/types/chart-decorate.d.ts +16 -0
  17. package/types/chart-options.d.ts +23 -0
  18. package/types/chart-summary.d.ts +12 -0
  19. package/types/chart-tooltip.d.ts +38 -0
  20. package/types/chart-types.d.ts +152 -0
  21. package/types/chart.d.ts +39 -0
  22. package/types/chip-menus.d.ts +32 -0
  23. package/types/clear-input.d.ts +20 -0
  24. package/types/dnd-moves.d.ts +45 -0
  25. package/types/dnd.d.ts +101 -0
  26. package/types/dom.d.ts +52 -0
  27. package/types/drill-export.d.ts +42 -0
  28. package/types/drill-panel.d.ts +39 -0
  29. package/types/drill.d.ts +62 -0
  30. package/types/echarts.d.ts +4 -0
  31. package/types/export-run.d.ts +59 -0
  32. package/types/field-info.d.ts +34 -0
  33. package/types/fields.d.ts +32 -0
  34. package/types/files.d.ts +27 -0
  35. package/types/filter.d.ts +21 -0
  36. package/types/icons.d.ts +76 -0
  37. package/types/index.d.ts +536 -0
  38. package/types/info.d.ts +34 -0
  39. package/types/iso.d.ts +2 -0
  40. package/types/labels.d.ts +721 -0
  41. package/types/lazy-menus.d.ts +16 -0
  42. package/types/menu-labels.d.ts +255 -0
  43. package/types/menus.d.ts +7 -0
  44. package/types/names.d.ts +80 -0
  45. package/types/numbers.d.ts +13 -0
  46. package/types/overflow.d.ts +59 -0
  47. package/types/place.d.ts +43 -0
  48. package/types/popover.d.ts +89 -0
  49. package/types/rove.d.ts +20 -0
  50. package/types/section.d.ts +42 -0
  51. package/types/share.d.ts +123 -0
  52. package/types/skeleton.d.ts +9 -0
  53. package/types/storage.d.ts +24 -0
  54. package/types/table.d.ts +23 -0
  55. package/types/templates.d.ts +40 -0
  56. package/types/theme.d.ts +24 -0
  57. package/types/tip-list.d.ts +20 -0
  58. package/types/tips.d.ts +298 -0
  59. package/types/toasts.d.ts +26 -0
  60. package/types/toolbar-panels.d.ts +90 -0
  61. package/types/toolbar.d.ts +5 -0
  62. package/types/use-big-result.d.ts +29 -0
  63. package/types/use-export.d.ts +7 -0
  64. package/types/use-theme.d.ts +11 -0
  65. package/types/use-view-history.d.ts +34 -0
  66. package/types/version.d.ts +2 -0
  67. package/types/view-history.d.ts +89 -0
  68. package/types/view-ops.d.ts +344 -0
  69. package/types/view-store.d.ts +52 -0
  70. package/types/virtual.d.ts +44 -0
  71. package/types/zones.d.ts +42 -0
package/dist/index.js ADDED
@@ -0,0 +1,3390 @@
1
+ import {
2
+ ALL_TIPS,
3
+ ClearInput,
4
+ DRILL_LIMIT,
5
+ FIELDS_COLLAPSED,
6
+ HelpContext,
7
+ Icon,
8
+ InfoButton,
9
+ LayerContext,
10
+ MenuButton,
11
+ NO_EXPLANATIONS,
12
+ Option,
13
+ Popover,
14
+ TYPE_ICON,
15
+ ZONES,
16
+ ZONE_ICON,
17
+ activeIn,
18
+ activeTips,
19
+ addField,
20
+ allowedTips,
21
+ cleanDismissed,
22
+ copyText,
23
+ drillRows,
24
+ drillTable,
25
+ fieldAction,
26
+ fieldsCollapsed,
27
+ filterZoneFields,
28
+ filtersOf,
29
+ groupField,
30
+ groupingName,
31
+ helpSwitch,
32
+ isEmptyView,
33
+ keptOnReset,
34
+ layoutSummary,
35
+ localStore,
36
+ moveField,
37
+ numberRange,
38
+ parseStored,
39
+ readItem,
40
+ readStored,
41
+ refLabel,
42
+ removeAt,
43
+ rootOf,
44
+ rowFolding,
45
+ safeFileName,
46
+ saveBlob,
47
+ sectionOpen,
48
+ selectedItems,
49
+ setChart,
50
+ setChartDisplay,
51
+ setCollapsed,
52
+ setDisplay,
53
+ setTotal,
54
+ sortOf,
55
+ sourceOf,
56
+ subscribeItem,
57
+ subscribeStored,
58
+ swapAxes,
59
+ tipActionText,
60
+ tipContext,
61
+ tipText,
62
+ toggleCollapsed,
63
+ useIsoLayoutEffect,
64
+ useModal,
65
+ valueConditionText,
66
+ valueLabel,
67
+ withHostOrders,
68
+ withSection,
69
+ withoutFilters,
70
+ writeDismissed,
71
+ writeItem,
72
+ zoneOverLimit
73
+ } from "./chunks/chunk-KKJO36W5.js";
74
+ import {
75
+ CHART_TYPES,
76
+ MAX_CATEGORIES,
77
+ chartPlan,
78
+ chartTypeOf
79
+ } from "./chunks/chunk-XYP47DJ3.js";
80
+ import {
81
+ LABELS,
82
+ errorText,
83
+ fill,
84
+ messageOf,
85
+ plural,
86
+ resolveLabels
87
+ } from "./chunks/chunk-ILHFIV2P.js";
88
+
89
+ // src/PivotReport.jsx
90
+ import React11, { useCallback as useCallback9, useEffect as useEffect10, useId as useId4, useMemo as useMemo7, useRef as useRef10, useState as useState11, useSyncExternalStore as useSyncExternalStore3 } from "react";
91
+ import { computePivot, encode, normalize as normalize3, fieldLabel as fieldLabel3, findNode, suggestDateUnit, toGrid, toSeries, toViewFile, viewFields, viewFileName, viewFileText } from "pivotkit-core";
92
+
93
+ // src/chart.jsx
94
+ import React, { useEffect, useId, useRef, useState } from "react";
95
+ import { fieldLabel, toEChartsOption } from "pivotkit-core";
96
+
97
+ // src/chart-summary.js
98
+ import { formatter } from "pivotkit-core";
99
+ var OLD_COUNTS = new RegExp("\\{(categories|series)\\}\\s*\\p{L}", "u");
100
+ function counts(s, labels, locale) {
101
+ const categories = s.categoryCount ?? s.categories.length;
102
+ const series = s.series.length;
103
+ if (OLD_COUNTS.test(labels.chartCounts)) {
104
+ return fill(labels.chartCounts, { categories: categories.toLocaleString(locale), series: series.toLocaleString(locale) });
105
+ }
106
+ return fill(labels.chartCounts, {
107
+ categories: plural(labels.chartCategories, categories, { lang: labels.lang, locale }),
108
+ series: plural(labels.chartSeries, series, { lang: labels.lang, locale })
109
+ });
110
+ }
111
+ function chartSummary(s, { type, rows, valueNames, labels, locale }) {
112
+ const parts = [
113
+ fill(labels.chartSummary, { type: labels.chartTypes[type] ?? type, values: valueNames.join(", "), categories: rows.length ? rows.join(" / ") : labels.categories }),
114
+ counts(s, labels, locale)
115
+ ];
116
+ let max = null;
117
+ let min = null;
118
+ s.series.forEach((series, si) => {
119
+ series.data.forEach((v, ci) => {
120
+ if (typeof v !== "number") {
121
+ return;
122
+ }
123
+ if (!max || v > max.v) {
124
+ max = { v, si, ci };
125
+ }
126
+ if (!min || v < min.v) {
127
+ min = { v, si, ci };
128
+ }
129
+ });
130
+ });
131
+ if (max && min) {
132
+ const where = (p) => s.series.length > 1 && s.series[p.si].name ? `${s.categories[p.ci]} / ${s.series[p.si].name}` : s.categories[p.ci];
133
+ const text = (p) => formatter(s.series[p.si].format, { locale })(p.v);
134
+ parts.push(fill(labels.chartExtremes, { max: text(max), maxAt: where(max), min: text(min), minAt: where(min) }));
135
+ }
136
+ parts.push(labels.chartTableHint);
137
+ return parts.join(" ");
138
+ }
139
+
140
+ // src/theme.js
141
+ function resolveTheme(wanted, htmlTheme, prefersDark) {
142
+ if (wanted === "light" || wanted === "dark") {
143
+ return wanted;
144
+ }
145
+ if (htmlTheme === "light" || htmlTheme === "dark") {
146
+ return htmlTheme;
147
+ }
148
+ return prefersDark ? "dark" : "light";
149
+ }
150
+ var CHART_COLORS = 8;
151
+ function chartThemeFrom(style) {
152
+ const v = (name) => style.getPropertyValue(name).trim();
153
+ const colors = [];
154
+ for (let i = 1; i <= CHART_COLORS; i++) {
155
+ const c = v(`--pk-chart-${i}`);
156
+ if (c) {
157
+ colors.push(c);
158
+ }
159
+ }
160
+ const theme = {
161
+ colors,
162
+ textColor: v("--pk-muted") || void 0,
163
+ axisColor: v("--pk-border") || void 0,
164
+ gridColor: v("--pk-grid") || v("--pk-border") || void 0,
165
+ fontFamily: v("font-family") || void 0,
166
+ backgroundColor: "transparent"
167
+ };
168
+ const low = v("--pk-heat-low");
169
+ const high = v("--pk-heat-high");
170
+ if (low && high) {
171
+ theme.heatmapColors = [low, high];
172
+ }
173
+ return theme;
174
+ }
175
+
176
+ // src/chart.jsx
177
+ var loading = null;
178
+ function loadECharts() {
179
+ loading ??= import("./echarts.js");
180
+ return loading;
181
+ }
182
+ function PivotChart({ result, series, labels, locale, themeName, root, onInstance, onPoint, valueNames, chartOptions, plan }) {
183
+ const el = useRef(
184
+ /** @type {HTMLDivElement | null} */
185
+ null
186
+ );
187
+ const chart = useRef(
188
+ /** @type {any} */
189
+ null
190
+ );
191
+ const [ready, setReady] = useState(false);
192
+ const [failed, setFailed] = useState(
193
+ /** @type {string | null} */
194
+ null
195
+ );
196
+ const [box, setBox] = useState("");
197
+ const [every, setEvery] = useState(1);
198
+ const summaryId = useId();
199
+ const type = plan ? plan.name : chartTypeOf(result.view.chart);
200
+ const drawAs = plan ? plan.chart : null;
201
+ const latest = useRef({ series, onPoint, onInstance, type });
202
+ const lib = useRef(
203
+ /** @type {any} */
204
+ null
205
+ );
206
+ const warned2 = useRef(
207
+ /** @type {unknown} */
208
+ void 0
209
+ );
210
+ useEffect(() => {
211
+ latest.current = { series, onPoint, onInstance, type };
212
+ });
213
+ useEffect(() => {
214
+ let disposed = false;
215
+ let ro = null;
216
+ loadECharts().then(
217
+ (echarts) => {
218
+ if (disposed || !el.current) {
219
+ return;
220
+ }
221
+ lib.current = echarts;
222
+ const instance = echarts.init(el.current, null, { renderer: "canvas" });
223
+ chart.current = instance;
224
+ latest.current.onInstance(instance);
225
+ instance.on("click", (p) => {
226
+ const { series: s, onPoint: cb } = latest.current;
227
+ const kind = p.seriesType;
228
+ if (!s || kind === "pie") {
229
+ return;
230
+ }
231
+ const seriesEntry = kind === "heatmap" ? s.series.filter((x) => x.valueIndex === s.series[0]?.valueIndex)[p.value?.[0]] : s.series[p.seriesIndex];
232
+ const row = kind === "heatmap" ? p.value?.[1] : p.dataIndex;
233
+ if (seriesEntry && s.categoryPaths[row]) {
234
+ cb({ rowPath: s.categoryPaths[row], colPath: seriesEntry.colPath, valueIndex: seriesEntry.valueIndex, value: kind === "heatmap" ? p.value[2] : p.value });
235
+ }
236
+ });
237
+ ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => {
238
+ instance.resize();
239
+ setBox(`${instance.getWidth()}x${instance.getHeight()}`);
240
+ }) : null;
241
+ ro?.observe(el.current);
242
+ setReady(true);
243
+ },
244
+ (err) => setFailed(String(err && err.message ? err.message : err))
245
+ );
246
+ return () => {
247
+ disposed = true;
248
+ ro?.disconnect();
249
+ chart.current?.dispose();
250
+ chart.current = null;
251
+ latest.current.onInstance(null);
252
+ };
253
+ }, []);
254
+ useEffect(() => {
255
+ if (!ready || !chart.current || !root.current) {
256
+ return;
257
+ }
258
+ const style = getComputedStyle(root.current);
259
+ const option = toEChartsOption(result, { theme: chartThemeFrom(style), locale, labels: labels.core, maxCategories: MAX_CATEGORIES, ...series ? { series } : {}, ...drawAs ? { chart: drawAs } : {} });
260
+ const { axisEvery, ...drawn } = lib.current.decorate(option, style, chart.current.getHeight(), root.current.ownerDocument, chart.current.getWidth(), { categoryNames: series?.categories, axisLabels: result.view.chart.axisLabels });
261
+ setEvery(axisEvery);
262
+ const clean = chartOptions ? lib.current.cleanChartOptions(chartOptions) : null;
263
+ if (clean?.problems.length && warned2.current !== chartOptions) {
264
+ warned2.current = chartOptions;
265
+ console.warn(`pivotkit: chartOptions entries left out (only plain JSON, and no markup, addresses or text templates): ${clean.problems.slice(0, 5).join("; ")}${clean.problems.length > 5 ? `; and ${clean.problems.length - 5} more` : ""}`);
266
+ }
267
+ chart.current.setOption(clean?.options ? lib.current.mergeChartOptions(drawn, clean.options) : drawn, { notMerge: true });
268
+ }, [ready, result, series, labels, locale, themeName, root, box, chartOptions, drawAs]);
269
+ const empty = result.view.values.length === 0;
270
+ const summary = series && !empty ? chartSummary(series, { type, rows: result.view.rows.map((f) => fieldLabel(f, labels.core)), valueNames, labels, locale }) : labels.noChartData;
271
+ return /* @__PURE__ */ React.createElement("div", { className: "pk-chart-wrap" }, /* @__PURE__ */ React.createElement("div", { className: "pk-chart-box" }, /* @__PURE__ */ React.createElement("div", { ref: el, className: "pk-chart", "data-testid": "pivot-chart", role: "img", "aria-label": result.view.chart.title ? `${labels.chart}: ${result.view.chart.title}` : labels.chart, "aria-describedby": summaryId }), /* @__PURE__ */ React.createElement("p", { id: summaryId, className: "pk-sr", "data-testid": "chart-summary" }, summary), !ready && !failed ? /* @__PURE__ */ React.createElement("div", { className: "pk-chart-note" }, labels.loadingChart) : null, failed ? /* @__PURE__ */ React.createElement("div", { className: "pk-chart-note pk-error" }, failed) : null, ready && empty ? /* @__PURE__ */ React.createElement("div", { className: "pk-chart-note" }, labels.noChartData) : null), ready && !empty && every > 1 ? /* @__PURE__ */ React.createElement("p", { className: "pk-axis-note", "data-testid": "axis-note" }, fill(labels.axisEvery, { n: every.toLocaleString(locale) })) : null);
272
+ }
273
+
274
+ // src/dnd.jsx
275
+ import React2, { createContext, useContext, useMemo, useState as useState2 } from "react";
276
+ import {
277
+ DndContext,
278
+ DragOverlay,
279
+ KeyboardSensor,
280
+ MouseSensor,
281
+ TouchSensor,
282
+ closestCenter,
283
+ pointerWithin,
284
+ rectIntersection,
285
+ useDraggable,
286
+ useDroppable,
287
+ useSensor,
288
+ useSensors
289
+ } from "@dnd-kit/core";
290
+ import { SortableContext, rectSortingStrategy, useSortable } from "@dnd-kit/sortable";
291
+
292
+ // src/dnd-moves.js
293
+ var ZONE_ORDER = ["filters", "cols", "rows", "values"];
294
+ function nextTarget(key, targets, over, active) {
295
+ const inZone = (zone2) => targets.filter((t) => t.zone === zone2).sort((a, b) => (a.kind === "zone" ? Infinity : a.index ?? 0) - (b.kind === "zone" ? Infinity : b.index ?? 0));
296
+ const endOf = (zone2) => inZone(zone2).find((t) => t.kind === "zone")?.id ?? null;
297
+ const zone = over?.zone ?? (active.kind === "chip" ? active.zone : null);
298
+ if (!zone) {
299
+ return endOf("rows");
300
+ }
301
+ if (key === "ArrowUp" || key === "ArrowDown") {
302
+ const at = ZONE_ORDER.indexOf(zone) + (key === "ArrowUp" ? -1 : 1);
303
+ return at >= 0 && at < ZONE_ORDER.length ? endOf(ZONE_ORDER[at]) : null;
304
+ }
305
+ const list = inZone(zone);
306
+ let pos = list.findIndex((t) => over && t.zone === over.zone && t.kind === over.kind && t.index === over.index);
307
+ if (pos === -1) {
308
+ const after = list.findIndex((t) => t.kind === "zone" || (t.index ?? 0) > (active.index ?? -1));
309
+ pos = key === "ArrowLeft" ? after : after - 1;
310
+ }
311
+ const next = list[pos + (key === "ArrowLeft" ? -1 : 1)];
312
+ return next ? next.id : null;
313
+ }
314
+ function announcementsOf(labels) {
315
+ const nameOf = (a) => a?.data?.current?.label ?? a?.data?.current?.field ?? "";
316
+ const where = (a, over, at, end, panel) => {
317
+ const d = over?.data?.current;
318
+ const field = nameOf(a);
319
+ if (!d) {
320
+ return null;
321
+ }
322
+ if (d.kind === "panel") {
323
+ return a?.data?.current?.kind === "field" ? null : fill(panel, { field });
324
+ }
325
+ const zone = labels.zones[d.zone] ?? d.zone;
326
+ if (d.kind === "chip") {
327
+ const same = a?.data?.current?.kind === "chip" && a.data.current.zone === d.zone;
328
+ const count = (d.count ?? d.index + 1) + (same ? 0 : 1);
329
+ return fill(at, { field, zone, position: d.index + 1, count });
330
+ }
331
+ return fill(end, { field, zone });
332
+ };
333
+ return {
334
+ onDragStart: ({ active: a }) => fill(labels.dragStart, { field: nameOf(a) }),
335
+ onDragOver: ({ active: a, over }) => where(a, over, labels.dragOverAt, labels.dragOverEnd, labels.dragRemove) ?? fill(labels.dragOverNone, { field: nameOf(a) }),
336
+ onDragEnd: ({ active: a, over }) => where(a, over, labels.dragEndAt, labels.dragEndEnd, labels.toastRemoved) ?? fill(labels.dragCancel, { field: nameOf(a) }),
337
+ onDragCancel: ({ active: a }) => fill(labels.dragCancel, { field: nameOf(a) })
338
+ };
339
+ }
340
+
341
+ // src/dnd.jsx
342
+ var DragContext = createContext({ active: (
343
+ /** @type {DragSource | null} */
344
+ null
345
+ ) });
346
+ function useActiveDrag() {
347
+ return useContext(DragContext).active;
348
+ }
349
+ function collision(args) {
350
+ if (!args.pointerCoordinates) {
351
+ return closestCenter(args);
352
+ }
353
+ const hits = pointerWithin(args);
354
+ const list = hits.length ? hits : rectIntersection(args);
355
+ return [...list].sort((a, b) => Number(String(b.id).startsWith("chip:")) - Number(String(a.id).startsWith("chip:")));
356
+ }
357
+ function keyboardCoordinates(event, { context }) {
358
+ if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.code)) {
359
+ return void 0;
360
+ }
361
+ event.preventDefault();
362
+ const activeId = context.active?.id;
363
+ const targets = context.droppableContainers.getEnabled().filter((entry) => entry && entry.id !== activeId && (entry.data?.current?.kind === "zone" || entry.data?.current?.kind === "chip")).map((entry) => ({ id: entry.id, zone: entry.data.current.zone, kind: entry.data.current.kind, index: entry.data.current.index }));
364
+ const over = context.over?.data?.current ?? null;
365
+ const id = nextTarget(event.code, targets, over, context.active?.data?.current ?? { kind: "field" });
366
+ const rect = id === null ? null : context.droppableRects.get(id);
367
+ const own2 = context.collisionRect;
368
+ if (!rect || !own2) {
369
+ return void 0;
370
+ }
371
+ return { x: rect.left + rect.width / 2 - own2.width / 2, y: rect.top + rect.height / 2 - own2.height / 2 };
372
+ }
373
+ function targetOf(source, over) {
374
+ const data = over?.data?.current;
375
+ if (!data) {
376
+ return null;
377
+ }
378
+ if (data.kind === "panel") {
379
+ return { zone: "panel" };
380
+ }
381
+ if (data.kind === "zone") {
382
+ return { zone: data.zone };
383
+ }
384
+ if (data.kind === "chip") {
385
+ return { zone: data.zone, index: data.index };
386
+ }
387
+ return null;
388
+ }
389
+ function PivotDnd({ labels, onDrop, onDragStart, renderOverlay, children }) {
390
+ const [active, setActive] = useState2(
391
+ /** @type {DragSource | null} */
392
+ null
393
+ );
394
+ const sensors = useSensors(
395
+ useSensor(MouseSensor, { activationConstraint: { distance: 5 } }),
396
+ useSensor(TouchSensor, { activationConstraint: { delay: 180, tolerance: 8 } }),
397
+ useSensor(KeyboardSensor, { coordinateGetter: keyboardCoordinates })
398
+ );
399
+ const accessibility = useMemo(() => ({ screenReaderInstructions: { draggable: labels.dragInstructions }, announcements: announcementsOf(labels) }), [labels]);
400
+ const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
401
+ return /* @__PURE__ */ React2.createElement(
402
+ DndContext,
403
+ {
404
+ sensors,
405
+ collisionDetection: collision,
406
+ accessibility,
407
+ autoScroll: { threshold: { x: 0.15, y: 0.15 }, acceleration: 14 },
408
+ onDragStart: (e) => {
409
+ const source = (
410
+ /** @type {DragSource} */
411
+ e.active.data.current
412
+ );
413
+ setActive(source);
414
+ onDragStart?.(source);
415
+ },
416
+ onDragCancel: () => setActive(null),
417
+ onDragEnd: (e) => {
418
+ const source = (
419
+ /** @type {DragSource} */
420
+ e.active.data.current
421
+ );
422
+ setActive(null);
423
+ const target = targetOf(source, e.over);
424
+ if (source && target) {
425
+ onDrop(source, target);
426
+ }
427
+ }
428
+ },
429
+ /* @__PURE__ */ React2.createElement(DragContext.Provider, { value: { active } }, children),
430
+ /* @__PURE__ */ React2.createElement(DragOverlay, { dropAnimation: reduced ? null : { duration: 160, easing: "cubic-bezier(.2,.8,.2,1)" }, zIndex: 1e3 }, active ? renderOverlay(active) : null)
431
+ );
432
+ }
433
+ function split(listeners) {
434
+ const { onKeyDown, ...pointer } = listeners ?? {};
435
+ return { pointer, keyboard: onKeyDown ? { onKeyDown } : {} };
436
+ }
437
+ function useDragSource(id, source, disabled = false) {
438
+ const { setNodeRef, setActivatorNodeRef, attributes, listeners, isDragging } = useDraggable({ id, data: source, disabled });
439
+ const { pointer, keyboard } = split(listeners);
440
+ return { setNodeRef, isDragging, itemProps: pointer, handleProps: { ref: setActivatorNodeRef, ...attributes, ...keyboard } };
441
+ }
442
+ function useChip(id, source) {
443
+ const { setNodeRef, setActivatorNodeRef, attributes, listeners, isDragging, transform, transition } = useSortable({ id, data: source });
444
+ const { pointer, keyboard } = split(listeners);
445
+ const style = transform ? { transform: `translate3d(${Math.round(transform.x)}px, ${Math.round(transform.y)}px, 0)`, transition } : { transition };
446
+ return { setNodeRef, isDragging, style, itemProps: pointer, handleProps: { ref: setActivatorNodeRef, ...attributes, ...keyboard } };
447
+ }
448
+ function useDropTarget(id, data) {
449
+ const { setNodeRef, isOver } = useDroppable({ id, data });
450
+ return { setNodeRef, isOver };
451
+ }
452
+ function ChipList({ ids, children }) {
453
+ return /* @__PURE__ */ React2.createElement(SortableContext, { items: ids, strategy: rectSortingStrategy }, children);
454
+ }
455
+
456
+ // src/field-info.js
457
+ import { fieldDefaultsFromSchema } from "pivotkit-core";
458
+ var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
459
+ var own = (o, k) => isObject(o) && Object.hasOwn(o, k) ? o[k] : void 0;
460
+ var TYPES = Object.freeze(["string", "number", "date", "boolean"]);
461
+ function fieldInfoOf(fieldDefaults) {
462
+ const map = /* @__PURE__ */ new Map();
463
+ if (!isObject(fieldDefaults)) {
464
+ return map;
465
+ }
466
+ const properties = {};
467
+ for (const name of Object.keys(
468
+ /** @type {object} */
469
+ fieldDefaults
470
+ )) {
471
+ const d = own(fieldDefaults, name);
472
+ const title = own(d, "label");
473
+ const description = own(d, "description");
474
+ const href = own(d, "href");
475
+ if (title !== void 0 || description !== void 0 || href !== void 0) {
476
+ Object.defineProperty(properties, name, { value: { title, description, externalDocs: { url: href } }, enumerable: true });
477
+ }
478
+ }
479
+ if (Object.keys(properties).length === 0) {
480
+ return map;
481
+ }
482
+ const clean = fieldDefaultsFromSchema({ properties }).defaults;
483
+ for (const name of Object.keys(clean)) {
484
+ const { label, description, href } = clean[name];
485
+ const info = {};
486
+ if (label) {
487
+ info.label = label;
488
+ }
489
+ if (description) {
490
+ info.description = description;
491
+ if (href) {
492
+ info.href = href;
493
+ }
494
+ }
495
+ if (Object.keys(info).length) {
496
+ map.set(name.toLowerCase(), info);
497
+ }
498
+ }
499
+ return map;
500
+ }
501
+ function displayNames(info, fieldNames = []) {
502
+ const spelling = new Map(fieldNames.map((n) => [String(n).toLowerCase(), String(n)]));
503
+ const uses = /* @__PURE__ */ new Map();
504
+ for (const entry of info.values()) {
505
+ if (entry.label) {
506
+ const l = entry.label.toLowerCase();
507
+ uses.set(l, (uses.get(l) ?? 0) + 1);
508
+ }
509
+ }
510
+ const out = {};
511
+ for (const [key, entry] of info) {
512
+ if (!entry.label) {
513
+ continue;
514
+ }
515
+ const l = entry.label.toLowerCase();
516
+ const clash = uses.get(l) > 1 || spelling.has(l) && l !== key;
517
+ const value = clash ? `${entry.label} (${spelling.get(key) ?? key})` : entry.label;
518
+ Object.defineProperty(out, key, { value, enumerable: true });
519
+ }
520
+ return Object.keys(out).length ? out : null;
521
+ }
522
+ function typesOf(fieldDefaults) {
523
+ if (!isObject(fieldDefaults)) {
524
+ return null;
525
+ }
526
+ const out = {};
527
+ for (const name of Object.keys(
528
+ /** @type {object} */
529
+ fieldDefaults
530
+ )) {
531
+ const type = own(own(fieldDefaults, name), "type");
532
+ if (typeof type === "string" && TYPES.includes(type)) {
533
+ Object.defineProperty(out, name, { value: type, enumerable: true });
534
+ }
535
+ }
536
+ return Object.keys(out).length ? out : null;
537
+ }
538
+ function fieldMatches(field, query, info) {
539
+ if (!query) {
540
+ return true;
541
+ }
542
+ return [field, info?.label, info?.description].some((t) => typeof t === "string" && t.toLowerCase().includes(query));
543
+ }
544
+
545
+ // src/fields.jsx
546
+ import React3, { useCallback, useEffect as useEffect2, useId as useId2, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
547
+
548
+ // src/rove.js
549
+ var SLOTS = Object.freeze(["handle", "name", "info", "menu"]);
550
+ function roveTarget(key, at, rows, slotsOf) {
551
+ if (rows <= 0) {
552
+ return null;
553
+ }
554
+ const fit = (row, slot) => ({ row, slot: slotsOf(row).includes(slot) ? slot : "name" });
555
+ if (key === "ArrowDown" || key === "ArrowUp") {
556
+ return fit(Math.max(0, Math.min(rows - 1, at.row + (key === "ArrowDown" ? 1 : -1))), at.slot);
557
+ }
558
+ if (key === "Home" || key === "End") {
559
+ return fit(key === "Home" ? 0 : rows - 1, at.slot);
560
+ }
561
+ if (key === "ArrowRight" || key === "ArrowLeft") {
562
+ const slots = slotsOf(at.row);
563
+ const i = Math.max(0, slots.indexOf(at.slot));
564
+ return { row: at.row, slot: slots[Math.max(0, Math.min(slots.length - 1, i + (key === "ArrowRight" ? 1 : -1)))] };
565
+ }
566
+ return null;
567
+ }
568
+ var opensMenu = (e) => e.key === "ContextMenu" || e.key === "F10" && e.shiftKey;
569
+
570
+ // src/fields.jsx
571
+ function FieldItem({ field, labels, zones, onAdd, onNote, onFilter, name, info, showInfo, stop }) {
572
+ const { setNodeRef, isDragging, itemProps, handleProps } = useDragSource(`field:${field.name}`, { kind: "field", field: field.name, type: field.type, label: name });
573
+ const item = useRef2(
574
+ /** @type {HTMLLIElement | null} */
575
+ null
576
+ );
577
+ const menu = useRef2(
578
+ /** @type {HTMLButtonElement | null} */
579
+ null
580
+ );
581
+ const ref = (el) => {
582
+ item.current = el;
583
+ setNodeRef(el);
584
+ };
585
+ const typeLabel = labels.types[field.type] ?? field.type;
586
+ const action = fieldAction(name, field.type, zones, labels);
587
+ const describedBy = useId2();
588
+ const slots = SLOTS.filter((x) => x !== "info" || info && showInfo);
589
+ const own2 = stop && slots.includes(stop) ? stop : stop ? "name" : null;
590
+ const tab = (slot) => own2 === slot ? 0 : -1;
591
+ return /* @__PURE__ */ React3.createElement("li", { className: `pk-field${isDragging ? " pk-dragging" : ""}${zones.length ? " pk-placed" : ""}`, ref, ...itemProps, "data-field": field.name }, /* @__PURE__ */ React3.createElement("span", { className: "pk-handle", ...handleProps, tabIndex: tab("handle"), "data-pk-slot": "handle", "aria-label": fill(labels.dragHandle, { field: name }), title: labels.dragIntoZone, onClick: () => menu.current?.click() }, /* @__PURE__ */ React3.createElement(Icon, { name: "grip", size: 18 })), /* @__PURE__ */ React3.createElement("span", { className: `pk-type pk-type-${field.type}`, title: typeLabel }, /* @__PURE__ */ React3.createElement(Icon, { name: (
592
+ /** @type {any} */
593
+ TYPE_ICON[field.type] ?? "text"
594
+ ), size: 14 }), /* @__PURE__ */ React3.createElement("span", { className: "pk-sr" }, typeLabel)), /* @__PURE__ */ React3.createElement(
595
+ "button",
596
+ {
597
+ type: "button",
598
+ className: "pk-field-name",
599
+ tabIndex: tab("name"),
600
+ "data-pk-slot": "name",
601
+ onClick: () => {
602
+ if (action.kind) {
603
+ onAdd(field.name, action.zone);
604
+ } else {
605
+ onNote(fill(labels.alreadyIn, { field: name, zone: labels.zones[action.zone] }));
606
+ }
607
+ },
608
+ title: action.description ? `${action.name} \u2013 ${action.description}` : void 0,
609
+ "aria-label": zones.length ? action.name : void 0,
610
+ "aria-description": info ? void 0 : action.description || void 0,
611
+ "aria-describedby": info ? describedBy : void 0
612
+ },
613
+ /* @__PURE__ */ React3.createElement("span", { className: "pk-field-title", title: name }, name)
614
+ ), info ? /* @__PURE__ */ React3.createElement("span", { id: describedBy, className: "pk-sr" }, [action.description, info.description].filter(Boolean).join(". ")) : null, zones.length ? /* @__PURE__ */ React3.createElement("span", { className: "pk-badges", "aria-hidden": "true" }, zones.map((z) => /* @__PURE__ */ React3.createElement("span", { key: z, className: `pk-badge pk-badge-${z}`, "aria-hidden": "true", title: fill(labels.inZone, { zone: labels.zones[z] }) }, /* @__PURE__ */ React3.createElement(Icon, { name: (
615
+ /** @type {any} */
616
+ ZONE_ICON[z]
617
+ ), size: 12 })))) : null, info && showInfo ? /* @__PURE__ */ React3.createElement(InfoButton, { info, name, labels, tabIndex: tab("info"), slot: "info" }) : null, /* @__PURE__ */ React3.createElement(MenuButton, { label: fill(labels.fieldMenu, { field: name }), icon: "more", className: "pk-icon-btn pk-field-menu", testId: `field-menu-${field.name}`, buttonRef: menu, tabIndex: tab("menu"), slot: "menu" }, (close) => /* @__PURE__ */ React3.createElement(React3.Fragment, null, ZONES.map((zone) => /* @__PURE__ */ React3.createElement(
618
+ Option,
619
+ {
620
+ key: zone,
621
+ inMenu: true,
622
+ icon: zone === "values" ? "sigma" : zone === "filters" ? "filter" : zone,
623
+ onSelect: () => {
624
+ close();
625
+ onAdd(field.name, zone);
626
+ }
627
+ },
628
+ fill(labels.addTo, { zone: labels.zones[zone] })
629
+ )), zones.length === 0 && onFilter ? /* @__PURE__ */ React3.createElement(
630
+ Option,
631
+ {
632
+ inMenu: true,
633
+ icon: "filter",
634
+ onSelect: () => {
635
+ close();
636
+ onFilter(field.name, item.current);
637
+ },
638
+ testId: `field-filter-${field.name}`
639
+ },
640
+ labels.filter
641
+ ) : null)));
642
+ }
643
+ function FieldPanel({ fields, placed, labels, onAdd, onNote, onFilter, drawer, open, onClose, nameOf, info, showInfo = true, onSkip, collapsed = false, onCollapse }) {
644
+ const [query, setQuery] = useState3("");
645
+ const active = useActiveDrag();
646
+ const { setNodeRef, isOver } = useDropTarget("panel", { kind: "panel" });
647
+ const shown = useMemo2(() => {
648
+ const q = query.trim().toLowerCase();
649
+ return q ? fields.filter((f) => fieldMatches(f.name, q, info.get(f.name.toLowerCase()))) : fields;
650
+ }, [fields, query, info]);
651
+ const removing = active && active.kind !== "field";
652
+ const modal = drawer && open;
653
+ const el = useRef2(
654
+ /** @type {HTMLElement | null} */
655
+ null
656
+ );
657
+ const { onKeyDown } = useModal(el, modal, onClose, "[data-pk-opener='fields']");
658
+ const ref = (node) => {
659
+ el.current = node;
660
+ setNodeRef(node);
661
+ };
662
+ const refocus = useRef2(
663
+ /** @type {string | null} */
664
+ null
665
+ );
666
+ const rail = collapsed && !drawer;
667
+ useEffect2(() => {
668
+ const to = refocus.current;
669
+ refocus.current = null;
670
+ if (to && el.current) {
671
+ el.current.querySelector(`[data-pk-focus="${to}"], [data-pk-focus="${to}"] input`)?.focus();
672
+ }
673
+ }, [rail]);
674
+ const fold = (next, to) => {
675
+ refocus.current = to;
676
+ onCollapse?.(next);
677
+ };
678
+ const [stop, setStop] = useState3(
679
+ /** @type {{ field: string, slot: string } | null} */
680
+ null
681
+ );
682
+ const current = stop && shown.some((f) => f.name === stop.field) ? stop : shown.length ? { field: shown[0].name, slot: "name" } : null;
683
+ const list = useRef2(
684
+ /** @type {HTMLUListElement | null} */
685
+ null
686
+ );
687
+ const keysId = useId2();
688
+ const onFocus = useCallback((e) => {
689
+ const control = (
690
+ /** @type {HTMLElement} */
691
+ e.target.closest?.("[data-pk-slot]")
692
+ );
693
+ const row = control?.closest("[data-field]");
694
+ if (control && row && list.current?.contains(row)) {
695
+ setStop({ field: row.getAttribute("data-field") ?? "", slot: control.getAttribute("data-pk-slot") ?? "name" });
696
+ }
697
+ }, []);
698
+ const onListKey = (e) => {
699
+ const target = (
700
+ /** @type {HTMLElement} */
701
+ e.target
702
+ );
703
+ if (active || !list.current || !list.current.contains(target)) {
704
+ return;
705
+ }
706
+ const rows = (
707
+ /** @type {HTMLElement[]} */
708
+ [...list.current.querySelectorAll(":scope > [data-field]")]
709
+ );
710
+ const row = target.closest("[data-field]");
711
+ const at = { row: rows.indexOf(
712
+ /** @type {HTMLElement} */
713
+ row
714
+ ), slot: target.closest("[data-pk-slot]")?.getAttribute("data-pk-slot") ?? "name" };
715
+ if (at.row < 0) {
716
+ return;
717
+ }
718
+ if (opensMenu(e)) {
719
+ e.preventDefault();
720
+ rows[at.row].querySelector("[data-pk-slot='menu']")?.click();
721
+ return;
722
+ }
723
+ const slotsOf = (i) => [...rows[i].querySelectorAll("[data-pk-slot]")].map((n) => n.getAttribute("data-pk-slot") ?? "");
724
+ const next = roveTarget(e.key, at, rows.length, slotsOf);
725
+ if (next) {
726
+ e.preventDefault();
727
+ rows[next.row].querySelector(`[data-pk-slot='${next.slot}']`)?.focus();
728
+ }
729
+ };
730
+ if (rail) {
731
+ return /* @__PURE__ */ React3.createElement("aside", { className: `pk-panel pk-rail${removing ? " pk-removing" : ""}${isOver && removing ? " pk-over" : ""}`, ref, "aria-label": labels.panel, "data-testid": "field-rail" }, /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-rail-open", "aria-expanded": false, "aria-label": labels.expandFields, title: labels.expandFields, onClick: () => fold(false, "collapse"), "data-pk-focus": "rail", "data-testid": "expand-fields" }, /* @__PURE__ */ React3.createElement("span", { className: "pk-rail-title", "aria-hidden": "true" }, removing ? labels.dropToRemove : labels.fields)), /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-icon-btn", "aria-label": labels.searchFields, title: labels.searchFields, onClick: () => fold(false, "search"), "data-testid": "rail-search" }, /* @__PURE__ */ React3.createElement(Icon, { name: "search" })), /* @__PURE__ */ React3.createElement("span", { className: "pk-sr", role: "status", "data-testid": "rail-status" }, removing ? labels.dropToRemove : ""));
732
+ }
733
+ return /* @__PURE__ */ React3.createElement(
734
+ "aside",
735
+ {
736
+ className: `pk-panel${removing ? " pk-removing" : ""}${isOver && removing ? " pk-over" : ""}`,
737
+ ref,
738
+ "aria-label": labels.panel,
739
+ role: modal ? "dialog" : void 0,
740
+ "aria-modal": modal ? true : void 0,
741
+ onKeyDown: modal ? onKeyDown : void 0
742
+ },
743
+ onSkip && !drawer ? /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-skip", onClick: onSkip, "data-testid": "skip-to-toolbar" }, labels.skipToToolbar) : null,
744
+ /* @__PURE__ */ React3.createElement("div", { className: "pk-panel-head" }, /* @__PURE__ */ React3.createElement("h2", { className: "pk-panel-title" }, labels.fields), onCollapse && !drawer ? /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-icon-btn", "aria-expanded": true, "aria-label": labels.collapseFields, title: labels.collapseFields, onClick: () => fold(true, "rail"), "data-pk-focus": "collapse", "data-testid": "collapse-fields" }, /* @__PURE__ */ React3.createElement("span", { "aria-hidden": "true" }, "\xAB")) : null, drawer ? /* @__PURE__ */ React3.createElement("button", { type: "button", className: "pk-icon-btn", onClick: onClose, "aria-label": labels.hideFields, title: labels.hideFields }, /* @__PURE__ */ React3.createElement(Icon, { name: "x" })) : null),
745
+ /* @__PURE__ */ React3.createElement("p", { className: "pk-hint" }, labels.fieldsHint),
746
+ /* @__PURE__ */ React3.createElement("label", { className: "pk-search", "data-pk-focus": "search" }, /* @__PURE__ */ React3.createElement(Icon, { name: "search" }), /* @__PURE__ */ React3.createElement("span", { className: "pk-sr" }, labels.searchFields), /* @__PURE__ */ React3.createElement(ClearInput, { type: "search", value: query, placeholder: labels.searchFields, onChange: setQuery, clearLabel: labels.clearText, "data-autofocus": "", "data-testid": "field-search" })),
747
+ /* @__PURE__ */ React3.createElement("ul", { className: "pk-field-list", ref: list, role: "list", "aria-label": labels.fields, "aria-describedby": keysId, onFocus, onKeyDown: onListKey, "data-testid": "field-list" }, shown.map((f) => /* @__PURE__ */ React3.createElement(
748
+ FieldItem,
749
+ {
750
+ key: f.name,
751
+ field: f,
752
+ labels,
753
+ zones: placed.get(f.name.toLowerCase()) ?? [],
754
+ onAdd,
755
+ onNote,
756
+ onFilter,
757
+ showInfo,
758
+ stop: current && current.field === f.name ? current.slot : null,
759
+ name: nameOf(f.name),
760
+ info: info.get(f.name.toLowerCase())?.description ? info.get(f.name.toLowerCase()) : void 0
761
+ }
762
+ ))),
763
+ /* @__PURE__ */ React3.createElement("p", { id: keysId, hidden: true }, labels.fieldListKeys),
764
+ shown.length === 0 ? /* @__PURE__ */ React3.createElement("p", { className: "pk-hint" }, fields.length ? fill(labels.noFieldMatch, { query }) : labels.emptyFields) : null,
765
+ removing ? /* @__PURE__ */ React3.createElement("div", { className: "pk-remove-hint", "aria-hidden": "true" }, /* @__PURE__ */ React3.createElement(Icon, { name: "trash" }), " ", labels.dropToRemove) : null
766
+ );
767
+ }
768
+
769
+ // src/lazy-menus.jsx
770
+ import React4, { useEffect as useEffect3, useRef as useRef3, useState as useState4 } from "react";
771
+ var pending = null;
772
+ var loaded = null;
773
+ function loadMenus() {
774
+ pending ??= import("./menus.js").then(
775
+ (m) => {
776
+ loaded = m;
777
+ return m;
778
+ },
779
+ (error) => {
780
+ pending = null;
781
+ throw error;
782
+ }
783
+ );
784
+ return pending;
785
+ }
786
+ var menusNow = () => loaded;
787
+ function focusFirst(el) {
788
+ const popover = el.closest(".pk-popover");
789
+ const now = activeIn(el);
790
+ if (popover && (now === popover || !now || !popover.contains(now))) {
791
+ const first = (
792
+ /** @type {HTMLElement | null} */
793
+ popover.querySelector("[data-autofocus], [data-pk-option]:not([disabled]), button:not([disabled])")
794
+ );
795
+ first?.focus({ preventScroll: true });
796
+ }
797
+ }
798
+ function MenuPanel({ name, loadingText, props }) {
799
+ const [mod, setMod] = useState4(loaded);
800
+ const [failed, setFailed] = useState4(false);
801
+ const [attempt, setAttempt] = useState4(0);
802
+ const box = useRef3(
803
+ /** @type {HTMLDivElement | null} */
804
+ null
805
+ );
806
+ const late = useRef3(false);
807
+ useEffect3(() => {
808
+ if (mod) {
809
+ return void 0;
810
+ }
811
+ late.current = true;
812
+ let live = true;
813
+ loadMenus().then(
814
+ (m) => {
815
+ if (live) {
816
+ setFailed(false);
817
+ setMod(m);
818
+ }
819
+ },
820
+ () => {
821
+ if (live) {
822
+ setFailed(true);
823
+ }
824
+ }
825
+ );
826
+ return () => {
827
+ live = false;
828
+ };
829
+ }, [mod, attempt]);
830
+ useEffect3(() => {
831
+ if (box.current && (mod && late.current || failed)) {
832
+ focusFirst(box.current);
833
+ }
834
+ }, [mod, failed]);
835
+ const Panel = mod ? (
836
+ /** @type {any} */
837
+ mod[name]
838
+ ) : null;
839
+ const labels = props.labels;
840
+ return /* @__PURE__ */ React4.createElement("div", { className: "pk-menu-panel", ref: box }, Panel ? (
841
+ // the menus' own texts (menu-labels.js) come with them, under the report's labels
842
+ /* @__PURE__ */ React4.createElement(Panel, { ...props, labels: labels && mod ? mod.menuLabels(labels) : labels })
843
+ ) : failed && labels ? /* @__PURE__ */ React4.createElement("div", { className: "pk-menu-failed", role: "alert", "data-testid": "menu-failed" }, /* @__PURE__ */ React4.createElement("p", null, labels.menuFailed), /* @__PURE__ */ React4.createElement(
844
+ "button",
845
+ {
846
+ type: "button",
847
+ className: "pk-btn pk-small-btn",
848
+ "data-autofocus": "",
849
+ "data-testid": "menu-retry",
850
+ onClick: () => {
851
+ setFailed(false);
852
+ setAttempt((n) => n + 1);
853
+ }
854
+ },
855
+ labels.tryAgain
856
+ )) : loadingText ? /* @__PURE__ */ React4.createElement("p", { className: "pk-hint pk-menu-loading", role: "status" }, loadingText) : null);
857
+ }
858
+
859
+ // src/share.js
860
+ import { VIEW_FILE_LIMITS, fromViewFile, normalize } from "pivotkit-core";
861
+ var linkModule = null;
862
+ var linkLoaded = null;
863
+ function loadLink() {
864
+ linkModule ??= import("pivotkit-core/link").then((m) => {
865
+ linkLoaded = m;
866
+ return m;
867
+ });
868
+ return linkModule;
869
+ }
870
+ var linkNow = () => linkLoaded;
871
+ function linkParam(storageKey) {
872
+ return storageKey ? `pivot-${storageKey}` : "pivot";
873
+ }
874
+ var entries = (fragment) => fragment ? fragment.split("&") : [];
875
+ var isEntry = (entry, param) => entry.startsWith(`${encodeURIComponent(param)}=`);
876
+ function readLinkParam(hash, param) {
877
+ const text = typeof hash === "string" ? hash.replace(/^#/, "") : "";
878
+ const entry = entries(text).find((e) => isEntry(e, param));
879
+ const value = entry ? entry.slice(encodeURIComponent(param).length + 1) : "";
880
+ return value ? value : null;
881
+ }
882
+ function withLinkParam(url, param, encoded) {
883
+ const at = url.indexOf("#");
884
+ const base = at === -1 ? url : url.slice(0, at);
885
+ const kept = entries(at === -1 ? "" : url.slice(at + 1)).filter((e) => !isEntry(e, param));
886
+ const next = encoded ? [...kept, `${encodeURIComponent(param)}=${encoded}`] : kept;
887
+ return next.length ? `${base}#${next.join("&")}` : base;
888
+ }
889
+ function shareBase(shareLink, here2) {
890
+ if (shareLink === true) {
891
+ if (!here2) {
892
+ return null;
893
+ }
894
+ try {
895
+ const url = new URL(here2);
896
+ return `${url.origin}${url.pathname}${url.hash}`;
897
+ } catch {
898
+ return null;
899
+ }
900
+ }
901
+ return typeof shareLink === "string" && shareLink.trim() ? shareLink.trim() : null;
902
+ }
903
+ var viewStorageName = (key) => `pivotkit:view:${key ?? ""}`;
904
+ function readStoredView(key, storage) {
905
+ if (!storage) {
906
+ return null;
907
+ }
908
+ try {
909
+ return storage.getItem(viewStorageName(key));
910
+ } catch {
911
+ return null;
912
+ }
913
+ }
914
+ function writeStoredView(key, storage, view) {
915
+ if (!storage) {
916
+ return;
917
+ }
918
+ try {
919
+ storage.setItem(viewStorageName(key), JSON.stringify(view));
920
+ } catch {
921
+ }
922
+ }
923
+ var VIEW_TEXT_MAX = VIEW_FILE_LIMITS.text;
924
+ var quoteNames = (names) => {
925
+ const shown = names.slice(0, 5).map((n) => `\u201C${n.length > 60 ? `${n.slice(0, 59)}\u2026` : n}\u201D`).join(", ");
926
+ return names.length > 5 ? `${shown} \u2026` : shown;
927
+ };
928
+ var fieldOf = (message) => /^unknown field (".*")$/.exec(message)?.[1];
929
+ function issueLines(issues, labels) {
930
+ const missing = [];
931
+ let other = 0;
932
+ for (const issue of issues) {
933
+ if (issue.message === "unknown key") {
934
+ continue;
935
+ }
936
+ const quoted = fieldOf(issue.message);
937
+ let name;
938
+ try {
939
+ name = quoted ? JSON.parse(quoted) : null;
940
+ } catch {
941
+ name = null;
942
+ }
943
+ if (typeof name === "string") {
944
+ if (!missing.includes(name)) {
945
+ missing.push(name);
946
+ }
947
+ } else {
948
+ other += 1;
949
+ }
950
+ }
951
+ const lines = [];
952
+ if (missing.length) {
953
+ lines.push(fill(labels.viewMissingFields, { fields: quoteNames(missing) }));
954
+ }
955
+ if (other) {
956
+ lines.push(fill(other === 1 ? labels.viewOtherIssue : labels.viewOtherIssues, { count: other }));
957
+ }
958
+ return lines;
959
+ }
960
+ var FAILED = Object.freeze({ newerFormat: "newer", newerView: "newer" });
961
+ function viewFromText(text, encoded, options = {}) {
962
+ return viewFromObject(text, encoded, options);
963
+ }
964
+ function viewFromObject(input, encoded, options = {}) {
965
+ const file = fromViewFile(input, { data: encoded, sourceId: options.sourceId });
966
+ if (file.failed || !file.view) {
967
+ const failed = file.failed ?? "notView";
968
+ return { view: null, issues: file.issues, failed: Object.hasOwn(FAILED, failed) ? FAILED[failed] : failed, file };
969
+ }
970
+ const { view, issues } = normalize(file.view, encoded, options.limits ? { limits: options.limits } : void 0);
971
+ if (issues.some((i) => i.path === "version")) {
972
+ return { view: null, issues, failed: "newer", file };
973
+ }
974
+ return { view, issues, failed: null, file };
975
+ }
976
+ function loadCheck(loaded2, labels, sources = []) {
977
+ const fit = loaded2.file?.compatible;
978
+ if (!loaded2.view || !fit || fit.ok) {
979
+ return null;
980
+ }
981
+ const lines = [];
982
+ const fileSource = loaded2.file?.source;
983
+ const target = fit.source === "other" && fileSource?.id ? sources.find((s) => s && s.id === fileSource.id) : void 0;
984
+ if (fit.source === "other") {
985
+ const name = target?.name || fileSource?.name || fileSource?.id;
986
+ lines.push(name ? fill(labels.loadCheckSource, { source: name }) : labels.loadCheckOtherSource);
987
+ }
988
+ if (fit.missing.length) {
989
+ lines.push(fill(labels.loadCheckMissing, { fields: quoteNames(fit.missing) }));
990
+ }
991
+ if (fit.changed.length) {
992
+ lines.push(fill(labels.loadCheckChanged, { fields: quoteNames(fit.changed.map((c) => c.name)) }));
993
+ }
994
+ return { lines, switchTo: target ? { id: target.id, name: target.name || target.id } : null };
995
+ }
996
+
997
+ // src/skeleton.jsx
998
+ import React5 from "react";
999
+ var ROWS = 6;
1000
+ function Skeleton({ text, full = false }) {
1001
+ const rows = /* @__PURE__ */ React5.createElement("div", { className: "pk-skel-table", "aria-hidden": "true" }, Array.from({ length: ROWS }, (_, i) => /* @__PURE__ */ React5.createElement("div", { key: i, className: "pk-skel-row" }, /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-cell pk-skel-head" }), /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-cell" }), /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-cell" }), /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-cell" }))));
1002
+ return /* @__PURE__ */ React5.createElement("div", { className: full ? "pk-skeleton pk-skeleton-full" : "pk-skeleton", role: "status", "data-testid": "skeleton" }, /* @__PURE__ */ React5.createElement("span", { className: "pk-sr" }, text), full ? /* @__PURE__ */ React5.createElement("div", { className: "pk-skel-layout", "aria-hidden": "true" }, /* @__PURE__ */ React5.createElement("div", { className: "pk-skel-panel" }, /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-title" }), Array.from({ length: 7 }, (_, i) => /* @__PURE__ */ React5.createElement("span", { key: i, className: "pk-skel pk-skel-field" }))), /* @__PURE__ */ React5.createElement("div", { className: "pk-skel-main" }, /* @__PURE__ */ React5.createElement("div", { className: "pk-skel-toolbar" }, /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-btn pk-skel-wide" }), /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-btn" }), /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-btn" }), /* @__PURE__ */ React5.createElement("span", { className: "pk-skel-grow" }), /* @__PURE__ */ React5.createElement("span", { className: "pk-skel pk-skel-btn" })), /* @__PURE__ */ React5.createElement("div", { className: "pk-skel-zones" }, Array.from({ length: 4 }, (_, i) => /* @__PURE__ */ React5.createElement("span", { key: i, className: "pk-skel pk-skel-zone" }))), rows)) : rows);
1003
+ }
1004
+
1005
+ // src/table.jsx
1006
+ import React6, { useCallback as useCallback2, useEffect as useEffect4, useMemo as useMemo3, useRef as useRef4, useState as useState5 } from "react";
1007
+
1008
+ // src/virtual.js
1009
+ var VIRTUAL_FROM = 300;
1010
+ function windowOf({ count, scrollTop, viewport, rowHeight, overscan = 12 }) {
1011
+ const h = Math.max(1, rowHeight);
1012
+ const first = Math.floor(Math.max(0, scrollTop) / h);
1013
+ const start = Math.max(0, Math.min(count, first - overscan));
1014
+ const end = Math.max(start, Math.min(count, first + Math.ceil(Math.max(0, viewport) / h) + overscan));
1015
+ return { start, end, padTop: start * h, padBottom: (count - end) * h };
1016
+ }
1017
+ function sliceRows(grid, start, end) {
1018
+ const h = grid.headerRows;
1019
+ const out = [];
1020
+ for (let r = start; r < end; r++) {
1021
+ const row = grid.rows[h + r];
1022
+ const cells = [];
1023
+ row.forEach((cell, col) => {
1024
+ if (cell) {
1025
+ cells.push({ cell, col, rowSpan: Math.min(cell.rowSpan ?? 1, end - r), colSpan: cell.colSpan ?? 1 });
1026
+ }
1027
+ });
1028
+ out.push({ index: r, cells });
1029
+ }
1030
+ if (start > 0 && out.length > 0) {
1031
+ const first = out[0].cells;
1032
+ for (const m of grid.merges) {
1033
+ const top = m.row - h;
1034
+ if (top >= 0 && top < start && top + m.rowSpan > start) {
1035
+ const cell = grid.rows[m.row][m.col];
1036
+ first.push({ cell, col: m.col, rowSpan: Math.min(top + m.rowSpan, end) - start, colSpan: m.colSpan });
1037
+ }
1038
+ }
1039
+ first.sort((a, b) => a.col - b.col);
1040
+ }
1041
+ return out;
1042
+ }
1043
+ function rowLabelOf(grid, r) {
1044
+ const row = grid.headerRows + r;
1045
+ const texts = [];
1046
+ for (let c = 0; c < grid.rowHeaderColumns; c++) {
1047
+ const own2 = grid.rows[row]?.[c];
1048
+ const merge = own2 ? null : grid.merges.find((m) => m.row <= row && row < m.row + m.rowSpan && m.col <= c && c < m.col + m.colSpan);
1049
+ const cell = own2 ?? (merge && merge.col === c ? grid.rows[merge.row][merge.col] : null);
1050
+ if (cell && cell.text) {
1051
+ texts.push(cell.text);
1052
+ }
1053
+ }
1054
+ return texts.join(" / ");
1055
+ }
1056
+
1057
+ // src/table.jsx
1058
+ var totalClass = (t) => t === 2 ? " pk-grand" : t === 1 ? " pk-sub" : "";
1059
+ function conditionalStyle(cell) {
1060
+ const s = cell.style;
1061
+ if (!s) {
1062
+ return void 0;
1063
+ }
1064
+ if (s.scale !== void 0 && s.color) {
1065
+ return { "--pk-cell-bg": s.color };
1066
+ }
1067
+ if (s.scale !== void 0) {
1068
+ const t = Math.max(0, Math.min(1, s.scale));
1069
+ const [from, to, part] = t < 0.5 ? ["--pk-scale-low", "--pk-scale-mid", t * 2] : ["--pk-scale-mid", "--pk-scale-high", (t - 0.5) * 2];
1070
+ return { "--pk-cell-bg": `color-mix(in srgb, var(${to}) ${Math.round(part * 100)}%, var(${from}))` };
1071
+ }
1072
+ if (s.bar !== void 0) {
1073
+ return { "--pk-bar": `${Math.round(s.bar * 1e3) / 10}%`, ...s.color ? { "--pk-bar-color": s.color } : {} };
1074
+ }
1075
+ return void 0;
1076
+ }
1077
+ var drillable = (cell) => cell.valueIndex !== void 0 && cell.hasRows !== false;
1078
+ function firstValueCell(grid) {
1079
+ for (let r = 0; r < grid.rows.length - grid.headerRows; r++) {
1080
+ const c = grid.rows[grid.headerRows + r].findIndex((cell) => cell && cell.kind === "value" && cell.valueIndex !== void 0);
1081
+ if (c !== -1) {
1082
+ return { r, c };
1083
+ }
1084
+ }
1085
+ return null;
1086
+ }
1087
+ function DraggableHeader({ cell, source, children, className, style, colSpan, rowSpan, scope, description, tooltip = true }) {
1088
+ const { setNodeRef, isDragging, itemProps } = useDragSource(`table:${source.zone}:${source.index}:${source.field ?? ""}`, source);
1089
+ return /* @__PURE__ */ React6.createElement("th", { ref: setNodeRef, ...itemProps, className: `${className} pk-draggable${isDragging ? " pk-dragging" : ""}`, style, colSpan, rowSpan, scope, "data-kind": cell.kind, title: tooltip ? description : void 0, "aria-description": description }, children, /* @__PURE__ */ React6.createElement(Icon, { name: "grip", size: 12, className: "pk-th-grip" }));
1090
+ }
1091
+ var toggleKey = (axis, path) => `${axis}:${JSON.stringify(path)}`;
1092
+ function Toggle({ toggle, text, labels, onToggle }) {
1093
+ const name = fill(toggle.collapsed ? labels.expand : labels.collapse, { label: text });
1094
+ return /* @__PURE__ */ React6.createElement("button", { type: "button", className: `pk-toggle${toggle.collapsed ? "" : " pk-open"}`, "aria-expanded": !toggle.collapsed, "aria-label": name, title: name, "data-pk-toggle": toggleKey(toggle.axis, toggle.path), onClick: () => onToggle(toggle.axis, toggle.path) }, /* @__PURE__ */ React6.createElement(Icon, { name: "chevronRight", size: 16 }));
1095
+ }
1096
+ function PivotTable({ grid, view, labels, onToggle: toggleGroup, onCell, version, hintId, onRowLabel, infoOf, showInfo = true }) {
1097
+ const wrap = useRef4(
1098
+ /** @type {HTMLDivElement | null} */
1099
+ null
1100
+ );
1101
+ const table = useRef4(
1102
+ /** @type {HTMLTableElement | null} */
1103
+ null
1104
+ );
1105
+ const bodyCount = grid.rows.length - grid.headerRows;
1106
+ const virtual = bodyCount >= VIRTUAL_FROM;
1107
+ const [scroll, setScroll] = useState5({ top: 0, height: 600 });
1108
+ const [rowHeight, setRowHeight] = useState5(34);
1109
+ const [lefts, setLefts] = useState5(
1110
+ /** @type {number[]} */
1111
+ []
1112
+ );
1113
+ const [tops, setTops] = useState5(
1114
+ /** @type {number[]} */
1115
+ []
1116
+ );
1117
+ const [headHeight, setHeadHeight] = useState5(0);
1118
+ const [width, setWidth] = useState5(0);
1119
+ const [active, setActive] = useState5(
1120
+ /** @type {{ r: number, c: number } | null} */
1121
+ null
1122
+ );
1123
+ const focusNext = useRef4(false);
1124
+ const focusToggle = useRef4(
1125
+ /** @type {string | null} */
1126
+ null
1127
+ );
1128
+ const onToggle = useCallback2(
1129
+ (axis, path) => {
1130
+ focusToggle.current = toggleKey(axis, path);
1131
+ toggleGroup(axis, path);
1132
+ },
1133
+ [toggleGroup]
1134
+ );
1135
+ useIsoLayoutEffect(() => {
1136
+ const t = table.current;
1137
+ if (!t) {
1138
+ return;
1139
+ }
1140
+ const row = t.tBodies[0]?.querySelector("tr[data-r]");
1141
+ if (row && row.getBoundingClientRect().height > 0) {
1142
+ setRowHeight(row.getBoundingClientRect().height);
1143
+ }
1144
+ const headRows = t.tHead ? [...t.tHead.rows] : [];
1145
+ setHeadHeight(t.tHead ? t.tHead.offsetHeight : 0);
1146
+ const top = t.tHead ? t.tHead.getBoundingClientRect().top : 0;
1147
+ const ys = headRows.map((tr) => tr.getBoundingClientRect().top - top);
1148
+ setTops((old) => old.length === ys.length && old.every((v, i) => Math.abs(v - ys[i]) < 0.01) ? old : ys);
1149
+ const last = headRows[headRows.length - 1];
1150
+ if (last) {
1151
+ const xs = [];
1152
+ let x = 0;
1153
+ for (let c = 0; c < grid.rowHeaderColumns && c < last.cells.length; c++) {
1154
+ xs.push(x);
1155
+ x += last.cells[c].getBoundingClientRect().width;
1156
+ }
1157
+ setLefts((old) => old.length === xs.length && old.every((v, i) => Math.abs(v - xs[i]) < 0.5) ? old : xs);
1158
+ }
1159
+ }, [grid, version, width]);
1160
+ useEffect4(() => {
1161
+ const el = wrap.current;
1162
+ if (!el) {
1163
+ return void 0;
1164
+ }
1165
+ const update = () => {
1166
+ setScroll({ top: el.scrollTop, height: el.clientHeight });
1167
+ setWidth(el.clientWidth);
1168
+ };
1169
+ update();
1170
+ const ro = typeof ResizeObserver === "function" ? new ResizeObserver(update) : null;
1171
+ ro?.observe(el);
1172
+ return () => ro?.disconnect();
1173
+ }, []);
1174
+ const head = headHeight || rowHeight * grid.headerRows;
1175
+ const win = virtual ? windowOf({ count: bodyCount, scrollTop: scroll.top - head, viewport: scroll.height, rowHeight }) : { start: 0, end: bodyCount, padTop: 0, padBottom: 0 };
1176
+ const rows = useMemo3(() => sliceRows(grid, win.start, win.end), [grid, win.start, win.end]);
1177
+ const [shownRow, setLabelRow] = useState5(
1178
+ /** @type {{ r: number, span: number, grid: unknown } | null} */
1179
+ null
1180
+ );
1181
+ const labelRow = shownRow && shownRow.grid === grid ? shownRow : null;
1182
+ useEffect4(() => {
1183
+ onRowLabel?.(null);
1184
+ }, [grid, onRowLabel]);
1185
+ const showRowLabel = virtual && onRowLabel ? (r, span = 1) => {
1186
+ setLabelRow({ r, span, grid });
1187
+ onRowLabel(rowLabelOf(grid, r));
1188
+ } : void 0;
1189
+ const clearRowLabel = () => {
1190
+ if (labelRow !== null) {
1191
+ setLabelRow(null);
1192
+ onRowLabel?.(null);
1193
+ }
1194
+ };
1195
+ const onScroll = (e) => {
1196
+ const box = e.currentTarget;
1197
+ setScroll({ top: box.scrollTop, height: box.clientHeight });
1198
+ const row = labelRow;
1199
+ if (row !== null) {
1200
+ const y = head + row.r * rowHeight - box.scrollTop;
1201
+ if (y + row.span * rowHeight <= head || y >= box.clientHeight) {
1202
+ clearRowLabel();
1203
+ }
1204
+ }
1205
+ };
1206
+ const onBlur = (e) => {
1207
+ if (!(e.relatedTarget instanceof Node && e.currentTarget.contains(e.relatedTarget))) {
1208
+ clearRowLabel();
1209
+ }
1210
+ };
1211
+ const firstValue = useMemo3(() => firstValueCell(grid), [grid]);
1212
+ const current = active && active.r < bodyCount && grid.rows[grid.headerRows + active.r]?.[active.c]?.kind === "value" ? active : firstValue;
1213
+ const move = (dr, dc) => {
1214
+ if (!current) {
1215
+ return;
1216
+ }
1217
+ let { r, c } = current;
1218
+ const valueAt = (rr, cc) => {
1219
+ const cell = grid.rows[grid.headerRows + rr]?.[cc];
1220
+ return cell && cell.kind === "value" && cell.valueIndex !== void 0;
1221
+ };
1222
+ for (let step = 0; step < Math.max(bodyCount, grid.columnCount); step++) {
1223
+ r += dr;
1224
+ c += dc;
1225
+ if (r < 0 || r >= bodyCount || c < grid.rowHeaderColumns || c >= grid.columnCount) {
1226
+ return;
1227
+ }
1228
+ if (valueAt(r, c)) {
1229
+ break;
1230
+ }
1231
+ }
1232
+ if (!valueAt(r, c)) {
1233
+ return;
1234
+ }
1235
+ focusNext.current = true;
1236
+ setActive({ r, c });
1237
+ const el = wrap.current;
1238
+ if (virtual && el) {
1239
+ const y = (grid.headerRows + r) * rowHeight;
1240
+ if (y < el.scrollTop + rowHeight * grid.headerRows || y + rowHeight > el.scrollTop + el.clientHeight) {
1241
+ el.scrollTop = Math.max(0, y - el.clientHeight / 2);
1242
+ }
1243
+ }
1244
+ };
1245
+ useEffect4(() => {
1246
+ const key = focusToggle.current;
1247
+ if (key && table.current) {
1248
+ focusToggle.current = null;
1249
+ const button = [...table.current.querySelectorAll("button[data-pk-toggle]")].find((b) => b.getAttribute("data-pk-toggle") === key);
1250
+ button?.focus({ preventScroll: true });
1251
+ }
1252
+ if (focusNext.current && current) {
1253
+ focusNext.current = false;
1254
+ const td = table.current?.querySelector(`td[data-r="${current.r}"][data-c="${current.c}"]`);
1255
+ td?.focus({ preventScroll: false });
1256
+ }
1257
+ });
1258
+ const onKeyDown = (e) => {
1259
+ const keys = { ArrowDown: [1, 0], ArrowUp: [-1, 0], ArrowRight: [0, 1], ArrowLeft: [0, -1] };
1260
+ if (keys[e.key] && e.target instanceof HTMLTableCellElement) {
1261
+ e.preventDefault();
1262
+ const [dr, dc] = keys[e.key];
1263
+ move(dr, dc);
1264
+ } else if ((e.key === "Enter" || e.key === " ") && e.target instanceof HTMLTableCellElement && current) {
1265
+ e.preventDefault();
1266
+ const cell = grid.rows[grid.headerRows + current.r][current.c];
1267
+ if (cell && drillable(cell)) {
1268
+ onCell(cell);
1269
+ }
1270
+ }
1271
+ };
1272
+ const stickyStyle = (col, extra) => col < grid.rowHeaderColumns && lefts[col] !== void 0 ? { left: lefts[col], ...extra } : extra;
1273
+ const headerCell = (cell, r, c) => {
1274
+ const top = { top: tops[r] ?? r * rowHeight };
1275
+ const sticky = c < grid.rowHeaderColumns;
1276
+ const className = `pk-th pk-${cell.kind}${totalClass(cell.total)}${sticky ? " pk-sticky" : ""}`;
1277
+ const content = /* @__PURE__ */ React6.createElement("span", { className: "pk-th-content" }, cell.toggle ? /* @__PURE__ */ React6.createElement(Toggle, { toggle: cell.toggle, text: cell.text, labels, onToggle }) : null, /* @__PURE__ */ React6.createElement("span", { className: "pk-th-text" }, cell.text));
1278
+ const props = { className, style: stickyStyle(c, top), colSpan: cell.colSpan, rowSpan: cell.rowSpan, scope: cell.kind === "colHeader" ? "col" : void 0 };
1279
+ if (cell.kind === "corner" && !cell.field && !cell.text) {
1280
+ return /* @__PURE__ */ React6.createElement("td", { key: c, className: `${className} pk-blank`, style: props.style, colSpan: cell.colSpan, rowSpan: cell.rowSpan });
1281
+ }
1282
+ if (cell.kind === "corner" && cell.field) {
1283
+ const zone = view.rows.includes(cell.field) ? "rows" : "cols";
1284
+ return /* @__PURE__ */ React6.createElement(DraggableHeader, { key: c, ...props, cell, source: { kind: "table", field: cell.field, zone, index: view[zone].indexOf(cell.field), label: cell.text }, description: infoOf?.(cell.field)?.description, tooltip: showInfo }, content);
1285
+ }
1286
+ if (cell.kind === "colHeader" && cell.valueIndex !== void 0 && r === grid.headerRows - 1) {
1287
+ const spec = view.values[cell.valueIndex];
1288
+ return /* @__PURE__ */ React6.createElement(DraggableHeader, { key: c, ...props, cell, source: { kind: "table", field: spec?.field ?? null, zone: "values", index: cell.valueIndex, label: cell.text }, description: spec?.field ? infoOf?.(spec.field)?.description : void 0, tooltip: showInfo }, content);
1289
+ }
1290
+ return /* @__PURE__ */ React6.createElement("th", { key: c, ...props }, content);
1291
+ };
1292
+ const bodyCell = ({ cell, col, rowSpan, colSpan }, r) => {
1293
+ if (cell.kind === "rowHeader") {
1294
+ return /* @__PURE__ */ React6.createElement("th", { key: col, scope: "row", className: `pk-th pk-rowHeader pk-sticky${totalClass(cell.total)}${rowSpan > 1 ? " pk-span" : ""}`, style: stickyStyle(col), rowSpan: rowSpan > 1 ? rowSpan : void 0, colSpan: colSpan > 1 ? colSpan : void 0, title: virtual ? cell.text : void 0, onClick: showRowLabel ? () => showRowLabel(r, rowSpan) : void 0 }, /* @__PURE__ */ React6.createElement("span", { className: "pk-th-content" }, cell.toggle ? /* @__PURE__ */ React6.createElement(Toggle, { toggle: cell.toggle, text: cell.text, labels, onToggle }) : null, /* @__PURE__ */ React6.createElement("span", { className: "pk-th-text" }, cell.text)));
1295
+ }
1296
+ const isValue = cell.valueIndex !== void 0;
1297
+ const clickable = isValue && drillable(cell);
1298
+ const focus = current && current.r === r && current.c === col;
1299
+ const cond = conditionalStyle(cell);
1300
+ return /* @__PURE__ */ React6.createElement(
1301
+ "td",
1302
+ {
1303
+ key: col,
1304
+ className: `pk-td${totalClass(cell.total)}${clickable ? " pk-clickable" : ""}${cell.valueType === "text" ? " pk-text" : ""}${cond ? cell.style.bar !== void 0 ? " pk-has-bar" : " pk-has-scale" : ""}`,
1305
+ style: cond,
1306
+ "data-r": r,
1307
+ "data-c": col,
1308
+ tabIndex: isValue ? focus ? 0 : -1 : void 0,
1309
+ onClick: clickable ? () => {
1310
+ setActive({ r, c: col });
1311
+ onCell(cell);
1312
+ } : void 0,
1313
+ onFocus: showRowLabel ? () => showRowLabel(r) : void 0
1314
+ },
1315
+ cell.text,
1316
+ isValue && cell.text === "" ? /* @__PURE__ */ React6.createElement("span", { className: "pk-sr pk-no-copy" }, cell.hasRows ? labels.emptyValue : labels.emptyCell) : null
1317
+ );
1318
+ };
1319
+ const columns = grid.columnCount;
1320
+ return /* @__PURE__ */ React6.createElement("div", { className: "pk-table-wrap", ref: wrap, onScroll: virtual ? onScroll : void 0, onBlur: virtual ? onBlur : void 0, "data-testid": "pivot-table" }, /* @__PURE__ */ React6.createElement("table", { ref: table, className: `pk-table${virtual ? " pk-virtual" : ""}`, style: (
1321
+ /** @type {any} */
1322
+ { "--pk-row-cols": grid.rowHeaderColumns }
1323
+ ), onKeyDown, "aria-rowcount": grid.rows.length, "aria-label": labels.tableName, "aria-describedby": hintId }, /* @__PURE__ */ React6.createElement("thead", null, grid.rows.slice(0, grid.headerRows).map((row, r) => /* @__PURE__ */ React6.createElement("tr", { key: r }, row.map((cell, c) => cell ? headerCell(cell, r, c) : null)))), /* @__PURE__ */ React6.createElement("tbody", null, win.padTop > 0 ? /* @__PURE__ */ React6.createElement("tr", { className: "pk-spacer", "aria-hidden": "true", style: { height: win.padTop } }, /* @__PURE__ */ React6.createElement("td", { colSpan: columns })) : null, rows.map(({ index, cells }) => /* @__PURE__ */ React6.createElement("tr", { key: index, "data-r": index, "aria-rowindex": grid.headerRows + index + 1, className: totalClass(grid.bodyRows[index]?.total).trim() || void 0 }, cells.map((c) => bodyCell(c, index)))), win.padBottom > 0 ? /* @__PURE__ */ React6.createElement("tr", { className: "pk-spacer", "aria-hidden": "true", style: { height: win.padBottom } }, /* @__PURE__ */ React6.createElement("td", { colSpan: columns })) : null)));
1324
+ }
1325
+
1326
+ // src/toasts.jsx
1327
+ import React7, { useCallback as useCallback3, useEffect as useEffect5, useRef as useRef5, useState as useState6 } from "react";
1328
+ var SHOWN_MS = 6e3;
1329
+ var MAX_SHOWN = 2;
1330
+ function useToasts() {
1331
+ const [toasts, setToasts] = useState6(
1332
+ /** @type {Toast[]} */
1333
+ []
1334
+ );
1335
+ const next = useRef5(1);
1336
+ const timers = useRef5(/* @__PURE__ */ new Map());
1337
+ const paused = useRef5(false);
1338
+ const dismiss = useCallback3((id) => {
1339
+ setToasts((list) => list.filter((t) => t.id !== id));
1340
+ clearTimeout(timers.current.get(id));
1341
+ timers.current.delete(id);
1342
+ }, []);
1343
+ const arm = useCallback3(
1344
+ (id) => {
1345
+ clearTimeout(timers.current.get(id));
1346
+ timers.current.set(id, setTimeout(() => dismiss(id), SHOWN_MS));
1347
+ },
1348
+ [dismiss]
1349
+ );
1350
+ const push = useCallback3(
1351
+ (toast) => {
1352
+ const id = next.current++;
1353
+ setToasts((list) => [...list.slice(-(MAX_SHOWN - 1)), { ...toast, id }]);
1354
+ if (toast.tone !== "error" && !paused.current) {
1355
+ arm(id);
1356
+ }
1357
+ },
1358
+ [arm]
1359
+ );
1360
+ const pause = useCallback3(
1361
+ (on, list) => {
1362
+ paused.current = on;
1363
+ for (const t of list) {
1364
+ if (on) {
1365
+ clearTimeout(timers.current.get(t.id));
1366
+ } else if (t.tone !== "error") {
1367
+ arm(t.id);
1368
+ }
1369
+ }
1370
+ },
1371
+ [arm]
1372
+ );
1373
+ useEffect5(() => {
1374
+ const map = timers.current;
1375
+ return () => map.forEach((t) => clearTimeout(t));
1376
+ }, []);
1377
+ return { toasts, push, dismiss, pause };
1378
+ }
1379
+ function Toasts({ toasts, dismiss, pause, closeLabel }) {
1380
+ const hold = () => pause(true, toasts);
1381
+ const release = (e) => {
1382
+ if (!e || !e.currentTarget.contains(
1383
+ /** @type {Node | null} */
1384
+ e.relatedTarget
1385
+ )) {
1386
+ pause(false, toasts);
1387
+ }
1388
+ };
1389
+ return /* @__PURE__ */ React7.createElement("div", { className: "pk-toasts", role: "status", "aria-live": "polite", "aria-atomic": "false", onMouseEnter: hold, onMouseLeave: () => release(null), onFocus: hold, onBlur: release }, toasts.map((t) => /* @__PURE__ */ React7.createElement("div", { key: t.id, className: `pk-toast${t.tone === "error" ? " pk-error" : ""}`, role: t.tone === "error" ? "alert" : void 0 }, t.tone === "error" ? /* @__PURE__ */ React7.createElement(Icon, { name: "info", size: 14 }) : null, /* @__PURE__ */ React7.createElement("span", { className: "pk-toast-text" }, t.text), t.action ? /* @__PURE__ */ React7.createElement(
1390
+ "button",
1391
+ {
1392
+ type: "button",
1393
+ className: "pk-link pk-toast-action",
1394
+ onClick: () => {
1395
+ dismiss(t.id);
1396
+ t.action?.run();
1397
+ }
1398
+ },
1399
+ t.action.label
1400
+ ) : null, /* @__PURE__ */ React7.createElement("button", { type: "button", className: "pk-icon-btn pk-toast-x", "aria-label": closeLabel, title: closeLabel, onClick: () => dismiss(t.id) }, /* @__PURE__ */ React7.createElement(Icon, { name: "x", size: 14 })))));
1401
+ }
1402
+
1403
+ // src/templates.js
1404
+ import { fieldDefaultsFromSchema as fieldDefaultsFromSchema2, fromViewFile as fromViewFile2 } from "pivotkit-core";
1405
+ var warnedScope = false;
1406
+ function plainNames(names) {
1407
+ const properties = {};
1408
+ names.forEach((title, i) => Object.defineProperty(properties, String(i), { value: { title }, enumerable: true }));
1409
+ const clean = names.length ? fieldDefaultsFromSchema2({ properties }).defaults : {};
1410
+ return names.map((n, i) => Object.hasOwn(clean, String(i)) ? clean[String(i)].label : void 0);
1411
+ }
1412
+ var viewsName = (key) => key ? `pivotkit:views:${key}` : "pivotkit:views";
1413
+ function templateEntries(templates, stored, hostDeletes) {
1414
+ const out = [];
1415
+ for (const t of Array.isArray(templates) ? templates : []) {
1416
+ if (!t || typeof t !== "object") {
1417
+ continue;
1418
+ }
1419
+ let { name, view } = t;
1420
+ if (t.file !== void 0 && t.file !== null) {
1421
+ const read = fromViewFile2(t.file);
1422
+ view = read.view;
1423
+ name = typeof name === "string" && name ? name : read.name;
1424
+ }
1425
+ if (typeof name === "string" && name && view && typeof view === "object") {
1426
+ const deletable = t.deletable === true;
1427
+ const scoped = t.scope === "shared" || t.scope === "user";
1428
+ if (deletable && !scoped && !warnedScope) {
1429
+ warnedScope = true;
1430
+ console.warn('pivotkit: a template marked deletable without a scope is listed under "My views"; give shared views scope: "shared"');
1431
+ }
1432
+ out.push({ name, view, deletable: deletable && hostDeletes, scope: scoped ? t.scope : deletable ? "user" : "shared" });
1433
+ }
1434
+ }
1435
+ const all = [...out, ...stored.map((t) => ({ name: t.name, view: t.view, scope: (
1436
+ /** @type {const} */
1437
+ "user"
1438
+ ), deletable: true, at: t.at }))];
1439
+ const names = plainNames(all.map((t) => t.name));
1440
+ return all.flatMap((t, i) => names[i] ? [{ ...t, name: (
1441
+ /** @type {string} */
1442
+ names[i]
1443
+ ) }] : []);
1444
+ }
1445
+
1446
+ // src/tip-list.jsx
1447
+ import React8, { useEffect as useEffect6, useId as useId3, useRef as useRef6 } from "react";
1448
+ function Tips({ tips, labels, onDismiss, onAction, focusFallback }) {
1449
+ const box = useRef6(
1450
+ /** @type {HTMLDivElement | null} */
1451
+ null
1452
+ );
1453
+ const idBase = useId3();
1454
+ const refocus = useRef6(false);
1455
+ useEffect6(() => {
1456
+ if (!refocus.current) {
1457
+ return;
1458
+ }
1459
+ refocus.current = false;
1460
+ const next = (
1461
+ /** @type {HTMLElement | null | undefined} */
1462
+ box.current?.querySelector(".pk-tip-x")
1463
+ );
1464
+ if (next) {
1465
+ next.focus({ preventScroll: true });
1466
+ } else {
1467
+ focusFallback();
1468
+ }
1469
+ });
1470
+ return /* @__PURE__ */ React8.createElement(React8.Fragment, null, tips.length ? /* @__PURE__ */ React8.createElement("div", { className: "pk-tips", ref: box, role: "group", "aria-label": labels.tipsTitle, "data-testid": "tips" }, tips.map((t) => /* @__PURE__ */ React8.createElement("div", { key: t.id, className: `pk-note pk-tip${t.notice ? " pk-notice" : ""}${t.action ? " pk-has-action" : ""}`, "data-tip": t.id, "data-kind": t.notice ? "notice" : "tip", "data-testid": `tip-${t.id}` }, /* @__PURE__ */ React8.createElement(Icon, { name: (
1471
+ /** @type {any} */
1472
+ t.icon
1473
+ ), size: 16 }), /* @__PURE__ */ React8.createElement("span", { className: "pk-tip-text", id: `${idBase}-${t.id}` }, t.text), t.action ? /* @__PURE__ */ React8.createElement("button", { type: "button", className: "pk-btn pk-small-btn", onClick: () => onAction(t.id, t.action), "data-testid": `tip-action-${t.id}` }, /* @__PURE__ */ React8.createElement("span", { className: "pk-btn-text" }, t.actionText)) : null, t.notice ? null : /* @__PURE__ */ React8.createElement(
1474
+ "button",
1475
+ {
1476
+ type: "button",
1477
+ className: "pk-icon-btn pk-tip-x",
1478
+ "aria-label": labels.dismissTip,
1479
+ "aria-describedby": `${idBase}-${t.id}`,
1480
+ title: labels.dismissTip,
1481
+ onClick: () => {
1482
+ refocus.current = true;
1483
+ onDismiss(t.id);
1484
+ }
1485
+ },
1486
+ /* @__PURE__ */ React8.createElement(Icon, { name: "x", size: 14 })
1487
+ )))) : null, /* @__PURE__ */ React8.createElement("div", { className: "pk-sr", "aria-live": "polite", "data-testid": "tips-live" }, tips.map((t) => /* @__PURE__ */ React8.createElement("p", { key: t.id }, t.text))));
1488
+ }
1489
+
1490
+ // src/toolbar.jsx
1491
+ import React9, { useCallback as useCallback4, useEffect as useEffect7, useMemo as useMemo4, useRef as useRef7, useState as useState7 } from "react";
1492
+
1493
+ // src/overflow.js
1494
+ var OVERFLOW_ORDER = Object.freeze(["reset", "layout", "views", "options", "chartType"]);
1495
+ var TOOLBAR_ROOM = Object.freeze({
1496
+ // measured in Chromium at the playground's font: the longer of English and German with the gap
1497
+ // after it, plus 2 %; a wider font still fits, as useOverflow measures as well
1498
+ fields: 6.4,
1499
+ display: 15.3,
1500
+ chartType: 12.9,
1501
+ sep: 1,
1502
+ undo: 8.75,
1503
+ redo: 9.15,
1504
+ reset: 9.65,
1505
+ layout: 8.4,
1506
+ options: 8.75,
1507
+ views: 9.1,
1508
+ export: 7.5,
1509
+ more: 7.2
1510
+ });
1511
+ var TEXT_BUTTONS = Object.freeze(["fields", "undo", "redo", "reset", "layout"]);
1512
+ var MENU_BUTTONS = Object.freeze(["chartType", "options", "views", "export", "more"]);
1513
+ function toolbarTexts(sets) {
1514
+ const out = (
1515
+ /** @type {any} */
1516
+ { fields: [], undo: [], redo: [], reset: [], layout: [], chartType: [], options: [], views: [], export: [], more: [], display: [] }
1517
+ );
1518
+ const text = (v) => typeof v === "string" ? v : "";
1519
+ for (const l of sets) {
1520
+ out.fields.push(text(l.showFields));
1521
+ out.undo.push(text(l.undo));
1522
+ out.redo.push(text(l.redo));
1523
+ out.reset.push(text(l.reset));
1524
+ out.layout.push(text(l.layout));
1525
+ out.options.push(text(l.options));
1526
+ out.views.push(text(l.views));
1527
+ out.export.push(text(l.exportLabel));
1528
+ out.more.push(text(l.more));
1529
+ out.chartType.push(...Object.values(l.chartTypes ?? {}).map(text));
1530
+ out.display.push([text(l.table), text(l.chart)]);
1531
+ }
1532
+ return out;
1533
+ }
1534
+ function toolbarRoom(texts, measure, chrome) {
1535
+ const widest = (list, kind = "button") => Math.max(0, ...list.map((t) => measure(t, kind)));
1536
+ const room = (
1537
+ /** @type {Record<string, number>} */
1538
+ { sep: chrome.sep + chrome.gap }
1539
+ );
1540
+ for (const id of TEXT_BUTTONS) {
1541
+ room[id] = chrome.text + widest(texts[id]) + chrome.gap;
1542
+ }
1543
+ for (const id of MENU_BUTTONS) {
1544
+ room[id] = chrome.menu + widest(texts[id]) + chrome.gap;
1545
+ }
1546
+ room.display = chrome.display + Math.max(0, ...texts.display.map(([a, b]) => measure(a, "display") + measure(b, "display"))) + chrome.gap;
1547
+ return room;
1548
+ }
1549
+ function overflowLevel(width, narrow, room = TOOLBAR_ROOM) {
1550
+ const fixed = (narrow ? room.fields : 0) + room.display + room.sep + room.undo + room.redo + room.export;
1551
+ let level = 0;
1552
+ const need = (n) => fixed + OVERFLOW_ORDER.slice(n).reduce((sum, id) => sum + room[id], 0) + (n > 0 ? room.more : 0);
1553
+ while (level < OVERFLOW_ORDER.length && need(level) > width) {
1554
+ level += 1;
1555
+ }
1556
+ return level;
1557
+ }
1558
+
1559
+ // src/toolbar.jsx
1560
+ function TextButton({ icon, label, onClick, disabled, testId, shortcut }) {
1561
+ return /* @__PURE__ */ React9.createElement("button", { type: "button", className: "pk-btn", onClick, disabled, title: shortcut ? `${label} (${shortcut})` : void 0, "aria-keyshortcuts": shortcut ? shortcut.replace("\u2318", "Meta+").replace("\u21E7", "Shift+") : void 0, "data-testid": testId }, /* @__PURE__ */ React9.createElement(Icon, { name: icon }), /* @__PURE__ */ React9.createElement("span", { className: "pk-btn-text" }, label));
1562
+ }
1563
+ var measuring;
1564
+ var fontOf = (style) => `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
1565
+ function measuredRoom(el, texts) {
1566
+ const doc = el.ownerDocument;
1567
+ if (measuring === void 0) {
1568
+ try {
1569
+ measuring = doc.createElement("canvas").getContext("2d");
1570
+ } catch {
1571
+ measuring = null;
1572
+ }
1573
+ }
1574
+ const undo2 = el.querySelector("[data-testid='undo']");
1575
+ const menu = el.querySelector("[data-testid='export']");
1576
+ const display = el.querySelector(".pk-segmented");
1577
+ const sep = el.querySelector(".pk-sep");
1578
+ const textOf = (node) => node?.querySelector(".pk-btn-text, span");
1579
+ if (!measuring || !undo2 || !menu || !display || !textOf(undo2) || !textOf(display)) {
1580
+ return null;
1581
+ }
1582
+ const view = doc.defaultView;
1583
+ if (!view) {
1584
+ return null;
1585
+ }
1586
+ const fonts = { button: fontOf(view.getComputedStyle(
1587
+ /** @type {Element} */
1588
+ textOf(undo2)
1589
+ )), display: fontOf(view.getComputedStyle(
1590
+ /** @type {Element} */
1591
+ textOf(display)
1592
+ )) };
1593
+ const ctx = measuring;
1594
+ const measure = (text, kind) => {
1595
+ ctx.font = fonts[kind];
1596
+ return ctx.measureText(text).width;
1597
+ };
1598
+ const w = (node) => node.getBoundingClientRect().width;
1599
+ const tw = (node) => node ? node.getBoundingClientRect().width : 0;
1600
+ const segTexts = [...display.querySelectorAll("button > span")];
1601
+ const sepStyle = sep ? view.getComputedStyle(sep) : null;
1602
+ const chrome = {
1603
+ text: w(undo2) - tw(textOf(undo2)),
1604
+ menu: w(menu) - tw(textOf(menu)),
1605
+ display: w(display) - segTexts.reduce((n, s) => n + tw(s), 0),
1606
+ sep: sep && sepStyle ? w(sep) + parseFloat(sepStyle.marginLeft) + parseFloat(sepStyle.marginRight) : 0,
1607
+ // one more px per part: text widths are fractional, the buttons round them
1608
+ gap: (parseFloat(view.getComputedStyle(el).columnGap) || 0) + 1
1609
+ };
1610
+ return toolbarRoom(texts, measure, chrome);
1611
+ }
1612
+ function useOverflow(ref, key, narrow, max, texts) {
1613
+ const [level, setLevel] = useState7(0);
1614
+ const [measure, setMeasure] = useState7(0);
1615
+ const [lastKey, setLastKey] = useState7(key);
1616
+ const latest = useRef7(texts);
1617
+ useIsoLayoutEffect(() => {
1618
+ latest.current = texts;
1619
+ });
1620
+ if (key !== lastKey) {
1621
+ setLastKey(key);
1622
+ setMeasure((m) => m + 1);
1623
+ }
1624
+ useIsoLayoutEffect(() => {
1625
+ const el = ref.current;
1626
+ if (!el || typeof ResizeObserver !== "function") {
1627
+ return void 0;
1628
+ }
1629
+ let width = -1;
1630
+ const decide = () => {
1631
+ const em = parseFloat(getComputedStyle(el).fontSize) || 14;
1632
+ const room = measuredRoom(el, latest.current);
1633
+ setLevel(room ? overflowLevel(width, narrow, room) : overflowLevel(width / em, narrow));
1634
+ setMeasure((m) => m + 1);
1635
+ };
1636
+ const ro = new ResizeObserver(([entry]) => {
1637
+ const w = Math.round(entry.contentRect.width);
1638
+ if (w !== width) {
1639
+ width = w;
1640
+ decide();
1641
+ }
1642
+ });
1643
+ width = Math.round(el.getBoundingClientRect().width);
1644
+ decide();
1645
+ ro.observe(el);
1646
+ let live = true;
1647
+ el.ownerDocument.fonts?.ready.then(() => live && width >= 0 && decide(), () => void 0);
1648
+ return () => {
1649
+ live = false;
1650
+ ro.disconnect();
1651
+ };
1652
+ }, [ref, narrow, key]);
1653
+ useIsoLayoutEffect(() => {
1654
+ const el = ref.current;
1655
+ if (el && el.scrollWidth > el.clientWidth + 1 && level < max) {
1656
+ setLevel(level + 1);
1657
+ }
1658
+ }, [ref, level, measure, key, max]);
1659
+ return level;
1660
+ }
1661
+ function Toolbar(props) {
1662
+ const { view, labels, size, canUndo, canRedo, canReset, onUndo, onRedo, onReset, onDisplay, onChart, onChartDisplay, onTotal, onExpand, onCollapse, folding, templates, onLoadTemplate, templateActions, onExport, chartReady, onShowFields, layoutFolded, onLayout, zonesId, share } = props;
1663
+ const tips = { controls: props.tipsControls, on: props.tipsOn, onOn: props.onTipsOn, canReset: props.canResetTips, onReset: props.onResetTips };
1664
+ const bar = useRef7(
1665
+ /** @type {HTMLDivElement | null} */
1666
+ null
1667
+ );
1668
+ const more = useRef7(
1669
+ /** @type {HTMLButtonElement | null} */
1670
+ null
1671
+ );
1672
+ const viewsButton = useRef7(
1673
+ /** @type {HTMLButtonElement | null} */
1674
+ null
1675
+ );
1676
+ const [panel, setPanel] = useState7(
1677
+ /** @type {"options" | "views" | "chartType" | null} */
1678
+ null
1679
+ );
1680
+ const order = OVERFLOW_ORDER;
1681
+ const texts = useMemo4(() => toolbarTexts([LABELS.en, LABELS.de, labels]), [labels]);
1682
+ const level = useOverflow(bar, `${labels.lang}:${labels.undo}:${size}`, size === "narrow", order.length, texts);
1683
+ const hidden = new Set(order.slice(0, level));
1684
+ if (panel && !hidden.has(panel)) {
1685
+ setPanel(null);
1686
+ }
1687
+ const closePanel = useCallback4(() => setPanel(null), []);
1688
+ const request = props.viewsRequest ?? 0;
1689
+ const [seenRequest, setSeenRequest] = useState7(request);
1690
+ const [clickFor, setClickFor] = useState7(0);
1691
+ if (request !== seenRequest) {
1692
+ setSeenRequest(request);
1693
+ if (hidden.has("views")) {
1694
+ setPanel("views");
1695
+ } else {
1696
+ setClickFor(request);
1697
+ }
1698
+ }
1699
+ useEffect7(() => {
1700
+ const button = viewsButton.current;
1701
+ if (clickFor > 0 && button && button.getAttribute("aria-expanded") !== "true") {
1702
+ button.click();
1703
+ }
1704
+ }, [clickFor]);
1705
+ const plan = props.chartPlan ?? { name: chartTypeOf(view.chart), auto: false };
1706
+ const preset = plan.auto ? "auto" : plan.name;
1707
+ const drawnIcon = CHART_TYPES[plan.name].icon;
1708
+ const mod = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? "\u2318" : "Ctrl+";
1709
+ const chartTypeText = fill(labels.chartTypeIs, { type: labels.chartTypes[preset] });
1710
+ const panels = {
1711
+ // the panels load with the chip menus (menus.js), on demand
1712
+ options: (close) => /* @__PURE__ */ React9.createElement(MenuPanel, { name: "OptionsPanel", loadingText: labels.loadingMenu, props: { view, labels, onTotal, onExpand, onCollapse, close, tips, mod, folding, help: props.help } }),
1713
+ views: (close) => /* @__PURE__ */ React9.createElement(MenuPanel, { name: "ViewsPanel", loadingText: labels.loadingMenu, props: { templates, labels, onLoad: onLoadTemplate, actions: templateActions, close, share } }),
1714
+ chartType: (close) => /* @__PURE__ */ React9.createElement(MenuPanel, { name: "ChartTypePanel", loadingText: labels.loadingMenu, props: { view, plan, labels, onChart, onDisplay: onChartDisplay, close } })
1715
+ };
1716
+ const actions = {
1717
+ chartType: {
1718
+ place: "chart",
1719
+ button: () => /* @__PURE__ */ React9.createElement(MenuButton, { key: "chartType", label: chartTypeText, name: chartTypeText, title: chartTypeText, icon: drawnIcon, text: labels.chartTypes[preset], role: "dialog", testId: "chart-type", popoverClass: "pk-chart-menu" }, panels.chartType),
1720
+ entry: (close) => /* @__PURE__ */ React9.createElement(Option, { key: "chartType", inMenu: true, icon: drawnIcon, onSelect: () => {
1721
+ close();
1722
+ setPanel("chartType");
1723
+ }, testId: "more-chart-type" }, `${chartTypeText}\u2026`)
1724
+ },
1725
+ reset: {
1726
+ place: "history",
1727
+ button: () => /* @__PURE__ */ React9.createElement(TextButton, { key: "reset", icon: "reset", label: labels.reset, onClick: onReset, disabled: !canReset, testId: "reset" }),
1728
+ entry: (close) => /* @__PURE__ */ React9.createElement(Option, { key: "reset", inMenu: true, icon: "reset", disabled: !canReset, onSelect: () => {
1729
+ close();
1730
+ onReset();
1731
+ }, testId: "more-reset" }, labels.reset)
1732
+ },
1733
+ layout: {
1734
+ place: "end",
1735
+ // a toggle of the zones: the same text, open or folded; aria-pressed says which
1736
+ button: () => /* @__PURE__ */ React9.createElement("button", { key: "layout", type: "button", className: "pk-btn pk-pressable", onClick: onLayout, "aria-pressed": !layoutFolded, "aria-controls": zonesId, title: labels.showLayout, "data-testid": "layout" }, /* @__PURE__ */ React9.createElement(Icon, { name: "layout" }), /* @__PURE__ */ React9.createElement("span", { className: "pk-btn-text" }, labels.layout)),
1737
+ entry: (close) => /* @__PURE__ */ React9.createElement(Option, { key: "layout", inMenu: true, icon: "layout", checked: !layoutFolded, onSelect: () => {
1738
+ close();
1739
+ onLayout();
1740
+ }, testId: "more-layout" }, labels.layout)
1741
+ },
1742
+ options: {
1743
+ place: "end",
1744
+ button: () => /* @__PURE__ */ React9.createElement(MenuButton, { key: "options", label: labels.options, icon: "sliders", text: labels.options, role: "dialog", align: "end", testId: "options" }, panels.options),
1745
+ entry: (close) => /* @__PURE__ */ React9.createElement(Option, { key: "options", inMenu: true, icon: "sliders", onSelect: () => {
1746
+ close();
1747
+ setPanel("options");
1748
+ }, testId: "more-options" }, `${labels.options}\u2026`)
1749
+ },
1750
+ views: {
1751
+ place: "end",
1752
+ button: () => /* @__PURE__ */ React9.createElement(MenuButton, { key: "views", label: labels.views, icon: "bookmark", text: labels.views, role: "dialog", align: "end", testId: "views", buttonRef: viewsButton }, panels.views),
1753
+ entry: (close) => /* @__PURE__ */ React9.createElement(Option, { key: "views", inMenu: true, icon: "bookmark", onSelect: () => {
1754
+ close();
1755
+ setPanel("views");
1756
+ }, testId: "more-views" }, `${labels.views}\u2026`)
1757
+ }
1758
+ };
1759
+ const ORDER = Object.keys(actions);
1760
+ const buttons = (place) => ORDER.filter((id) => actions[id].place === place && !hidden.has(id)).map((id) => actions[id].button());
1761
+ return /* @__PURE__ */ React9.createElement("div", { className: `pk-toolbar${level >= order.length ? " pk-wrap" : ""}`, role: "toolbar", "aria-label": labels.toolbar, ref: bar, "data-overflow": level }, size === "narrow" ? /* @__PURE__ */ React9.createElement("button", { type: "button", className: "pk-btn", onClick: onShowFields, "data-testid": "show-fields", "data-pk-opener": "fields" }, /* @__PURE__ */ React9.createElement(Icon, { name: "panel" }), /* @__PURE__ */ React9.createElement("span", { className: "pk-btn-text" }, labels.showFields)) : null, /* @__PURE__ */ React9.createElement("div", { className: "pk-segmented", role: "group", "aria-label": labels.view }, /* @__PURE__ */ React9.createElement("button", { type: "button", "aria-pressed": view.display === "table", onClick: () => onDisplay("table"), "data-testid": "show-table" }, /* @__PURE__ */ React9.createElement(Icon, { name: "table" }), /* @__PURE__ */ React9.createElement("span", null, labels.table)), /* @__PURE__ */ React9.createElement("button", { type: "button", "aria-pressed": view.display === "chart", onClick: () => onDisplay("chart"), "data-testid": "show-chart" }, /* @__PURE__ */ React9.createElement(Icon, { name: (
1762
+ /** @type {any} */
1763
+ drawnIcon
1764
+ ) }), /* @__PURE__ */ React9.createElement("span", null, labels.chart))), buttons("chart"), /* @__PURE__ */ React9.createElement("span", { className: "pk-sep", "aria-hidden": "true" }), /* @__PURE__ */ React9.createElement("span", { className: "pk-toolbar-pair" }, /* @__PURE__ */ React9.createElement(TextButton, { icon: "undo", label: labels.undo, onClick: onUndo, disabled: !canUndo, testId: "undo", shortcut: `${mod}Z` }), /* @__PURE__ */ React9.createElement(TextButton, { icon: "redo", label: labels.redo, onClick: onRedo, disabled: !canRedo, testId: "redo", shortcut: `${mod}\u21E7Z` })), buttons("history"), /* @__PURE__ */ React9.createElement("span", { className: "pk-grow" }), buttons("end"), /* @__PURE__ */ React9.createElement(MenuButton, { label: labels.exportLabel, icon: "download", text: labels.exportLabel, role: "dialog", align: "end", testId: "export" }, (close) => /* @__PURE__ */ React9.createElement(MenuPanel, { name: "ExportPanel", loadingText: labels.loadingMenu, props: { labels, onExport, chartReady, display: view.display, prepare: props.prepareExport, close } })), level > 0 ? /* @__PURE__ */ React9.createElement(MenuButton, { label: labels.more, icon: "more", text: labels.more, align: "end", testId: "more", buttonRef: more }, (close) => ORDER.filter((id) => hidden.has(id)).map((id) => actions[id].entry(close))) : null, panel ? /* @__PURE__ */ React9.createElement(Popover, { open: true, anchor: more, onClose: closePanel, label: panel === "chartType" ? chartTypeText : panel === "views" ? labels.views : labels.options, role: "dialog", align: "end", className: panel === "chartType" ? "pk-chart-menu" : void 0 }, panels[panel](closePanel)) : null);
1765
+ }
1766
+
1767
+ // src/use-export.js
1768
+ function useExport(context) {
1769
+ return async (kind) => {
1770
+ try {
1771
+ const menus = menusNow() ?? await loadMenus();
1772
+ await menus.runExport(kind, context);
1773
+ } catch (e) {
1774
+ context.announce(fill(context.labels.toastExportFailed, { message: messageOf(e) }), { tone: "error" });
1775
+ }
1776
+ };
1777
+ }
1778
+ var prepareExporters = () => void loadMenus().then((m) => m.prepareExporters(), () => void 0);
1779
+
1780
+ // src/use-theme.js
1781
+ import { useCallback as useCallback5, useSyncExternalStore } from "react";
1782
+ function hostTheme(el) {
1783
+ let node = el;
1784
+ while (node) {
1785
+ if (node.nodeType === 1 && /** @type {Element} */
1786
+ node.hasAttribute("data-theme")) {
1787
+ return (
1788
+ /** @type {Element} */
1789
+ node.getAttribute("data-theme")
1790
+ );
1791
+ }
1792
+ node = node.parentNode ?? /** @type {ShadowRoot} */
1793
+ node.host ?? null;
1794
+ }
1795
+ return typeof document !== "undefined" ? document.documentElement.getAttribute("data-theme") : null;
1796
+ }
1797
+ var darkQuery = () => typeof matchMedia === "function" ? matchMedia("(prefers-color-scheme: dark)") : null;
1798
+ function useResolvedTheme(wanted, ref) {
1799
+ const subscribe = useCallback5(
1800
+ (onChange) => {
1801
+ if (wanted === "light" || wanted === "dark" || typeof document === "undefined") {
1802
+ return () => {
1803
+ };
1804
+ }
1805
+ const mo = typeof MutationObserver === "function" ? new MutationObserver(onChange) : null;
1806
+ const options = { attributes: true, attributeFilter: ["data-theme"], subtree: true };
1807
+ mo?.observe(document.documentElement, options);
1808
+ for (let root = ref.current?.getRootNode(); root && root.nodeType === 11; root = /** @type {ShadowRoot} */
1809
+ root.host.getRootNode()) {
1810
+ mo?.observe(root, options);
1811
+ }
1812
+ const mq = darkQuery();
1813
+ mq?.addEventListener("change", onChange);
1814
+ return () => {
1815
+ mo?.disconnect();
1816
+ mq?.removeEventListener("change", onChange);
1817
+ };
1818
+ },
1819
+ [wanted, ref]
1820
+ );
1821
+ const snapshot = () => resolveTheme(wanted, typeof document === "undefined" ? null : hostTheme(ref.current), darkQuery()?.matches ?? false);
1822
+ return useSyncExternalStore(subscribe, snapshot, () => resolveTheme(wanted, null, false));
1823
+ }
1824
+
1825
+ // src/use-view-history.js
1826
+ import { useCallback as useCallback6, useMemo as useMemo5, useState as useState8 } from "react";
1827
+ import { emptyView, normalize as normalize2 } from "pivotkit-core";
1828
+
1829
+ // src/view-history.js
1830
+ var HISTORY_LIMIT = 100;
1831
+ function createState(schema, start, current = start) {
1832
+ return { schema, start, present: current, past: [], future: [] };
1833
+ }
1834
+ function settle(state, at) {
1835
+ let s = state.schema === at.schema ? state : createState(at.schema, at.start, at.shown);
1836
+ if (s.present !== at.shown) {
1837
+ s = record(s, at.shown, at.outside);
1838
+ }
1839
+ return s;
1840
+ }
1841
+ function record(state, view, note) {
1842
+ if (view === state.present) {
1843
+ return state;
1844
+ }
1845
+ const past = [...state.past, { view: state.present, note }].slice(-HISTORY_LIMIT);
1846
+ return { ...state, present: view, past, future: [] };
1847
+ }
1848
+ function undo(state) {
1849
+ const last = state.past[state.past.length - 1];
1850
+ if (!last) {
1851
+ return { state, note: null };
1852
+ }
1853
+ return {
1854
+ state: { ...state, present: last.view, past: state.past.slice(0, -1), future: [...state.future, { view: state.present, note: last.note }] },
1855
+ note: last.note
1856
+ };
1857
+ }
1858
+ function redo(state) {
1859
+ const next = state.future[state.future.length - 1];
1860
+ if (!next) {
1861
+ return { state, note: null };
1862
+ }
1863
+ return {
1864
+ state: { ...state, present: next.view, future: state.future.slice(0, -1), past: [...state.past, { view: state.present, note: next.note }] },
1865
+ note: next.note
1866
+ };
1867
+ }
1868
+ function reset(state, note) {
1869
+ return record(state, state.start, note);
1870
+ }
1871
+
1872
+ // src/use-view-history.js
1873
+ function schemaKeyOf(encoded) {
1874
+ return JSON.stringify(encoded.schema.fields.map((f) => [f.name, f.type]));
1875
+ }
1876
+ function useViewHistory({ encoded, view, defaultView, onViewChange, limits, outsideNote, orderOf }) {
1877
+ const controlled = view !== void 0;
1878
+ const schema = useMemo5(() => schemaKeyOf(encoded), [encoded]);
1879
+ const json = useCallback6(
1880
+ (v) => {
1881
+ const normalized = normalize2(v ?? emptyView(), encoded, { limits }).view;
1882
+ const ordered = orderOf ? withHostOrders(normalized, orderOf) : normalized;
1883
+ return JSON.stringify(ordered === normalized ? normalized : normalize2(ordered, encoded, { limits }).view);
1884
+ },
1885
+ [encoded, limits, orderOf]
1886
+ );
1887
+ const [initial] = useState8(() => (controlled ? view : defaultView) ?? null);
1888
+ const start = useMemo5(() => json(initial), [json, initial]);
1889
+ const [state, setState] = useState8(() => createState(schema, start));
1890
+ const viewKey = controlled ? JSON.stringify(view) : null;
1891
+ const shown = useMemo5(() => {
1892
+ if (viewKey !== null) {
1893
+ return json(JSON.parse(viewKey));
1894
+ }
1895
+ return state.schema === schema ? state.present : json(JSON.parse(state.present));
1896
+ }, [viewKey, json, state, schema]);
1897
+ const current = useMemo5(() => (
1898
+ /** @type {import("pivotkit-core").View} */
1899
+ JSON.parse(shown)
1900
+ ), [shown]);
1901
+ const live = useMemo5(() => settle(state, { schema, start, shown, outside: outsideNote }), [state, schema, start, shown, outsideNote]);
1902
+ const apply = useCallback6(
1903
+ (next) => {
1904
+ setState(next);
1905
+ onViewChange?.(JSON.parse(next.present));
1906
+ },
1907
+ [onViewChange]
1908
+ );
1909
+ const commit = useCallback6(
1910
+ (next, note) => {
1911
+ const s = record(live, json(next), note);
1912
+ if (s === live) {
1913
+ return false;
1914
+ }
1915
+ apply(s);
1916
+ return true;
1917
+ },
1918
+ [live, json, apply]
1919
+ );
1920
+ const undo2 = useCallback6(() => {
1921
+ const { state: s, note } = undo(live);
1922
+ if (note !== null) {
1923
+ apply(s);
1924
+ }
1925
+ return note;
1926
+ }, [live, apply]);
1927
+ const redo2 = useCallback6(() => {
1928
+ const { state: s, note } = redo(live);
1929
+ if (note !== null) {
1930
+ apply(s);
1931
+ }
1932
+ return note;
1933
+ }, [live, apply]);
1934
+ const reset2 = useCallback6(
1935
+ (note) => {
1936
+ const s = reset(live, note);
1937
+ if (s !== live) {
1938
+ apply(s);
1939
+ }
1940
+ },
1941
+ [live, apply]
1942
+ );
1943
+ const restore = useCallback6((next) => apply(createState(schema, start, json(next))), [schema, start, json, apply]);
1944
+ const canUndo = live.past.length > 0;
1945
+ const canRedo = live.future.length > 0;
1946
+ const canReset = live.present !== live.start;
1947
+ return useMemo5(
1948
+ () => ({ view: current, viewKey: shown, commit, undo: undo2, redo: redo2, reset: reset2, restore, canUndo, canRedo, canReset }),
1949
+ [current, shown, commit, undo2, redo2, reset2, restore, canUndo, canRedo, canReset]
1950
+ );
1951
+ }
1952
+
1953
+ // src/use-big-result.js
1954
+ import { useCallback as useCallback7, useEffect as useEffect8, useRef as useRef8, useState as useState9, useSyncExternalStore as useSyncExternalStore2 } from "react";
1955
+ function fullScreenSupported() {
1956
+ return typeof document !== "undefined" && Boolean(document.fullscreenEnabled) && typeof HTMLElement !== "undefined" && typeof HTMLElement.prototype.requestFullscreen === "function";
1957
+ }
1958
+ var never = () => () => {
1959
+ };
1960
+ function useBigResult(root) {
1961
+ const [enlarged, setEnlarged] = useState9(false);
1962
+ const [full, setFull] = useState9(false);
1963
+ const fullOk = useSyncExternalStore2(never, fullScreenSupported, () => false);
1964
+ useEffect8(() => {
1965
+ const el = root.current;
1966
+ if (!el) {
1967
+ return void 0;
1968
+ }
1969
+ const doc = el.ownerDocument;
1970
+ const sync = () => setFull(
1971
+ /** @type {any} */
1972
+ rootOf(el)?.fullscreenElement === el
1973
+ );
1974
+ doc.addEventListener("fullscreenchange", sync);
1975
+ return () => doc.removeEventListener("fullscreenchange", sync);
1976
+ }, [root]);
1977
+ const toggleEnlarged = useCallback7(() => setEnlarged((on) => !on), []);
1978
+ const toggleFull = () => {
1979
+ const el = root.current;
1980
+ if (!el) {
1981
+ return;
1982
+ }
1983
+ if (
1984
+ /** @type {any} */
1985
+ rootOf(el)?.fullscreenElement === el
1986
+ ) {
1987
+ el.ownerDocument.exitFullscreen?.().catch(() => void 0);
1988
+ } else {
1989
+ el.requestFullscreen?.().catch(() => void 0);
1990
+ }
1991
+ };
1992
+ return { enlarged, setEnlarged, toggleEnlarged, full, fullOk, toggleFull };
1993
+ }
1994
+ function useFitHeight(root, main, grow) {
1995
+ const fit = useRef8({ need: 0, open: 0, grow });
1996
+ useIsoLayoutEffect(() => {
1997
+ fit.current.grow = grow;
1998
+ measureFit(root.current, main.current, fit);
1999
+ });
2000
+ useIsoLayoutEffect(() => {
2001
+ const el = root.current;
2002
+ if (!el || typeof ResizeObserver !== "function") {
2003
+ return void 0;
2004
+ }
2005
+ let frame = 0;
2006
+ const ro = new ResizeObserver(() => {
2007
+ cancelAnimationFrame(frame);
2008
+ frame = requestAnimationFrame(() => measureFit(root.current, main.current, fit));
2009
+ });
2010
+ ro.observe(el);
2011
+ return () => {
2012
+ cancelAnimationFrame(frame);
2013
+ ro.disconnect();
2014
+ };
2015
+ }, [root, main]);
2016
+ return fit;
2017
+ }
2018
+ function measureFit(el, m, fit) {
2019
+ const result = m?.querySelector(":scope > .pk-result");
2020
+ if (!el || !m || !(result instanceof HTMLElement)) {
2021
+ return;
2022
+ }
2023
+ const least = parseFloat(el.ownerDocument.defaultView?.getComputedStyle(result).getPropertyValue("--pk-result-least") ?? "") || 0;
2024
+ const needMain = m.scrollHeight - result.offsetHeight + least;
2025
+ const need = Math.ceil(el.offsetHeight - m.clientHeight + needMain);
2026
+ if (!el.hasAttribute("data-pk-layout") && !el.hasAttribute("data-pk-enlarged")) {
2027
+ fit.current.open = need;
2028
+ }
2029
+ if (!fit.current.grow) {
2030
+ fit.current.need = 0;
2031
+ el.style.minHeight = "";
2032
+ } else if (Math.abs(need - fit.current.need) > 1) {
2033
+ fit.current.need = need;
2034
+ el.style.minHeight = `${need}px`;
2035
+ }
2036
+ }
2037
+
2038
+ // src/version.js
2039
+ var VERSION = true ? "0.1.0" : "0.0.0-source";
2040
+
2041
+ // src/zones.jsx
2042
+ import React10, { useCallback as useCallback8, useEffect as useEffect9, useMemo as useMemo6, useRef as useRef9, useState as useState10 } from "react";
2043
+ import { fieldItems, fieldLabel as fieldLabel2 } from "pivotkit-core";
2044
+ function fieldState(view, field, encoded, locale) {
2045
+ const items = filtersOf(view, field, ["include", "exclude"]).filter((f) => f.type === "include" || f.items.length > 0);
2046
+ let summary = null;
2047
+ if (items.length) {
2048
+ const info = fieldItems(encoded, field, { view, locale });
2049
+ if (info) {
2050
+ const all = info.items.map((i) => i.value);
2051
+ summary = { shown: selectedItems(view, field, all).length, total: all.length };
2052
+ }
2053
+ }
2054
+ const top = filtersOf(view, field, ["top"])[0] ?? null;
2055
+ const condition = filtersOf(view, field, ["value"])[0] ?? null;
2056
+ const other = filtersOf(view, field, ["label"]).length > 0;
2057
+ return { summary, top, condition, other, sort: sortOf(view, field) };
2058
+ }
2059
+ function stateWords(state, view, labels, locale) {
2060
+ if (!state) {
2061
+ return "";
2062
+ }
2063
+ const words = [];
2064
+ if (state.summary) {
2065
+ words.push(`${labels.stateFiltered} ${fill(labels.filterSummary, { shown: state.summary.shown.toLocaleString(locale), total: state.summary.total.toLocaleString(locale) })}`);
2066
+ } else if (state.other) {
2067
+ words.push(labels.stateFiltered);
2068
+ }
2069
+ if (state.top) {
2070
+ words.push(fill(state.top.bottom ? labels.bottomBadge : labels.topBadge, { count: state.top.count.toLocaleString(locale) }));
2071
+ }
2072
+ if (state.condition) {
2073
+ words.push(valueConditionText(view, state.condition, labels, locale));
2074
+ }
2075
+ if (state.sort) {
2076
+ const desc = state.sort.order === "desc";
2077
+ const order = state.sort.by === "value" ? fill(desc ? labels.sortValueDesc : labels.sortValueAsc, { value: refLabel(view, state.sort.value, labels) }) : state.sort.by === "custom" ? desc ? labels.sortCustomDesc : labels.sortCustom : desc ? labels.sortLabelDesc : labels.sortLabelAsc;
2078
+ words.push(fill(labels.stateSorted, { order }));
2079
+ }
2080
+ return words.join(", ");
2081
+ }
2082
+ function Badges({ state, view, labels, locale }) {
2083
+ const parts = [];
2084
+ if (state.summary) {
2085
+ const text = fill(labels.filterSummary, { shown: state.summary.shown.toLocaleString(locale), total: state.summary.total.toLocaleString(locale) });
2086
+ parts.push(
2087
+ /* @__PURE__ */ React10.createElement("span", { key: "filter", className: "pk-chip-badge pk-badge-text" }, /* @__PURE__ */ React10.createElement(Icon, { name: "filter", size: 12 }), text)
2088
+ );
2089
+ } else if (state.other) {
2090
+ parts.push(/* @__PURE__ */ React10.createElement(Icon, { key: "filter", name: "filter", size: 12, className: "pk-chip-badge" }));
2091
+ }
2092
+ if (state.top) {
2093
+ const text = fill(state.top.bottom ? labels.bottomBadge : labels.topBadge, { count: state.top.count.toLocaleString(locale) });
2094
+ parts.push(
2095
+ /* @__PURE__ */ React10.createElement("span", { key: "top", className: "pk-chip-badge pk-badge-text", "data-testid": "top-badge" }, /* @__PURE__ */ React10.createElement(Icon, { name: "top", size: 12 }), text)
2096
+ );
2097
+ }
2098
+ if (state.condition) {
2099
+ const text = valueConditionText(view, state.condition, labels, locale);
2100
+ parts.push(
2101
+ /* @__PURE__ */ React10.createElement("span", { key: "condition", className: "pk-chip-badge pk-badge-text pk-badge-condition", "data-testid": "condition-badge", title: text }, /* @__PURE__ */ React10.createElement(Icon, { name: "filter", size: 12 }), /* @__PURE__ */ React10.createElement("span", { className: "pk-badge-cut" }, text))
2102
+ );
2103
+ }
2104
+ if (state.sort) {
2105
+ const desc = state.sort.order === "desc";
2106
+ parts.push(/* @__PURE__ */ React10.createElement(Icon, { key: "sort", name: desc ? "sortDesc" : "sortAsc", size: 12, className: "pk-chip-badge" }));
2107
+ }
2108
+ if (!parts.length) {
2109
+ return null;
2110
+ }
2111
+ return /* @__PURE__ */ React10.createElement("span", { className: "pk-badges-inline", "aria-hidden": "true" }, parts);
2112
+ }
2113
+ function Chip({ id, zone, index, count, field, text, typeName, view, types, labels, commit, openFilter, onRemove, state, locale, defaultsOf, rangeOf, info, showInfo }) {
2114
+ const { setNodeRef, isDragging, style, itemProps, handleProps } = useChip(id, { kind: "chip", zone, index, count, field, label: text, type: typeName });
2115
+ const chipRef = useRef9(
2116
+ /** @type {HTMLElement | null} */
2117
+ null
2118
+ );
2119
+ const ref = (el) => {
2120
+ chipRef.current = el;
2121
+ setNodeRef(el);
2122
+ };
2123
+ const badges = state ? /* @__PURE__ */ React10.createElement(Badges, { state, view, labels, locale }) : null;
2124
+ const words = stateWords(state, view, labels, locale);
2125
+ const name = words ? `${text}, ${words}` : void 0;
2126
+ const remove = () => onRemove(zone, index, text);
2127
+ return /* @__PURE__ */ React10.createElement("li", { ref, style, className: `pk-chip pk-chip-${zone}${isDragging ? " pk-dragging" : ""}`, ...itemProps, "data-chip": text }, /* @__PURE__ */ React10.createElement("span", { className: "pk-handle", ...handleProps, "aria-label": fill(labels.dragHandle, { field: text }) }, /* @__PURE__ */ React10.createElement(Icon, { name: "grip", size: 16 })), /* @__PURE__ */ React10.createElement("span", { className: `pk-type pk-type-${typeName}`, "aria-hidden": "true" }, /* @__PURE__ */ React10.createElement(Icon, { name: (
2128
+ /** @type {any} */
2129
+ TYPE_ICON[typeName] ?? "text"
2130
+ ), size: 13 })), zone === "filters" ? /* @__PURE__ */ React10.createElement("button", { type: "button", className: "pk-chip-label", onClick: (e) => openFilter(field, e.currentTarget.closest(".pk-chip")), title: fill(labels.filterTitle, { field: text }), "aria-label": name }, /* @__PURE__ */ React10.createElement("span", { className: "pk-btn-text" }, /* @__PURE__ */ React10.createElement("span", { className: "pk-chip-name" }, text), badges)) : /* @__PURE__ */ React10.createElement(
2131
+ MenuButton,
2132
+ {
2133
+ label: fill(labels.fieldMenu, { field: text }),
2134
+ text: /* @__PURE__ */ React10.createElement(React10.Fragment, null, /* @__PURE__ */ React10.createElement("span", { className: "pk-chip-name" }, text), badges),
2135
+ className: "pk-chip-label",
2136
+ name,
2137
+ role: "dialog",
2138
+ popoverClass: "pk-chip-menu",
2139
+ fill: true,
2140
+ testId: `chip-menu-${text}`
2141
+ },
2142
+ (close) => zone === "values" ? /* @__PURE__ */ React10.createElement(MenuPanel, { name: "ValueMenu", loadingText: labels.loadingMenu, props: { view, index, types, labels, commit, close, onRemove: remove, defaultsOf, info } }) : /* @__PURE__ */ React10.createElement(MenuPanel, { name: "AxisMenu", loadingText: labels.loadingMenu, props: { view, zone, index, field, types, labels, commit, close, openFilter, chipRef, onRemove: remove, defaultsOf, rangeOf, locale, info, state } })
2143
+ ), info && showInfo ? /* @__PURE__ */ React10.createElement(InfoButton, { info, name: fieldLabel2(sourceOf(view, field), labels.core), labels, className: "pk-chip-info" }) : null, /* @__PURE__ */ React10.createElement("button", { type: "button", className: "pk-chip-x", onClick: remove, "aria-label": fill(labels.removeField, { field: text }), title: fill(labels.removeField, { field: text }) }, /* @__PURE__ */ React10.createElement(Icon, { name: "x", size: 14 })));
2144
+ }
2145
+ function Zone({ zone, entries: entries2, labels, children, action, explain }) {
2146
+ const count = entries2.length;
2147
+ const { setNodeRef, isOver } = useDropTarget(`zone:${zone}`, { kind: "zone", zone, count });
2148
+ const active = useActiveDrag();
2149
+ const dragging = Boolean(active);
2150
+ const [flash, setFlash] = useState10(false);
2151
+ const [prev, setPrev] = useState10(count);
2152
+ if (count !== prev) {
2153
+ setPrev(count);
2154
+ if (count > prev) {
2155
+ setFlash(true);
2156
+ }
2157
+ }
2158
+ useEffect9(() => {
2159
+ if (!flash) {
2160
+ return void 0;
2161
+ }
2162
+ const t = setTimeout(() => setFlash(false), 600);
2163
+ return () => clearTimeout(t);
2164
+ }, [flash]);
2165
+ return /* @__PURE__ */ React10.createElement("section", { ref: setNodeRef, tabIndex: -1, className: `pk-zone pk-zone-${zone}${isOver ? " pk-over" : ""}${dragging ? " pk-dropping" : ""}${flash ? " pk-flash" : ""}`, "aria-label": labels.zones[zone], "data-zone": zone }, /* @__PURE__ */ React10.createElement("div", { className: "pk-zone-head" }, /* @__PURE__ */ React10.createElement("h3", { className: "pk-zone-title" }, /* @__PURE__ */ React10.createElement(Icon, { name: (
2166
+ /** @type {any} */
2167
+ ZONE_ICON[zone]
2168
+ ), size: 14 }), labels.zones[zone]), explain ? /* @__PURE__ */ React10.createElement(InfoButton, { info: { description: labels.zoneInfo[zone] }, name: labels.zones[zone], labels, className: "pk-zone-info", testId: `zone-info-${zone}` }) : null, /* @__PURE__ */ React10.createElement("span", { className: "pk-grow" }), action), /* @__PURE__ */ React10.createElement(ChipList, { ids: entries2.map((e) => e.id) }, /* @__PURE__ */ React10.createElement("ul", { className: "pk-chips" }, children, count === 0 ? /* @__PURE__ */ React10.createElement("li", { className: "pk-zone-hint" }, labels.zoneHints[zone]) : null)));
2169
+ }
2170
+ function zoneEntries(view, types, labels) {
2171
+ const typeOf = (f) => types.get(String(sourceOf(view, f)).toLowerCase()) ?? "string";
2172
+ const seen = /* @__PURE__ */ new Map();
2173
+ const text = (f) => fieldLabel2(f, labels.core);
2174
+ const axis = (zone) => view[zone].map((f, i) => ({ id: `chip:${zone}:${f}`, field: f, text: text(f), type: typeOf(f), index: i }));
2175
+ return {
2176
+ filters: filterZoneFields(view).map((f, i) => ({ id: `chip:filters:${f}`, field: f, text: text(f), type: typeOf(f), index: i })),
2177
+ cols: axis("cols"),
2178
+ rows: axis("rows"),
2179
+ values: view.values.map((v, i) => {
2180
+ const key = `${v.agg}:${v.field}`;
2181
+ seen.set(key, (seen.get(key) ?? 0) + 1);
2182
+ return { id: `chip:values:${key}:${seen.get(key)}`, field: v.field, text: valueLabel(v, labels), type: v.field ? typeOf(v.field) : "number", index: i };
2183
+ })
2184
+ };
2185
+ }
2186
+ function ZoneSummary({ entries: entries2, labels, id, onShow, buttonRef }) {
2187
+ const parts = layoutSummary(entries2, labels);
2188
+ const text = parts.length ? parts.map((p) => `${p.title}: ${p.fields}`).join(" \xB7 ") : labels.layoutEmpty;
2189
+ return /* @__PURE__ */ React10.createElement("button", { ref: buttonRef, type: "button", id, className: "pk-zones-summary", "aria-expanded": "false", "aria-label": `${labels.showLayout}: ${text}`, title: labels.showLayout, onClick: onShow, "data-testid": "layout-summary" }, /* @__PURE__ */ React10.createElement(Icon, { name: "chevronRight", size: 16 }), /* @__PURE__ */ React10.createElement("span", { className: "pk-zones-summary-text" }, parts.length ? parts.map((p, i) => /* @__PURE__ */ React10.createElement(React10.Fragment, { key: p.zone }, i ? /* @__PURE__ */ React10.createElement("span", { "aria-hidden": "true" }, " \xB7 ") : null, /* @__PURE__ */ React10.createElement("span", { className: "pk-zones-summary-zone" }, p.title, ":"), " ", p.fields)) : labels.layoutEmpty));
2190
+ }
2191
+ function Zones({ view, types, labels, commit, openFilter, encoded, locale, onSwap, id, folded, onShow, defaultsOf, infoOf, explain = false, showInfo = true }) {
2192
+ const entries2 = useMemo6(() => zoneEntries(view, types, labels), [view, types, labels]);
2193
+ const dragging = Boolean(useActiveDrag());
2194
+ const showing = useRef9(false);
2195
+ const focusInside = useRef9(false);
2196
+ const summary = useRef9(
2197
+ /** @type {HTMLButtonElement | null} */
2198
+ null
2199
+ );
2200
+ const states = useMemo6(() => {
2201
+ const map = /* @__PURE__ */ new Map();
2202
+ for (const zone of ["filters", "cols", "rows"]) {
2203
+ for (const e of entries2[zone]) {
2204
+ map.set(e.field, fieldState(view, e.field, encoded, locale));
2205
+ }
2206
+ }
2207
+ return map;
2208
+ }, [entries2, view, encoded, locale]);
2209
+ const rangeOf = useCallback8((field) => numberRange(encoded, field), [encoded]);
2210
+ const root = useRef9(
2211
+ /** @type {HTMLDivElement | null} */
2212
+ null
2213
+ );
2214
+ const focusAfter = useRef9(
2215
+ /** @type {{ zone: string, index: number } | null} */
2216
+ null
2217
+ );
2218
+ const onRemove = (zone, index, text) => {
2219
+ focusAfter.current = { zone, index };
2220
+ commit(removeAt(view, zone, index), { step: "removed", field: text, removed: true });
2221
+ };
2222
+ useEffect9(() => {
2223
+ const at = focusAfter.current;
2224
+ if (!at || !root.current) {
2225
+ return;
2226
+ }
2227
+ focusAfter.current = null;
2228
+ const zone = root.current.querySelector(`[data-zone="${at.zone}"]`);
2229
+ const chips = zone ? [...zone.querySelectorAll(".pk-chip .pk-chip-label")] : [];
2230
+ const target = (
2231
+ /** @type {HTMLElement | null} */
2232
+ chips[Math.min(at.index, chips.length - 1)] ?? zone
2233
+ );
2234
+ target?.focus({ preventScroll: true });
2235
+ });
2236
+ useEffect9(() => {
2237
+ if (showing.current && !folded) {
2238
+ showing.current = false;
2239
+ root.current?.querySelector("[data-zone]")?.focus({ preventScroll: true });
2240
+ }
2241
+ if (folded && focusInside.current) {
2242
+ focusInside.current = false;
2243
+ summary.current?.focus({ preventScroll: true });
2244
+ }
2245
+ }, [folded]);
2246
+ if (folded && !dragging) {
2247
+ return /* @__PURE__ */ React10.createElement(
2248
+ ZoneSummary,
2249
+ {
2250
+ entries: entries2,
2251
+ labels,
2252
+ id,
2253
+ buttonRef: summary,
2254
+ onShow: () => {
2255
+ showing.current = true;
2256
+ onShow();
2257
+ }
2258
+ }
2259
+ );
2260
+ }
2261
+ return /* @__PURE__ */ React10.createElement(
2262
+ "div",
2263
+ {
2264
+ className: "pk-zones",
2265
+ ref: root,
2266
+ id,
2267
+ onFocus: () => {
2268
+ focusInside.current = true;
2269
+ },
2270
+ onBlur: (e) => {
2271
+ if (e.relatedTarget && !e.currentTarget.contains(
2272
+ /** @type {Node} */
2273
+ e.relatedTarget
2274
+ )) {
2275
+ focusInside.current = false;
2276
+ }
2277
+ }
2278
+ },
2279
+ ZONES.map((zone) => /* @__PURE__ */ React10.createElement(
2280
+ Zone,
2281
+ {
2282
+ key: zone,
2283
+ zone,
2284
+ entries: entries2[zone],
2285
+ labels,
2286
+ explain,
2287
+ action: zone === "cols" ? (
2288
+ // the text goes when the zone is too narrow (styles.css): the title keeps it as a tooltip
2289
+ /* @__PURE__ */ React10.createElement("button", { type: "button", className: "pk-link pk-swap", onClick: onSwap, disabled: view.rows.length + view.cols.length === 0, "data-testid": "swap", title: labels.swap }, /* @__PURE__ */ React10.createElement(Icon, { name: "swap", size: 14 }), /* @__PURE__ */ React10.createElement("span", { className: "pk-btn-text" }, labels.swap))
2290
+ ) : null
2291
+ },
2292
+ entries2[zone].map((e) => /* @__PURE__ */ React10.createElement(
2293
+ Chip,
2294
+ {
2295
+ key: e.id,
2296
+ id: e.id,
2297
+ zone,
2298
+ index: e.index,
2299
+ count: entries2[zone].length,
2300
+ field: e.field,
2301
+ text: e.text,
2302
+ typeName: e.type,
2303
+ view,
2304
+ types,
2305
+ labels,
2306
+ commit,
2307
+ openFilter,
2308
+ onRemove,
2309
+ state: zone === "values" ? null : states.get(e.field),
2310
+ locale,
2311
+ defaultsOf,
2312
+ rangeOf,
2313
+ info: e.field ? infoOf?.(e.field) : void 0,
2314
+ showInfo
2315
+ }
2316
+ ))
2317
+ ))
2318
+ );
2319
+ }
2320
+
2321
+ // src/PivotReport.jsx
2322
+ function sizeOf(width) {
2323
+ return width < 640 ? "narrow" : width < 1024 ? "medium" : "wide";
2324
+ }
2325
+ var COMPACT_HEIGHT = 600;
2326
+ var COMPACT_HEIGHT_NARROW = 820;
2327
+ var compactAt = (size, height) => height < (size === "narrow" ? COMPACT_HEIGHT_NARROW : COMPACT_HEIGHT);
2328
+ var layerOpen = (layer) => Boolean(layer && [...layer.children].some((c) => !c.classList.contains("pk-origin")));
2329
+ function measured(name, fn) {
2330
+ const t0 = typeof performance !== "undefined" ? performance.now() : 0;
2331
+ const out = fn();
2332
+ if (typeof performance !== "undefined" && typeof performance.measure === "function") {
2333
+ try {
2334
+ performance.measure(`pivotkit:${name}`, { start: t0, end: performance.now() });
2335
+ } catch {
2336
+ }
2337
+ }
2338
+ return out;
2339
+ }
2340
+ function pathTitle(result, rowPath, colPath, labels) {
2341
+ const parts = [];
2342
+ const items = [];
2343
+ const add = (axis, fields, path) => {
2344
+ const node = findNode(result, axis, path);
2345
+ for (let n = node; n && n.parent; n = n.parent) {
2346
+ const item = result.label(axis, n, labels.core);
2347
+ parts.unshift(`${fieldLabel3(fields[n.depth - 1], labels.core)}: ${item}`);
2348
+ items.unshift(item);
2349
+ }
2350
+ };
2351
+ add("cols", result.colFields, colPath);
2352
+ add("rows", result.rowFields, rowPath);
2353
+ return { title: parts.length ? parts.join(" \xB7 ") : labels.core.grandTotal, name: items.length ? items.join(" \u2013 ") : labels.core.grandTotal };
2354
+ }
2355
+ function outerPaths(result) {
2356
+ const depth = result.rowFields.length;
2357
+ const out = [];
2358
+ const walk = (node) => {
2359
+ if (node.depth > 0 && node.depth < depth) {
2360
+ out.push(node.path);
2361
+ }
2362
+ if (node.depth < depth - 1) {
2363
+ node.children.forEach(walk);
2364
+ }
2365
+ };
2366
+ walk(result.rowRoot);
2367
+ return out;
2368
+ }
2369
+ function sessionStore() {
2370
+ try {
2371
+ return typeof window !== "undefined" && window.sessionStorage ? window.sessionStorage : null;
2372
+ } catch {
2373
+ return null;
2374
+ }
2375
+ }
2376
+ var warned = /* @__PURE__ */ new Set();
2377
+ var warnOnce = (text) => {
2378
+ if (!warned.has(text)) {
2379
+ warned.add(text);
2380
+ console.warn(text);
2381
+ }
2382
+ };
2383
+ function optionsKey(options) {
2384
+ try {
2385
+ return JSON.stringify(options ?? null, (k, v) => ["function", "symbol", "bigint"].includes(typeof v) ? `\0${typeof v}` : v);
2386
+ } catch {
2387
+ return options;
2388
+ }
2389
+ }
2390
+ var here = () => typeof location !== "undefined" ? { href: location.href, hash: location.hash } : void 0;
2391
+ var DEFER_ROWS = 1e4;
2392
+ function PivotReport(props) {
2393
+ const { loading: loading2 = false, data, encoded } = props;
2394
+ const [deferred, setDeferred] = useState11(() => !encoded && Array.isArray(data) && data.length > DEFER_ROWS);
2395
+ const [started, setStarted] = useState11(false);
2396
+ useEffect10(() => {
2397
+ if (!deferred) {
2398
+ return void 0;
2399
+ }
2400
+ let timer = 0;
2401
+ const frame = requestAnimationFrame(() => {
2402
+ timer = window.setTimeout(() => setDeferred(false), 0);
2403
+ });
2404
+ return () => {
2405
+ cancelAnimationFrame(frame);
2406
+ clearTimeout(timer);
2407
+ };
2408
+ }, [deferred]);
2409
+ const waiting = Boolean(loading2) || deferred;
2410
+ if (!waiting && !started) {
2411
+ setStarted(true);
2412
+ }
2413
+ if (waiting && !started) {
2414
+ return /* @__PURE__ */ React11.createElement(WaitingReport, { ...props });
2415
+ }
2416
+ return /* @__PURE__ */ React11.createElement(Report, { ...props });
2417
+ }
2418
+ function WaitingReport({ locale = "en-US", labels: customLabels, theme = "auto", height = 640, className, label }) {
2419
+ const root = useRef10(
2420
+ /** @type {HTMLDivElement | null} */
2421
+ null
2422
+ );
2423
+ const labelsKey = JSON.stringify(customLabels ?? null);
2424
+ const labels = useMemo7(() => resolveLabels(locale, JSON.parse(labelsKey)), [locale, labelsKey]);
2425
+ const themeName = useResolvedTheme(theme, root);
2426
+ return /* @__PURE__ */ React11.createElement("div", { ref: root, className: `pk-root${className ? ` ${className}` : ""}`, "data-pk-theme": themeName, lang: labels.lang, role: "region", "aria-label": label || labels.report, style: { height } }, /* @__PURE__ */ React11.createElement(Skeleton, { full: true, text: labels.loadingReport }));
2427
+ }
2428
+ function defaultsFor(fieldDefaults, field) {
2429
+ if (!fieldDefaults || typeof fieldDefaults !== "object") {
2430
+ return void 0;
2431
+ }
2432
+ const key = Object.keys(fieldDefaults).find((k) => k.toLowerCase() === String(field).toLowerCase());
2433
+ return key === void 0 ? void 0 : fieldDefaults[key];
2434
+ }
2435
+ function EmptyState({ labels, templates, onTemplate }) {
2436
+ return /* @__PURE__ */ React11.createElement("div", { className: "pk-empty", "data-testid": "empty-state" }, /* @__PURE__ */ React11.createElement("div", { className: "pk-empty-art", "aria-hidden": "true" }, /* @__PURE__ */ React11.createElement("span", { className: "pk-empty-chip pk-c1" }), /* @__PURE__ */ React11.createElement("span", { className: "pk-empty-chip pk-c2" }), /* @__PURE__ */ React11.createElement("span", { className: "pk-empty-chip pk-c3" })), /* @__PURE__ */ React11.createElement("h2", null, labels.emptyTitle), /* @__PURE__ */ React11.createElement("ol", { className: "pk-steps" }, labels.emptySteps.map((s, i) => /* @__PURE__ */ React11.createElement("li", { key: i }, /* @__PURE__ */ React11.createElement("span", { className: "pk-step-n", "aria-hidden": "true" }, i + 1), /* @__PURE__ */ React11.createElement("span", null, s)))), templates.length ? /* @__PURE__ */ React11.createElement("div", { className: "pk-empty-actions" }, templates.slice(0, 3).map((t, i) => /* @__PURE__ */ React11.createElement("button", { key: `${i}:${t.name}`, type: "button", className: "pk-btn", onClick: () => onTemplate(t) }, /* @__PURE__ */ React11.createElement(Icon, { name: "sparkle" }), /* @__PURE__ */ React11.createElement("span", { className: "pk-btn-text" }, fill(labels.tryView, { name: t.name }))))) : null);
2437
+ }
2438
+ function Report(props) {
2439
+ const {
2440
+ data,
2441
+ dataKey,
2442
+ encoded: encodedProp,
2443
+ view: viewProp,
2444
+ defaultView,
2445
+ onViewChange,
2446
+ templates = [],
2447
+ onSaveTemplate,
2448
+ onDeleteTemplate,
2449
+ onPublishTemplate,
2450
+ canPublish = false,
2451
+ templateStore,
2452
+ onCellClick,
2453
+ drillDown = true,
2454
+ drillDownLimit = DRILL_LIMIT,
2455
+ locale = "en-US",
2456
+ timeZone,
2457
+ labels: customLabels,
2458
+ theme = "auto",
2459
+ height = 640,
2460
+ limits: limitsProp,
2461
+ className,
2462
+ fileName = "pivot",
2463
+ fieldDefaults,
2464
+ onExport,
2465
+ label,
2466
+ tips: tipsProp = "on",
2467
+ storageKey,
2468
+ dismissedTips,
2469
+ onTipDismiss,
2470
+ chartOptions,
2471
+ shareLink,
2472
+ persistView,
2473
+ fieldInfo: fieldInfoProp,
2474
+ zoneInfo: zoneInfoProp,
2475
+ settingInfo: settingInfoProp,
2476
+ source: sourceProp,
2477
+ sources,
2478
+ onSourceSwitch,
2479
+ schemaUrl,
2480
+ grow: growProp,
2481
+ fieldList,
2482
+ loading: loading2 = false
2483
+ } = props;
2484
+ const grow = growProp === "on" || growProp !== "off" && props.height === void 0;
2485
+ const sourceId = typeof sourceProp?.id === "string" && sourceProp.id ? sourceProp.id : void 0;
2486
+ const sourceName = typeof sourceProp?.name === "string" && sourceProp.name ? sourceProp.name : void 0;
2487
+ const labelsKey = JSON.stringify(customLabels ?? null);
2488
+ const defaultsKey = JSON.stringify(fieldDefaults ?? null);
2489
+ const info = useMemo7(() => fieldInfoOf(JSON.parse(defaultsKey)), [defaultsKey]);
2490
+ const baseLabels = useMemo7(() => resolveLabels(locale, JSON.parse(labelsKey)), [locale, labelsKey]);
2491
+ const typesKey = JSON.stringify(typesOf(fieldDefaults));
2492
+ const limitsKey = JSON.stringify(limitsProp ?? null);
2493
+ const limits = useMemo7(() => JSON.parse(limitsKey) ?? void 0, [limitsKey]);
2494
+ const root = useRef10(
2495
+ /** @type {HTMLDivElement | null} */
2496
+ null
2497
+ );
2498
+ const themeName = useResolvedTheme(theme, root);
2499
+ const [layer, setLayer] = useState11(
2500
+ /** @type {HTMLElement | null} */
2501
+ null
2502
+ );
2503
+ const [size, setSize] = useState11("wide");
2504
+ const [measuredShort, setMeasuredShort] = useState11(false);
2505
+ const [short, setShort] = useState11(false);
2506
+ const [folded, setFolded] = useState11(
2507
+ /** @type {boolean | null} */
2508
+ null
2509
+ );
2510
+ const layoutFolded = folded ?? short;
2511
+ const zonesId = useId4();
2512
+ const [drawer, setDrawer] = useState11(false);
2513
+ const [filterTarget, setFilterTarget] = useState11(
2514
+ /** @type {{ field: string, anchor: HTMLElement, base?: object } | null} */
2515
+ null
2516
+ );
2517
+ const [drill, setDrill] = useState11(
2518
+ /** @type {import("./drill-panel.jsx").Drill | null} */
2519
+ null
2520
+ );
2521
+ const [hinted, setHinted] = useState11(false);
2522
+ const changesRef = useRef10(0);
2523
+ const [changes, setChanges] = useState11(0);
2524
+ const [dragAt, setDragAt] = useState11(
2525
+ /** @type {number | null} */
2526
+ null
2527
+ );
2528
+ const [savedAt, setSavedAt] = useState11(0);
2529
+ const [menus, setMenus] = useState11(
2530
+ /** @type {typeof import("./menus.js") | null} */
2531
+ null
2532
+ );
2533
+ const [viewsRequest, setViewsRequest] = useState11(0);
2534
+ const [leftOut, setLeftOut] = useState11(
2535
+ /** @type {string[]} */
2536
+ []
2537
+ );
2538
+ const [issuesDismissed, setIssuesDismissed] = useState11(
2539
+ /** @type {string | null} */
2540
+ null
2541
+ );
2542
+ const [viewName, setViewName] = useState11(
2543
+ /** @type {string | null} */
2544
+ null
2545
+ );
2546
+ const [rowLabel, setRowLabel] = useState11(
2547
+ /** @type {string | null} */
2548
+ null
2549
+ );
2550
+ const chartRef = useRef10(null);
2551
+ const [chartReady, setChartReady] = useState11(false);
2552
+ const hintId = useId4();
2553
+ const closeFilter = useCallback9(() => setFilterTarget(null), []);
2554
+ const { toasts, push, dismiss, pause } = useToasts();
2555
+ const announce = useCallback9(
2556
+ /** @param {string} text @param {{ action?: { label: string, run: () => void }, tone?: "error" }} [extra] */
2557
+ (text, extra) => push({ text, ...extra }),
2558
+ [push]
2559
+ );
2560
+ const dataIdentity = dataKey !== void 0 ? dataKey : data;
2561
+ const source = useMemo7(() => {
2562
+ try {
2563
+ const types2 = JSON.parse(typesKey);
2564
+ const enc = encodedProp ?? measured("encode", () => encode(
2565
+ /** @type {any[]} */
2566
+ Array.isArray(data) ? data : [],
2567
+ { timeZone: timeZone ?? "UTC", limits, ...types2 ? { types: types2 } : {} }
2568
+ ));
2569
+ return { encoded: enc, error: null };
2570
+ } catch (error2) {
2571
+ return { encoded: encode([]), error: error2 };
2572
+ }
2573
+ }, [encodedProp, dataIdentity, timeZone, limits, typesKey]);
2574
+ const encoded = source.encoded;
2575
+ const fieldNamesKey = encoded.schema.fields.map((f) => f.name).join("\0");
2576
+ const labels = useMemo7(() => {
2577
+ const fields2 = displayNames(info, fieldNamesKey ? fieldNamesKey.split("\0") : []);
2578
+ return fields2 ? { ...baseLabels, core: { ...baseLabels.core, fields: fields2 } } : baseLabels;
2579
+ }, [baseLabels, info, fieldNamesKey]);
2580
+ const ordersKey = JSON.stringify(
2581
+ fieldDefaults && typeof fieldDefaults === "object" ? Object.entries(fieldDefaults).filter(([, d]) => d && Array.isArray(d.order) && d.order.length > 0).map(([field, d]) => [field, d.order]) : []
2582
+ );
2583
+ const orderOf = useMemo7(() => {
2584
+ const orders = (
2585
+ /** @type {[string, unknown[]][]} */
2586
+ JSON.parse(ordersKey)
2587
+ );
2588
+ if (!orders.length) {
2589
+ return void 0;
2590
+ }
2591
+ return (field) => orders.find(([name]) => name.toLowerCase() === field.toLowerCase())?.[1];
2592
+ }, [ordersKey]);
2593
+ const history = useViewHistory({ encoded, view: viewProp, defaultView, onViewChange, limits, outsideNote: labels.steps.outside, orderOf });
2594
+ const view = history.view;
2595
+ const chartOptionsKey = optionsKey(chartOptions);
2596
+ const stableChartOptions = useMemo7(() => chartOptions, [chartOptionsKey]);
2597
+ const stepText = useCallback9(
2598
+ (note) => {
2599
+ const template = Object.hasOwn(labels.steps, note.step) ? labels.steps[note.step] : labels.steps.change;
2600
+ return fill(template, {
2601
+ field: note.field ?? "",
2602
+ name: note.name ?? "",
2603
+ zone: labels.zones[note.zone] ?? note.zone ?? "",
2604
+ display: note.display ? labels[note.display] : "",
2605
+ type: note.type ? labels.chartTypes[note.type] : ""
2606
+ });
2607
+ },
2608
+ [labels]
2609
+ );
2610
+ const undo2 = useCallback9(() => {
2611
+ const note = history.undo();
2612
+ if (note !== null) {
2613
+ announce(fill(labels.toastUndone, { step: note }));
2614
+ }
2615
+ }, [history, labels, announce]);
2616
+ const redo2 = useCallback9(() => {
2617
+ const note = history.redo();
2618
+ if (note !== null) {
2619
+ announce(fill(labels.toastRedone, { step: note }));
2620
+ }
2621
+ }, [history, labels, announce]);
2622
+ const undoLater = useRef10(undo2);
2623
+ useEffect10(() => {
2624
+ undoLater.current = undo2;
2625
+ });
2626
+ const reset2 = useCallback9(() => {
2627
+ history.reset(labels.steps.reset);
2628
+ announce(labels.toastReset);
2629
+ }, [history, labels, announce]);
2630
+ const param = linkParam(storageKey);
2631
+ const [opening, setOpening] = useState11(false);
2632
+ const appliedLink = useRef10(
2633
+ /** @type {string | null} */
2634
+ null
2635
+ );
2636
+ const latest = useRef10({ history, encoded, limits, labels, announce, commit: (
2637
+ /** @type {any} */
2638
+ null
2639
+ ), sourceId, loaded: (
2640
+ /** @type {any} */
2641
+ null
2642
+ ), sources, onSourceSwitch });
2643
+ const [linkCheck, setLinkCheck] = useState11(
2644
+ /** @type {null | { lines: string[], quiet: boolean, load: () => void, switchTo?: { name: string, run: () => void } }} */
2645
+ null
2646
+ );
2647
+ const openLink = useCallback9((text, asStep = false) => {
2648
+ appliedLink.current = text;
2649
+ const now = linkNow();
2650
+ const apply = (m) => {
2651
+ const { history: h, encoded: enc, limits: lim, labels: l, announce: say, sourceId: id, loaded: done, sources: list, onSourceSwitch: switchTo } = latest.current;
2652
+ const decoded = m.decodeViewLink(text);
2653
+ const loaded2 = decoded.view ? viewFromObject(decoded.view, enc, { limits: lim, sourceId: id }) : null;
2654
+ if (!loaded2 || !loaded2.view) {
2655
+ say(loaded2?.failed === "newer" ? l.viewFailed.newer : l.viewFailed.badLink, { tone: "error" });
2656
+ return;
2657
+ }
2658
+ const open = () => {
2659
+ if (asStep) {
2660
+ done(loaded2, { link: true });
2661
+ } else {
2662
+ h.restore(
2663
+ /** @type {object} */
2664
+ loaded2.view
2665
+ );
2666
+ done(loaded2, { link: true, restored: true });
2667
+ }
2668
+ };
2669
+ const check = loadCheck(loaded2, l, Array.isArray(list) ? list : []);
2670
+ if (!check) {
2671
+ open();
2672
+ return;
2673
+ }
2674
+ const target = check.switchTo;
2675
+ setLinkCheck({
2676
+ lines: check.lines,
2677
+ quiet: !asStep,
2678
+ load: open,
2679
+ switchTo: target && typeof switchTo === "function" ? { name: target.name, run: () => switchTo({ source: { id: target.id, name: target.name }, view: (
2680
+ /** @type {Record<string, unknown>} */
2681
+ loaded2.file?.view ?? loaded2.view
2682
+ ), name: loaded2.file?.name || void 0 }) } : void 0
2683
+ });
2684
+ };
2685
+ if (now) {
2686
+ apply(now);
2687
+ return;
2688
+ }
2689
+ setOpening(true);
2690
+ loadLink().then(
2691
+ (m) => {
2692
+ setOpening(false);
2693
+ apply(m);
2694
+ },
2695
+ () => {
2696
+ setOpening(false);
2697
+ latest.current.announce(latest.current.labels.viewFailed.badLink, { tone: "error" });
2698
+ }
2699
+ );
2700
+ }, []);
2701
+ useIsoLayoutEffect(() => {
2702
+ const page = here();
2703
+ const link = shareLink ? readLinkParam(page?.hash ?? "", param) : null;
2704
+ if (link) {
2705
+ openLink(link);
2706
+ } else if (persistView === "session") {
2707
+ const raw = readStoredView(storageKey, sessionStore());
2708
+ if (raw) {
2709
+ try {
2710
+ const loaded2 = viewFromObject(JSON.parse(raw), encoded, { limits });
2711
+ if (loaded2.view) {
2712
+ history.restore(loaded2.view);
2713
+ }
2714
+ } catch {
2715
+ }
2716
+ }
2717
+ }
2718
+ }, []);
2719
+ useEffect10(() => {
2720
+ if (!shareLink || typeof window === "undefined") {
2721
+ return void 0;
2722
+ }
2723
+ const onHash = () => {
2724
+ const link = readLinkParam(here()?.hash ?? "", param);
2725
+ if (link && link !== appliedLink.current) {
2726
+ openLink(link, true);
2727
+ }
2728
+ };
2729
+ window.addEventListener("hashchange", onHash);
2730
+ return () => window.removeEventListener("hashchange", onHash);
2731
+ }, [shareLink, param, openLink]);
2732
+ useEffect10(() => {
2733
+ if (persistView === "session") {
2734
+ writeStoredView(storageKey, sessionStore(), JSON.parse(history.viewKey));
2735
+ }
2736
+ }, [persistView, storageKey, history.viewKey]);
2737
+ const commit = useCallback9(
2738
+ /** @param {object} next @param {{ step: string, removed?: boolean, field?: string, zone?: string, name?: string, display?: string, type?: string }} [note] */
2739
+ (next, note = { step: "change" }) => {
2740
+ const over = note.step === "template" ? null : zoneOverLimit(next, limits);
2741
+ if (over) {
2742
+ announce(fill(labels.zoneFull, { zone: labels.zones[over.zone], max: over.max.toLocaleString(locale) }), { tone: "error" });
2743
+ return;
2744
+ }
2745
+ const changed = history.commit(next, stepText(note));
2746
+ if (changed) {
2747
+ changesRef.current += 1;
2748
+ setChanges(changesRef.current);
2749
+ }
2750
+ if (!changed || !note.removed) {
2751
+ return;
2752
+ }
2753
+ announce(fill(labels.toastRemoved, { field: note.field ?? "" }).trim(), { action: { label: labels.undo, run: () => undoLater.current() } });
2754
+ },
2755
+ [history, stepText, labels, announce, limits, locale]
2756
+ );
2757
+ const applyLoaded = useCallback9(
2758
+ /** @param {import("./share.js").LoadedView} loaded @param {{ link?: boolean, restored?: boolean }} [how] */
2759
+ (loaded2, { link = false, restored = false } = {}) => {
2760
+ if (!loaded2.view) {
2761
+ return;
2762
+ }
2763
+ if (!restored) {
2764
+ commit(loaded2.view, { step: "viewLoaded" });
2765
+ }
2766
+ const lines = issueLines(loaded2.issues, labels);
2767
+ setLeftOut(lines);
2768
+ setIssuesDismissed(null);
2769
+ setViewName(loaded2.file?.name || null);
2770
+ const text = link ? lines.length ? labels.toastLinkOpenedPartly : labels.toastLinkOpened : lines.length ? labels.toastViewLoadedPartly : labels.toastViewLoaded;
2771
+ announce(text, restored ? void 0 : { action: { label: labels.undo, run: () => undoLater.current() } });
2772
+ },
2773
+ [commit, labels, announce]
2774
+ );
2775
+ useEffect10(() => {
2776
+ latest.current = { history, encoded, limits, labels, announce, commit, sourceId, loaded: applyLoaded, sources, onSourceSwitch };
2777
+ });
2778
+ const computed = useMemo7(() => {
2779
+ try {
2780
+ return { result: measured("computePivot", () => computePivot(encoded, view, { locale, limits })), error: null };
2781
+ } catch (error2) {
2782
+ return { result: null, error: error2 };
2783
+ }
2784
+ }, [encoded, view, locale, limits]);
2785
+ const result = computed.result;
2786
+ const plan = useMemo7(() => chartPlan(view, encoded), [view, encoded]);
2787
+ const chartComputed = useMemo7(() => {
2788
+ if (!plan.swap || view.display !== "chart" || !result) {
2789
+ return computed;
2790
+ }
2791
+ try {
2792
+ return { result: measured("computePivot", () => computePivot(encoded, swapAxes(view), { locale, limits })), error: null };
2793
+ } catch (error2) {
2794
+ return { result: null, error: error2 };
2795
+ }
2796
+ }, [plan.swap, view, encoded, locale, limits, computed, result]);
2797
+ const chartResult = chartComputed.result;
2798
+ const empty = isEmptyView(view);
2799
+ const gridState = useMemo7(() => {
2800
+ if (!result || view.display !== "table" || empty) {
2801
+ return { grid: null, error: null };
2802
+ }
2803
+ try {
2804
+ return { grid: measured("toGrid", () => toGrid(result, { locale, labels: labels.core, limits })), error: null };
2805
+ } catch (error2) {
2806
+ return { grid: null, error: error2 };
2807
+ }
2808
+ }, [result, view.display, empty, locale, labels, limits]);
2809
+ const error = source.error ?? computed.error ?? gridState.error ?? (view.display === "chart" ? chartComputed.error : null);
2810
+ const fields = encoded.schema.fields;
2811
+ const types = useMemo7(() => new Map(viewFields(view, encoded).map((f) => [f.name.toLowerCase(), f.type])), [view, encoded]);
2812
+ const typeOf = useCallback9((field) => types.get(sourceOf(view, field ?? "").toLowerCase()) ?? "string", [types, view]);
2813
+ const nameOf = useCallback9((field) => fieldLabel3(field, labels.core), [labels]);
2814
+ const infoOf = useCallback9(
2815
+ (field) => {
2816
+ if (!field || info.size === 0) {
2817
+ return void 0;
2818
+ }
2819
+ const entry = info.get(sourceOf(view, field).toLowerCase());
2820
+ return entry && entry.description ? entry : void 0;
2821
+ },
2822
+ [info, view]
2823
+ );
2824
+ const placed = useMemo7(() => {
2825
+ const map = /* @__PURE__ */ new Map();
2826
+ const mark = (name, zone) => {
2827
+ const key = sourceOf(view, name).toLowerCase();
2828
+ const list = map.get(key) ?? [];
2829
+ if (!list.includes(zone)) {
2830
+ list.push(zone);
2831
+ }
2832
+ map.set(key, list);
2833
+ };
2834
+ view.rows.forEach((f) => mark(f, "rows"));
2835
+ view.cols.forEach((f) => mark(f, "cols"));
2836
+ view.values.forEach((v) => v.field && mark(v.field, "values"));
2837
+ filterZoneFields(view).forEach((f) => mark(f, "filters"));
2838
+ return map;
2839
+ }, [view]);
2840
+ useEffect10(() => {
2841
+ let live = true;
2842
+ loadMenus().then((m) => live && setMenus(() => m), () => void 0);
2843
+ return () => {
2844
+ live = false;
2845
+ };
2846
+ }, []);
2847
+ const mainRef = useRef10(
2848
+ /** @type {HTMLDivElement | null} */
2849
+ null
2850
+ );
2851
+ const fit = useFitHeight(root, mainRef, grow);
2852
+ const big = useBigResult(root);
2853
+ useIsoLayoutEffect(() => {
2854
+ const el = root.current;
2855
+ if (!el) {
2856
+ return void 0;
2857
+ }
2858
+ const box = el.getBoundingClientRect();
2859
+ setSize(sizeOf(box.width));
2860
+ const first = compactAt(sizeOf(box.width), box.height);
2861
+ setMeasuredShort(first);
2862
+ setShort(first);
2863
+ if (typeof ResizeObserver !== "function") {
2864
+ return void 0;
2865
+ }
2866
+ const ro = new ResizeObserver(([entry]) => {
2867
+ const width = sizeOf(entry.contentRect.width);
2868
+ setSize(width);
2869
+ const height2 = entry.borderBoxSize?.[0]?.blockSize ?? el.getBoundingClientRect().height;
2870
+ setMeasuredShort(compactAt(width, height2) || fit.current.open > 0 && height2 <= fit.current.open + 1);
2871
+ });
2872
+ ro.observe(el);
2873
+ return () => ro.disconnect();
2874
+ }, []);
2875
+ useEffect10(() => {
2876
+ if (measuredShort === short) {
2877
+ return void 0;
2878
+ }
2879
+ const apply = () => {
2880
+ if (!layerOpen(layer)) {
2881
+ setShort(measuredShort);
2882
+ }
2883
+ };
2884
+ apply();
2885
+ if (!layer || typeof MutationObserver !== "function") {
2886
+ return void 0;
2887
+ }
2888
+ const mo = new MutationObserver(apply);
2889
+ mo.observe(layer, { childList: true });
2890
+ return () => mo.disconnect();
2891
+ }, [measuredShort, short, layer]);
2892
+ const drawerOpen = drawer && size === "narrow";
2893
+ const panelRef = useRef10(
2894
+ /** @type {HTMLDivElement | null} */
2895
+ null
2896
+ );
2897
+ useEffect10(() => {
2898
+ if (panelRef.current) {
2899
+ panelRef.current.inert = size === "narrow" && !drawerOpen;
2900
+ }
2901
+ }, [size, drawerOpen]);
2902
+ const placeOptions = useCallback9(
2903
+ (field, zone, index = void 0) => {
2904
+ const column = encoded.column(field);
2905
+ const unit = zone !== "values" && column && column.type === "date" && !column.derived ? suggestDateUnit(encoded, field) : null;
2906
+ return { index, type: typeOf(field), defaults: defaultsFor(fieldDefaults, field), dateUnit: unit, groupName: unit ? groupingName(nameOf(column.name), unit, labels) : void 0 };
2907
+ },
2908
+ [encoded, typeOf, fieldDefaults, labels, nameOf]
2909
+ );
2910
+ const defaultsOf = useCallback9((field) => defaultsFor(fieldDefaults, field), [fieldDefaults]);
2911
+ const addTo = useCallback9(
2912
+ (field, zone, index = void 0) => {
2913
+ const options = placeOptions(field, zone, index);
2914
+ commit(addField(view, field, zone, options), { step: "added", field: options.groupName ?? nameOf(field), zone });
2915
+ },
2916
+ [view, placeOptions, commit, nameOf]
2917
+ );
2918
+ const filterNew = useCallback9(
2919
+ (field, anchor) => {
2920
+ const options = placeOptions(field, "filters");
2921
+ const draft = addField(view, field, "filters", options);
2922
+ const opener = size === "narrow" ? (
2923
+ /** @type {HTMLElement | null} */
2924
+ root.current?.querySelector("[data-pk-opener='fields']") ?? null
2925
+ ) : null;
2926
+ if (size === "narrow") {
2927
+ setDrawer(false);
2928
+ }
2929
+ const target = opener ?? anchor;
2930
+ if (target) {
2931
+ setFilterTarget({ field: options.groupName ?? field, anchor: target, base: draft });
2932
+ }
2933
+ },
2934
+ [placeOptions, view, size]
2935
+ );
2936
+ const onDrop = useCallback9(
2937
+ (src, target) => {
2938
+ setDragAt((at) => at ?? changesRef.current + 1);
2939
+ if (target.zone === "panel") {
2940
+ if (src.kind !== "field") {
2941
+ commit(removeAt(view, src.zone, src.index), { step: "removed", removed: true, field: src.label ?? src.field });
2942
+ }
2943
+ return;
2944
+ }
2945
+ if (src.kind === "field") {
2946
+ addTo(src.field, target.zone, target.index);
2947
+ } else {
2948
+ const zone = (
2949
+ /** @type {any} */
2950
+ target.zone
2951
+ );
2952
+ const note = src.zone !== zone ? { step: "moved", field: src.label ?? src.field, zone } : { step: "reordered", zone };
2953
+ commit(moveField(view, src.zone, src.index, zone, target.index, { type: typeOf(src.field) }), note);
2954
+ }
2955
+ },
2956
+ [view, typeOf, commit, addTo]
2957
+ );
2958
+ const openCell = useCallback9(
2959
+ /** @param {any} cell */
2960
+ ({ rowPath = [], colPath = [], value, valueIndex, text }) => {
2961
+ if (!result) {
2962
+ return;
2963
+ }
2964
+ setHinted(true);
2965
+ const { count, rows, indices } = drillRows(result, { rowPath, colPath, data: encodedProp ? null : data, limit: drillDownLimit });
2966
+ onCellClick?.({ row: rowPath, col: colPath, value, valueIndex, text, count, rows });
2967
+ if (drillDown) {
2968
+ const formatOf = (name) => {
2969
+ const d = defaultsFor(fieldDefaults, name);
2970
+ return d ? d.drillFormat ?? d.format : void 0;
2971
+ };
2972
+ const table = drillTable(encoded, indices, { locale: result.locale, labels: labels.core, formatOf });
2973
+ const columns = table.columns.map((c) => ({ ...c, label: nameOf(c.name), description: infoOf(c.name)?.description }));
2974
+ const formats = Object.fromEntries(table.columns.map((c) => [c.name, formatOf(c.name)]).filter(([, f]) => typeof f === "string"));
2975
+ setDrill({ ...pathTitle(result, rowPath, colPath, labels), count, rows: table.rows, columns, indices, formats, locale: result.locale });
2976
+ }
2977
+ },
2978
+ [result, encodedProp, data, drillDownLimit, onCellClick, drillDown, labels, encoded, fieldDefaults, nameOf, infoOf]
2979
+ );
2980
+ const doExport = useExport({ fileName, result, locale, labels, limits, root, chartRef, announce, onExport });
2981
+ const base = shareBase(shareLink, here()?.href);
2982
+ const viewFile = () => viewFileText(toViewFile(view, { name: viewName ?? "", createdAt: /* @__PURE__ */ new Date(), generator: { name: "pivotkit-react", version: VERSION }, source: { id: sourceId, name: sourceName }, data: encoded, ...schemaUrl !== void 0 ? { schemaUrl } : {} }));
2983
+ const share = {
2984
+ canLink: base !== null,
2985
+ prepare: base !== null ? () => void loadLink().catch(() => void 0) : void 0,
2986
+ copyLink: async () => {
2987
+ const target = shareBase(shareLink, here()?.href);
2988
+ if (target === null) {
2989
+ return;
2990
+ }
2991
+ let text;
2992
+ try {
2993
+ text = (linkNow() ?? await loadLink()).encodeViewLink(toViewFile(view, { name: viewName ?? void 0, source: { id: sourceId } }, { link: true }));
2994
+ } catch (e) {
2995
+ announce(e && /** @type {any} */
2996
+ e.code === "LIMIT_EXCEEDED" ? labels.toastLinkTooLong : fill(labels.error, { message: String(e) }), { tone: "error" });
2997
+ return;
2998
+ }
2999
+ const ok = await copyText(withLinkParam(target, param, text), root.current);
3000
+ announce(ok ? labels.toastLinkCopied : labels.toastCopyFailed, ok ? void 0 : { tone: "error" });
3001
+ },
3002
+ copyJson: async () => {
3003
+ const ok = await copyText(viewFile(), root.current);
3004
+ announce(ok ? labels.toastJsonCopied : labels.toastCopyFailed, ok ? void 0 : { tone: "error" });
3005
+ },
3006
+ download: () => {
3007
+ const file = viewFileName(viewName || sourceName || safeFileName(fileName));
3008
+ const blob = new Blob([viewFile()], { type: "application/json" });
3009
+ if (onExport?.({ kind: "json", fileName: file, blob }) === false) {
3010
+ return;
3011
+ }
3012
+ saveBlob(blob, file, root.current?.ownerDocument ?? document);
3013
+ announce(fill(labels.toastExported, { file }));
3014
+ },
3015
+ /**
3016
+ * @param {string} text
3017
+ * @returns {Promise<string | null | { lines: string[], load: () => void, switchTo?: { name: string, run: () => void } }>}
3018
+ * why nothing was loaded, null when it was, or what to ask first (a view for other data)
3019
+ */
3020
+ loadText: async (text) => {
3021
+ let loaded2 = viewFromText(text, encoded, { limits, sourceId });
3022
+ if (loaded2.failed === "notJson") {
3023
+ const t = text.trim();
3024
+ const fromUrl = t.includes("#") ? readLinkParam(t.slice(t.indexOf("#")), param) ?? readLinkParam(t.slice(t.indexOf("#")), "pivot") : null;
3025
+ const payload = fromUrl ?? (t.startsWith("1.") ? t : null);
3026
+ if (!payload) {
3027
+ return labels.viewFailed.notJson;
3028
+ }
3029
+ try {
3030
+ const decoded = (linkNow() ?? await loadLink()).decodeViewLink(payload);
3031
+ loaded2 = decoded.view ? viewFromObject(decoded.view, encoded, { limits, sourceId }) : { view: null, issues: [], failed: "badLink", file: null };
3032
+ } catch {
3033
+ return labels.viewFailed.badLink;
3034
+ }
3035
+ }
3036
+ if (!loaded2.view) {
3037
+ return labels.viewFailed[loaded2.failed ?? "notView"] ?? labels.viewFailed.notView;
3038
+ }
3039
+ const ready = (
3040
+ /** @type {import("./share.js").LoadedView} */
3041
+ loaded2
3042
+ );
3043
+ const check = loadCheck(ready, labels, Array.isArray(sources) ? sources : []);
3044
+ if (!check) {
3045
+ applyLoaded(ready);
3046
+ return null;
3047
+ }
3048
+ const target = check.switchTo;
3049
+ return {
3050
+ lines: check.lines,
3051
+ load: () => applyLoaded(ready),
3052
+ switchTo: target && typeof onSourceSwitch === "function" ? { name: target.name, run: () => onSourceSwitch({ source: { id: target.id, name: target.name }, view: (
3053
+ /** @type {Record<string, unknown>} */
3054
+ ready.file?.view ?? ready.view
3055
+ ), name: ready.file?.name || void 0 }) } : void 0
3056
+ };
3057
+ }
3058
+ };
3059
+ const loadTemplate = useCallback9(
3060
+ (t) => {
3061
+ commit(t.view, { step: "template", name: t.name });
3062
+ setViewName(typeof t.name === "string" ? t.name : null);
3063
+ const over = zoneOverLimit(t.view, limits);
3064
+ setLeftOut(over ? [fill(labels.viewTrimmed, { name: t.name, zone: labels.zones[over.zone], max: over.max.toLocaleString(locale) })] : []);
3065
+ setIssuesDismissed(null);
3066
+ announce(fill(labels.toastLoaded, { name: t.name }));
3067
+ },
3068
+ [commit, labels, announce, limits, locale]
3069
+ );
3070
+ const viewStore = templateStore === "browser";
3071
+ const storeName = viewsName(storageKey);
3072
+ const subscribeViews = useCallback9((callback) => viewStore ? subscribeItem(storeName, callback) : () => {
3073
+ }, [viewStore, storeName]);
3074
+ const viewsText = useSyncExternalStore3(subscribeViews, () => viewStore ? readItem(storeName, localStore()) : null, () => null);
3075
+ const entries2 = useMemo7(() => templateEntries(templates, viewStore && menus ? menus.storedViews(viewsText, sourceId) : [], Boolean(onDeleteTemplate)), [templates, viewStore, menus, viewsText, sourceId, onDeleteTemplate]);
3076
+ const templateActions = {
3077
+ view,
3078
+ announce,
3079
+ locale,
3080
+ sourceId,
3081
+ viewsText,
3082
+ store: viewStore,
3083
+ keep: (text) => writeItem(storeName, localStore(), text),
3084
+ onSave: onSaveTemplate,
3085
+ onDelete: onDeleteTemplate,
3086
+ onPublish: canPublish ? onPublishTemplate : void 0,
3087
+ // a view leaves the report checked against the data, never as it was stored
3088
+ normalized: (v) => normalize3(v, encoded, { limits }).view,
3089
+ onSaved: () => setSavedAt(changesRef.current)
3090
+ };
3091
+ const onKeyDown = (e) => {
3092
+ const target = (
3093
+ /** @type {HTMLElement} */
3094
+ e.target
3095
+ );
3096
+ if (e.key === "Escape" && big.enlarged && !e.defaultPrevented && !layerOpen(layer) && !drawerOpen && !drill && !filterTarget) {
3097
+ e.preventDefault();
3098
+ big.setEnlarged(false);
3099
+ return;
3100
+ }
3101
+ if (target.closest("input, textarea, select, [contenteditable]")) {
3102
+ return;
3103
+ }
3104
+ const mod = e.ctrlKey || e.metaKey;
3105
+ if (mod && !e.altKey && (e.key === "z" || e.key === "Z")) {
3106
+ e.preventDefault();
3107
+ if (e.shiftKey) {
3108
+ redo2();
3109
+ } else {
3110
+ undo2();
3111
+ }
3112
+ } else if (mod && (e.key === "y" || e.key === "Y")) {
3113
+ e.preventDefault();
3114
+ redo2();
3115
+ }
3116
+ };
3117
+ const layerValue = useMemo7(() => ({ layer, size }), [layer, size]);
3118
+ const renderOverlay = (src) => /* @__PURE__ */ React11.createElement("div", { className: "pk-chip pk-overlay" }, /* @__PURE__ */ React11.createElement(Icon, { name: "grip", size: 14 }), /* @__PURE__ */ React11.createElement("span", { className: `pk-type pk-type-${src.type ?? typeOf(src.field)}` }, /* @__PURE__ */ React11.createElement(Icon, { name: (
3119
+ /** @type {any} */
3120
+ TYPE_ICON[src.type ?? typeOf(src.field)] ?? "text"
3121
+ ), size: 13 })), /* @__PURE__ */ React11.createElement("span", { className: "pk-chip-text" }, src.label ?? src.field));
3122
+ const showTable = !error && !(empty && view.display === "table") && view.display !== "chart" && gridState.grid;
3123
+ const outer = useMemo7(() => result ? outerPaths(result) : [], [result]);
3124
+ const folding = rowFolding(view, outer);
3125
+ const expandAll = () => {
3126
+ const count = view.collapsed.rows.length;
3127
+ commit(setCollapsed(view, "rows", null), { step: "collapse" });
3128
+ announce(plural(labels.groupsExpanded, count, { lang: labels.lang, locale }));
3129
+ };
3130
+ const collapseAll = () => {
3131
+ if (!result) {
3132
+ return;
3133
+ }
3134
+ commit(setCollapsed(view, "rows", outer), { step: "collapse" });
3135
+ announce(plural(labels.groupsCollapsed, folding.open, { lang: labels.lang, locale }));
3136
+ };
3137
+ const series = useMemo7(() => {
3138
+ if (!chartResult || view.display !== "chart" || view.values.length === 0) {
3139
+ return null;
3140
+ }
3141
+ try {
3142
+ return toSeries(chartResult, { labels: labels.core, maxCategories: MAX_CATEGORIES });
3143
+ } catch {
3144
+ return null;
3145
+ }
3146
+ }, [chartResult, view.display, view.values.length, labels]);
3147
+ const allowedKey = JSON.stringify(allowedTips(tipsProp));
3148
+ const allowed = useMemo7(() => JSON.parse(allowedKey), [allowedKey]);
3149
+ const dismissedKey = JSON.stringify(cleanDismissed(dismissedTips));
3150
+ const [own2, setOwn] = useState11(() => cleanDismissed(JSON.parse(dismissedKey)));
3151
+ const [lastDismissedKey, setLastDismissedKey] = useState11(dismissedKey);
3152
+ if (dismissedKey !== lastDismissedKey) {
3153
+ setLastDismissedKey(dismissedKey);
3154
+ setOwn(JSON.parse(dismissedKey));
3155
+ }
3156
+ const subscribe = useCallback9((callback) => subscribeStored(storageKey, callback), [storageKey]);
3157
+ const storedRaw = useSyncExternalStore3(subscribe, () => readStored(storageKey, localStore()), () => null);
3158
+ const dismissed = useMemo7(() => cleanDismissed([...own2, ...parseStored(storedRaw)]), [own2, storedRaw]);
3159
+ const changeDismissed = useCallback9(
3160
+ (next, id) => {
3161
+ setOwn(next);
3162
+ writeDismissed(storageKey, localStore(), next);
3163
+ onTipDismiss?.({ id, dismissed: next });
3164
+ },
3165
+ [storageKey, onTipDismiss]
3166
+ );
3167
+ const tipsOn = allowed !== "off" && !dismissed.includes(ALL_TIPS);
3168
+ const describedFields = [...info.values()].some((i) => i.description);
3169
+ const fieldSwitch = helpSwitch(fieldInfoProp, dismissed);
3170
+ const zoneSwitch = helpSwitch(zoneInfoProp, dismissed);
3171
+ const settingSwitch = helpSwitch(settingInfoProp, dismissed);
3172
+ const explainUser = settingSwitch.user || zoneSwitch.user || describedFields && fieldSwitch.user;
3173
+ const help = useMemo7(
3174
+ () => ({
3175
+ explain: settingSwitch.on,
3176
+ // with the menus' texts once they are loaded: the explanations are among them
3177
+ labels: menus ? menus.menuLabels(labels) : labels,
3178
+ isOpen: (id) => sectionOpen(id, dismissed),
3179
+ setOpen: (id, open) => changeDismissed(withSection(dismissed, id, open), null)
3180
+ }),
3181
+ [settingSwitch.on, labels, menus, dismissed, changeDismissed]
3182
+ );
3183
+ const [fieldsSession, setFieldsSession] = useState11(
3184
+ /** @type {boolean | null} */
3185
+ null
3186
+ );
3187
+ useEffect10(() => {
3188
+ if (fieldList !== void 0 && fieldList !== "open" && fieldList !== "collapsed") {
3189
+ warnOnce(`pivotkit: fieldList ${JSON.stringify(String(fieldList)).slice(0, 40)} is neither "open" nor "collapsed"; the user's choice decides`);
3190
+ }
3191
+ }, [fieldList]);
3192
+ const railed = size !== "narrow" && fieldsCollapsed(fieldsSession, fieldList, dismissed);
3193
+ const collapseFields = (next) => {
3194
+ if (fieldList === "open" || fieldList === "collapsed") {
3195
+ setFieldsSession(next);
3196
+ } else {
3197
+ changeDismissed(next ? [...dismissed, FIELDS_COLLAPSED] : dismissed.filter((d) => d !== FIELDS_COLLAPSED), null);
3198
+ }
3199
+ };
3200
+ const toggle = (id, on) => changeDismissed(on ? dismissed.filter((d) => d !== id) : [...dismissed, id], on ? null : id);
3201
+ const ctx = tipContext({ view, result, encoded, failed: Boolean(error), empty, typeOf, fields: labels.core.fields, series, tableShown: Boolean(showTable), drilled: hinted, changes, dragAt, canSave: Boolean(onSaveTemplate) || viewStore, savedAt, chartPlan: plan });
3202
+ const shownTips = activeTips(ctx, { allowed, dismissed }).map((t) => ({
3203
+ id: t.id,
3204
+ params: t.params,
3205
+ icon: t.entry.icon ?? "info",
3206
+ notice: t.entry.kind === "notice",
3207
+ action: t.entry.action ?? "",
3208
+ text: tipText(t.id, t.params, labels, locale),
3209
+ actionText: tipActionText(t.entry, t.params, labels)
3210
+ }));
3211
+ const runTip = (id, action) => {
3212
+ const params = shownTips.find((t) => t.id === id)?.params ?? {};
3213
+ if (action === "swap") {
3214
+ commit(swapAxes(view), { step: "swap" });
3215
+ } else if (action === "removeFilters") {
3216
+ commit(withoutFilters(view), { step: "filtersRemoved" });
3217
+ } else if (action === "groupDate") {
3218
+ commit(groupField(view, params.source, params.unit, { name: groupingName(nameOf(params.source), params.unit, labels) }).view, { step: "group", field: nameOf(params.source) });
3219
+ } else if (action === "bars") {
3220
+ commit(setChart(view, "bar"), { step: "chart", type: "bar" });
3221
+ } else if (action === "auto") {
3222
+ commit(setChart(view, "auto"), { step: "chart", type: "auto" });
3223
+ } else if (action === "saveTemplate") {
3224
+ setViewsRequest((n) => n + 1);
3225
+ }
3226
+ };
3227
+ const cancelLink = () => {
3228
+ appliedLink.current = null;
3229
+ setLinkCheck(null);
3230
+ };
3231
+ const notes = [...leftOut.map((text) => ({ path: "", text })), ...result && !empty ? result.issues.slice(0, 20).map((i) => ({ path: i.path, text: i.message })) : []];
3232
+ const notesKey = JSON.stringify(notes);
3233
+ const summaryParts = big.enlarged ? layoutSummary(zoneEntries(view, types, labels), labels) : [];
3234
+ const summaryText = summaryParts.length ? summaryParts.map((p) => `${p.title}: ${p.fields}`).join(" \xB7 ") : labels.layoutEmpty;
3235
+ return /* @__PURE__ */ React11.createElement(
3236
+ "div",
3237
+ {
3238
+ ref: root,
3239
+ className: `pk-root${className ? ` ${className}` : ""}`,
3240
+ "data-pk-theme": themeName,
3241
+ "data-pk-size": size,
3242
+ "data-pk-layout": layoutFolded ? "compact" : void 0,
3243
+ "data-pk-enlarged": big.enlarged ? "" : void 0,
3244
+ "data-pk-fields": railed ? "collapsed" : void 0,
3245
+ "data-pk-fit": grow ? void 0 : "contain",
3246
+ lang: labels.lang,
3247
+ role: "region",
3248
+ "aria-label": label || labels.report,
3249
+ style: { height },
3250
+ tabIndex: -1,
3251
+ onKeyDown
3252
+ },
3253
+ /* @__PURE__ */ React11.createElement(LayerContext.Provider, { value: layerValue }, /* @__PURE__ */ React11.createElement(HelpContext.Provider, { value: help }, /* @__PURE__ */ React11.createElement(
3254
+ PivotDnd,
3255
+ {
3256
+ labels,
3257
+ onDrop,
3258
+ renderOverlay,
3259
+ onDragStart: (src) => {
3260
+ if (src.kind === "field" && size === "narrow") {
3261
+ setDrawer(false);
3262
+ }
3263
+ }
3264
+ },
3265
+ /* @__PURE__ */ React11.createElement("div", { className: `pk-layout${drawerOpen ? " pk-drawer-open" : ""}` }, /* @__PURE__ */ React11.createElement("div", { className: "pk-panel-slot", ref: panelRef }, /* @__PURE__ */ React11.createElement(
3266
+ FieldPanel,
3267
+ {
3268
+ fields,
3269
+ placed,
3270
+ labels,
3271
+ onAdd: (f, z) => {
3272
+ addTo(f, z);
3273
+ if (size === "narrow") {
3274
+ setDrawer(false);
3275
+ }
3276
+ },
3277
+ onNote: (text) => announce(text),
3278
+ onFilter: filterNew,
3279
+ nameOf,
3280
+ info,
3281
+ showInfo: fieldSwitch.on,
3282
+ drawer: size === "narrow",
3283
+ open: drawerOpen,
3284
+ onClose: () => setDrawer(false),
3285
+ collapsed: railed,
3286
+ onCollapse: collapseFields,
3287
+ onSkip: () => (
3288
+ /** @type {HTMLElement | null | undefined} */
3289
+ root.current?.querySelector(".pk-toolbar button:not([disabled])")?.focus()
3290
+ )
3291
+ }
3292
+ )), drawerOpen ? /* @__PURE__ */ React11.createElement("div", { className: "pk-scrim pk-drawer-scrim", onClick: () => setDrawer(false), "aria-hidden": "true" }) : null, /* @__PURE__ */ React11.createElement("div", { className: "pk-main", ref: mainRef }, /* @__PURE__ */ React11.createElement(
3293
+ Toolbar,
3294
+ {
3295
+ view,
3296
+ chartPlan: plan,
3297
+ labels,
3298
+ size,
3299
+ canUndo: history.canUndo,
3300
+ canRedo: history.canRedo,
3301
+ canReset: history.canReset,
3302
+ onUndo: undo2,
3303
+ onRedo: redo2,
3304
+ onReset: reset2,
3305
+ onDisplay: (d) => commit(setDisplay(view, d), { step: "display", display: d }),
3306
+ onChart: (p) => commit(setChart(view, p), { step: "chart", type: p }),
3307
+ onChartDisplay: (patch) => commit(setChartDisplay(view, patch), { step: "chartDisplay" }),
3308
+ onTotal: (key, on) => commit(setTotal(view, key, on), { step: "totals" }),
3309
+ onExpand: expandAll,
3310
+ onCollapse: collapseAll,
3311
+ folding,
3312
+ share,
3313
+ templates: entries2,
3314
+ onLoadTemplate: loadTemplate,
3315
+ templateActions,
3316
+ onExport: doExport,
3317
+ prepareExport: prepareExporters,
3318
+ chartReady: view.display === "chart" && chartReady,
3319
+ onShowFields: () => setDrawer(true),
3320
+ layoutFolded,
3321
+ onLayout: () => setFolded(!layoutFolded),
3322
+ zonesId,
3323
+ tipsControls: allowed !== "off",
3324
+ tipsOn,
3325
+ onTipsOn: (on) => changeDismissed(on ? dismissed.filter((id) => id !== ALL_TIPS) : [...dismissed, ALL_TIPS], on ? null : ALL_TIPS),
3326
+ canResetTips: dismissed.some((id) => !keptOnReset(id)),
3327
+ onResetTips: () => changeDismissed(dismissed.filter(keptOnReset), null),
3328
+ help: {
3329
+ explanations: explainUser ? { on: !dismissed.includes(NO_EXPLANATIONS), set: (on) => toggle(NO_EXPLANATIONS, on) } : null
3330
+ },
3331
+ viewsRequest
3332
+ }
3333
+ ), /* @__PURE__ */ React11.createElement(
3334
+ Zones,
3335
+ {
3336
+ view,
3337
+ types,
3338
+ labels,
3339
+ commit,
3340
+ openFilter: (field, anchor) => setFilterTarget({ field, anchor }),
3341
+ encoded,
3342
+ locale,
3343
+ onSwap: () => commit(swapAxes(view), { step: "swap" }),
3344
+ id: zonesId,
3345
+ folded: layoutFolded,
3346
+ onShow: () => setFolded(false),
3347
+ defaultsOf,
3348
+ infoOf,
3349
+ explain: zoneSwitch.on,
3350
+ showInfo: fieldSwitch.on
3351
+ }
3352
+ ), linkCheck ? /* @__PURE__ */ React11.createElement("div", { className: "pk-link-check", "data-testid": "link-check" }, /* @__PURE__ */ React11.createElement(MenuPanel, { name: "LoadCheck", props: { check: linkCheck, labels, title: labels.linkCheckTitle, quiet: linkCheck.quiet, close: () => setLinkCheck(null), onCancel: cancelLink } })) : null, notes.length > 0 && issuesDismissed !== notesKey ? (
3353
+ // what a loaded view left out and what the view asks for that this data has not:
3354
+ // it stays (the status note goes by itself) until it is dismissed
3355
+ /* @__PURE__ */ React11.createElement("div", { className: "pk-issues", "data-testid": "view-issues" }, /* @__PURE__ */ React11.createElement("details", null, /* @__PURE__ */ React11.createElement("summary", null, /* @__PURE__ */ React11.createElement(Icon, { name: "info" }), " ", labels.issues, " ", notes.length), /* @__PURE__ */ React11.createElement("ul", null, notes.map((n, k) => /* @__PURE__ */ React11.createElement("li", { key: k }, n.path ? /* @__PURE__ */ React11.createElement("code", null, n.path) : null, " ", n.text)))), /* @__PURE__ */ React11.createElement("button", { type: "button", className: "pk-icon-btn pk-issues-x", "aria-label": labels.dismissIssues, title: labels.dismissIssues, onClick: () => setIssuesDismissed(notesKey), "data-testid": "dismiss-issues" }, /* @__PURE__ */ React11.createElement(Icon, { name: "x", size: 14 })))
3356
+ ) : null, /* @__PURE__ */ React11.createElement(
3357
+ Tips,
3358
+ {
3359
+ tips: shownTips,
3360
+ labels,
3361
+ onDismiss: (id) => changeDismissed([...dismissed, id], id),
3362
+ onAction: runTip,
3363
+ focusFallback: () => root.current?.focus({ preventScroll: true })
3364
+ }
3365
+ ), showTable && view.values.length ? /* @__PURE__ */ React11.createElement("p", { id: hintId, className: "pk-sr", "data-testid": "cell-hint" }, labels.tips.cells) : null, /* @__PURE__ */ React11.createElement("div", { className: "pk-result-head" }, big.enlarged ? /* @__PURE__ */ React11.createElement("p", { className: "pk-enlarged-fields", "data-testid": "enlarged-fields" }, summaryText) : null, /* @__PURE__ */ React11.createElement("span", { className: "pk-grow" }), /* @__PURE__ */ React11.createElement("button", { type: "button", className: "pk-btn pk-pressable pk-small-btn", "data-pk-on": big.enlarged ? "" : void 0, onClick: big.toggleEnlarged, "data-testid": "enlarge" }, /* @__PURE__ */ React11.createElement(Icon, { name: "enlarge", size: 14 }), /* @__PURE__ */ React11.createElement("span", { className: "pk-btn-text" }, big.enlarged ? labels.reduce : labels.enlarge)), big.fullOk ? /* @__PURE__ */ React11.createElement("button", { type: "button", className: "pk-btn pk-pressable pk-small-btn", "aria-pressed": big.full, onClick: big.toggleFull, "data-testid": "full-screen" }, /* @__PURE__ */ React11.createElement(Icon, { name: "fullScreen", size: 14 }), /* @__PURE__ */ React11.createElement("span", { className: "pk-btn-text" }, labels.fullScreen)) : null), /* @__PURE__ */ React11.createElement("section", { className: "pk-result", "aria-label": view.display === "chart" ? labels.chart : labels.table }, loading2 || opening ? /* @__PURE__ */ React11.createElement(Skeleton, { text: labels.loadingReport }) : error ? /* @__PURE__ */ React11.createElement("div", { className: "pk-message pk-error", role: "alert" }, /* @__PURE__ */ React11.createElement(Icon, { name: "info" }), /* @__PURE__ */ React11.createElement("p", null, errorText(error, labels, locale))) : empty && view.display === "table" ? /* @__PURE__ */ React11.createElement(EmptyState, { labels, templates: entries2, onTemplate: loadTemplate }) : view.display === "chart" && chartResult ? /* @__PURE__ */ React11.createElement(
3366
+ PivotChart,
3367
+ {
3368
+ result: chartResult,
3369
+ plan,
3370
+ series,
3371
+ labels,
3372
+ locale,
3373
+ themeName,
3374
+ root,
3375
+ valueNames: view.values.map((v) => valueLabel(v, labels)),
3376
+ chartOptions: stableChartOptions,
3377
+ onInstance: (c) => {
3378
+ chartRef.current = c;
3379
+ setChartReady(Boolean(c));
3380
+ },
3381
+ onPoint: (p) => openCell({ rowPath: plan.swap ? p.colPath : p.rowPath, colPath: plan.swap ? p.rowPath : p.colPath, value: p.value, valueIndex: p.valueIndex, text: String(p.value ?? "") })
3382
+ }
3383
+ ) : gridState.grid ? /* @__PURE__ */ React11.createElement(PivotTable, { grid: gridState.grid, view, labels, version: history.viewKey, hintId: view.values.length ? hintId : void 0, onRowLabel: setRowLabel, infoOf, showInfo: fieldSwitch.on, onToggle: (axis, path) => commit(toggleCollapsed(view, axis, path), { step: "collapse" }), onCell: (cell) => openCell(cell) }) : null), /* @__PURE__ */ React11.createElement("div", { className: "pk-status" }, /* @__PURE__ */ React11.createElement("span", { "data-testid": "row-count" }, result ? plural(labels.rowsCount, result.rows.length, { lang: labels.lang, locale }) : ""), rowLabel && showTable ? /* @__PURE__ */ React11.createElement("span", { className: "pk-row-label", "data-testid": "row-label" }, fill(labels.rowLabel, { label: rowLabel })) : null), /* @__PURE__ */ React11.createElement("div", { className: "pk-toast-dock" }, /* @__PURE__ */ React11.createElement(Toasts, { toasts, dismiss, pause, closeLabel: labels.close }))), drill ? /* @__PURE__ */ React11.createElement(MenuPanel, { name: "DrillPanel", props: { drill, onClose: () => setDrill(null), labels, locale, exportContext: { encoded, onExport, announce, root } } }) : null),
3384
+ filterTarget ? /* @__PURE__ */ React11.createElement(MenuPanel, { name: "FilterPopover", props: { target: filterTarget, onClose: closeFilter, view, encoded, locale, labels, commit } }) : null
3385
+ ), /* @__PURE__ */ React11.createElement("div", { className: "pk-layer", ref: setLayer }, /* @__PURE__ */ React11.createElement("span", { className: "pk-origin", "aria-hidden": "true" }))))
3386
+ );
3387
+ }
3388
+ export {
3389
+ PivotReport
3390
+ };