pivotkit-react 0.3.0 → 0.5.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 (73) hide show
  1. package/CHANGELOG.md +339 -1
  2. package/README.md +2 -2
  3. package/dist/chunks/{chunk-IOPAM4JD.js → chunk-2AT72SLA.js} +635 -980
  4. package/dist/chunks/chunk-3E4NB5RZ.js +215 -0
  5. package/dist/chunks/{chunk-32Z33U6S.js → chunk-3WUGQPWV.js} +106 -9
  6. package/dist/chunks/{chunk-7CC4JHDY.js → chunk-4RS72AAA.js} +27 -8
  7. package/dist/chunks/{chunk-EM23V5GH.js → chunk-E6M57YLL.js} +19 -8
  8. package/dist/chunks/{chunk-RWYHJRQO.js → chunk-JMRTIOX4.js} +17 -7
  9. package/dist/chunks/chunk-RIOSIYGC.js +665 -0
  10. package/dist/chunks/{chunk-APB4NW4O.js → chunk-U5Q5I2D5.js} +36 -10
  11. package/dist/chunks/report-run-BZBFOMPF.js +12 -0
  12. package/dist/chunks/{unused-texts-K3VFH65P.js → unused-texts-Y4R67XSN.js} +1 -1
  13. package/dist/chunks/{unused-texts-de-OW4TGIVX.js → unused-texts-de-6YVPTNVS.js} +1 -1
  14. package/dist/echarts.js +38 -156
  15. package/dist/import-ui.js +765 -0
  16. package/dist/import-worker.js +20 -0
  17. package/dist/index.js +683 -244
  18. package/dist/labels.js +14 -10
  19. package/dist/menu-texts-de.js +1 -1
  20. package/dist/menus.js +768 -299
  21. package/dist/styles.css +322 -100
  22. package/package.json +9 -4
  23. package/types/chart-decorate.d.ts +28 -4
  24. package/types/chart-types.d.ts +2 -4
  25. package/types/data-history.d.ts +85 -0
  26. package/types/data-keep.d.ts +51 -0
  27. package/types/data-menu.d.ts +11 -0
  28. package/types/dom.d.ts +40 -7
  29. package/types/echarts.d.ts +1 -1
  30. package/types/export-run.d.ts +37 -3
  31. package/types/field-info.d.ts +32 -0
  32. package/types/filter.d.ts +1 -1
  33. package/types/icons.d.ts +1 -0
  34. package/types/import-host.d.ts +53 -0
  35. package/types/import-labels.d.ts +401 -0
  36. package/types/import-limits.d.ts +6 -0
  37. package/types/import-module.d.ts +2 -0
  38. package/types/import-run.d.ts +73 -0
  39. package/types/import-source.d.ts +32 -0
  40. package/types/import-steps.d.ts +121 -0
  41. package/types/import-ui.d.ts +108 -0
  42. package/types/import-worker.d.ts +1 -0
  43. package/types/index.d.ts +81 -11
  44. package/types/labels.d.ts +224 -4
  45. package/types/lazy-import.d.ts +4 -0
  46. package/types/lazy-menus.d.ts +2 -2
  47. package/types/levels.d.ts +3 -2
  48. package/types/light-tokens.d.ts +16 -0
  49. package/types/menu-labels.d.ts +37 -17
  50. package/types/menu-ops.d.ts +161 -40
  51. package/types/menu-topics.d.ts +9 -8
  52. package/types/menus.d.ts +1 -0
  53. package/types/names.d.ts +47 -19
  54. package/types/overflow.d.ts +29 -17
  55. package/types/place.d.ts +24 -0
  56. package/types/popover.d.ts +47 -5
  57. package/types/print-frame.d.ts +24 -0
  58. package/types/report-run.d.ts +14 -0
  59. package/types/section.d.ts +2 -2
  60. package/types/share-actions.d.ts +3 -3
  61. package/types/share.d.ts +13 -17
  62. package/types/theme.d.ts +2 -16
  63. package/types/tips.d.ts +5 -0
  64. package/types/toasts.d.ts +1 -1
  65. package/types/toolbar-panels.d.ts +11 -9
  66. package/types/unused-keep.d.ts +20 -0
  67. package/types/unused-texts.d.ts +13 -3
  68. package/types/unused.d.ts +1 -0
  69. package/types/use-export.d.ts +2 -2
  70. package/types/use-view-history.d.ts +12 -4
  71. package/types/view-ops.d.ts +65 -6
  72. package/types/virtual.d.ts +15 -0
  73. package/types/chart-layout.d.ts +0 -111
@@ -0,0 +1,765 @@
1
+ import {
2
+ Group,
3
+ Icon,
4
+ LayerContext,
5
+ Option,
6
+ hasTopLayer,
7
+ useFormName,
8
+ useModal,
9
+ useTopLayer
10
+ } from "./chunks/chunk-RIOSIYGC.js";
11
+ import {
12
+ errorText,
13
+ importLabels,
14
+ noteText
15
+ } from "./chunks/chunk-3E4NB5RZ.js";
16
+ import {
17
+ fill,
18
+ messageOf,
19
+ plural
20
+ } from "./chunks/chunk-3WUGQPWV.js";
21
+
22
+ // src/import-host.jsx
23
+ import React2 from "react";
24
+
25
+ // src/import-ui.jsx
26
+ import React, { useContext, useEffect, useId, useMemo, useRef, useState } from "react";
27
+ import { createPortal } from "react-dom";
28
+ import { encode } from "pivotkit-core";
29
+ import { IMPORT_TYPES, fileName, retype } from "pivotkit-core/import";
30
+
31
+ // src/import-run.js
32
+ import { PivotkitError } from "pivotkit-core";
33
+ import { BUILT_IN_READERS, loadReader, readFile, readerFor } from "pivotkit-core/import";
34
+ function acceptOf(plugins) {
35
+ const all = [];
36
+ for (const p of [...plugins, ...BUILT_IN_READERS]) {
37
+ for (const a of Array.isArray(p?.accept) ? p.accept : []) {
38
+ if (typeof a === "string" && !all.includes(a)) {
39
+ all.push(a);
40
+ }
41
+ }
42
+ }
43
+ return all.join(",");
44
+ }
45
+ var formatsOf = (plugins, names = {}) => [...plugins, ...BUILT_IN_READERS].map((p) => typeof p?.name === "string" && Object.hasOwn(names, p.name) ? names[p.name] : typeof p?.label === "string" ? p.label.trim().slice(0, 100) : "").filter((t, i, all) => t && all.indexOf(t) === i);
46
+ var WORKER_READY_MS = 1e4;
47
+ function completeTable(table) {
48
+ const n = table.data[0]?.length ?? 0;
49
+ const same = (list) => Array.isArray(list) && list.length === table.columns.length;
50
+ return {
51
+ ...table,
52
+ rowCount: Number.isInteger(table.rowCount) && table.rowCount >= 0 ? table.rowCount : n,
53
+ raw: same(table.raw) && table.raw.every((c) => Array.isArray(c) && c.length === n) ? table.raw : table.data,
54
+ detected: same(table.detected) ? table.detected : table.types,
55
+ hints: table.hints && typeof table.hints === "object" ? table.hints : { decimal: ".", dateOrder: "dmy" },
56
+ notes: table.notes.filter((x) => x && typeof x.code === "string").map((x) => ({ code: x.code, params: x.params && typeof x.params === "object" ? x.params : {}, message: String(x.message ?? x.code) }))
57
+ };
58
+ }
59
+ var isTable = (t) => t !== null && typeof t === "object" && Array.isArray(t.columns) && Array.isArray(t.types) && Array.isArray(t.data) && Array.isArray(t.notes);
60
+ var aborted = (signal) => signal?.reason ?? new DOMException("The read was cancelled", "AbortError");
61
+ var UNAVAILABLE = /* @__PURE__ */ Symbol("worker unavailable");
62
+ function inWorker(start, file, options, signal, onProgress, readyMs = WORKER_READY_MS) {
63
+ let worker;
64
+ try {
65
+ worker = start();
66
+ } catch {
67
+ return Promise.resolve(UNAVAILABLE);
68
+ }
69
+ if (!worker || typeof worker.postMessage !== "function") {
70
+ return Promise.resolve(UNAVAILABLE);
71
+ }
72
+ return new Promise((resolve, reject) => {
73
+ let ready = false;
74
+ const late = setTimeout(() => {
75
+ end();
76
+ resolve(UNAVAILABLE);
77
+ }, readyMs);
78
+ const end = () => {
79
+ clearTimeout(late);
80
+ worker.terminate?.();
81
+ signal?.removeEventListener("abort", stop);
82
+ };
83
+ const stop = () => {
84
+ end();
85
+ reject(aborted(signal));
86
+ };
87
+ if (signal?.aborted) {
88
+ stop();
89
+ return;
90
+ }
91
+ signal?.addEventListener("abort", stop, { once: true });
92
+ worker.onmessage = (event) => {
93
+ const m = event.data;
94
+ if (m?.type === "ready" && !ready) {
95
+ ready = true;
96
+ clearTimeout(late);
97
+ try {
98
+ worker.postMessage({ file, options });
99
+ } catch {
100
+ end();
101
+ resolve(UNAVAILABLE);
102
+ }
103
+ } else if (m?.type === "progress") {
104
+ if (m.progress && typeof m.progress === "object") {
105
+ onProgress?.(m.progress);
106
+ }
107
+ } else if (m?.type === "done") {
108
+ end();
109
+ if (isTable(m.table)) {
110
+ resolve(m.table);
111
+ } else {
112
+ reject(new Error("The import worker returned no table"));
113
+ }
114
+ } else if (m?.type === "error") {
115
+ end();
116
+ const e = m.error ?? {};
117
+ reject(typeof e.code === "string" ? new PivotkitError(e.code, String(e.message ?? ""), e.details ?? {}) : new Error(String(e.message ?? "The file could not be read")));
118
+ }
119
+ };
120
+ worker.onmessageerror = () => {
121
+ end();
122
+ reject(new Error("The import worker's answer could not be read"));
123
+ };
124
+ worker.onerror = (event) => {
125
+ event.preventDefault?.();
126
+ end();
127
+ if (ready) {
128
+ reject(new Error(String(event.message || "The file could not be read")));
129
+ } else {
130
+ resolve(UNAVAILABLE);
131
+ }
132
+ };
133
+ });
134
+ }
135
+ async function readImport(file, { plugins = [], worker, sheet, locale, limits, signal, onProgress, readyMs } = {}) {
136
+ const plain = { name: file.name, ...sheet !== void 0 ? { sheet } : {}, ...locale ? { locale } : {}, ...limits ? { limits } : {} };
137
+ const reader = readerFor(file, plugins);
138
+ if (worker && reader && BUILT_IN_READERS.includes(reader)) {
139
+ const table = await inWorker(worker, file, plain, signal, onProgress, readyMs);
140
+ if (table !== UNAVAILABLE) {
141
+ return completeTable(table);
142
+ }
143
+ }
144
+ signal?.throwIfAborted();
145
+ return completeTable(await readFile(file, { ...plain, plugins, signal, onProgress }));
146
+ }
147
+ async function sheetsOf(file, { plugins = [], limits, signal } = {}) {
148
+ const reader = readerFor(file, plugins);
149
+ if (!reader) {
150
+ return [];
151
+ }
152
+ const mod = await loadReader(reader);
153
+ if (typeof mod.sheets !== "function") {
154
+ return [];
155
+ }
156
+ const list = await mod.sheets(file, { name: file.name, ...limits ? { limits } : {}, signal });
157
+ return Array.isArray(list) ? list.filter((s) => s && typeof s.name === "string" && Number.isInteger(s.index)) : [];
158
+ }
159
+
160
+ // src/import-source.js
161
+ var SHOWN_MAX = 120;
162
+ function shownName(name) {
163
+ if (name.length <= SHOWN_MAX) {
164
+ return name;
165
+ }
166
+ let cut = SHOWN_MAX - 3;
167
+ const code = name.charCodeAt(cut - 1);
168
+ if (code >= 55296 && code <= 56319) {
169
+ cut -= 1;
170
+ }
171
+ return `${name.slice(0, cut)}...`;
172
+ }
173
+ var K = new Uint32Array([
174
+ 1116352408,
175
+ 1899447441,
176
+ 3049323471,
177
+ 3921009573,
178
+ 961987163,
179
+ 1508970993,
180
+ 2453635748,
181
+ 2870763221,
182
+ 3624381080,
183
+ 310598401,
184
+ 607225278,
185
+ 1426881987,
186
+ 1925078388,
187
+ 2162078206,
188
+ 2614888103,
189
+ 3248222580,
190
+ 3835390401,
191
+ 4022224774,
192
+ 264347078,
193
+ 604807628,
194
+ 770255983,
195
+ 1249150122,
196
+ 1555081692,
197
+ 1996064986,
198
+ 2554220882,
199
+ 2821834349,
200
+ 2952996808,
201
+ 3210313671,
202
+ 3336571891,
203
+ 3584528711,
204
+ 113926993,
205
+ 338241895,
206
+ 666307205,
207
+ 773529912,
208
+ 1294757372,
209
+ 1396182291,
210
+ 1695183700,
211
+ 1986661051,
212
+ 2177026350,
213
+ 2456956037,
214
+ 2730485921,
215
+ 2820302411,
216
+ 3259730800,
217
+ 3345764771,
218
+ 3516065817,
219
+ 3600352804,
220
+ 4094571909,
221
+ 275423344,
222
+ 430227734,
223
+ 506948616,
224
+ 659060556,
225
+ 883997877,
226
+ 958139571,
227
+ 1322822218,
228
+ 1537002063,
229
+ 1747873779,
230
+ 1955562222,
231
+ 2024104815,
232
+ 2227730452,
233
+ 2361852424,
234
+ 2428436474,
235
+ 2756734187,
236
+ 3204031479,
237
+ 3329325298
238
+ ]);
239
+ function sha256Bytes(bytes) {
240
+ const bits = bytes.length * 8;
241
+ const padded = new Uint8Array(Math.ceil((bytes.length + 9) / 64) * 64);
242
+ padded.set(bytes);
243
+ padded[bytes.length] = 128;
244
+ const view = new DataView(padded.buffer);
245
+ view.setUint32(padded.length - 8, Math.floor(bits / 2 ** 32));
246
+ view.setUint32(padded.length - 4, bits >>> 0);
247
+ const h = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
248
+ const w = new Uint32Array(64);
249
+ const rotr = (x, n) => x >>> n | x << 32 - n;
250
+ for (let at = 0; at < padded.length; at += 64) {
251
+ for (let i = 0; i < 16; i++) {
252
+ w[i] = view.getUint32(at + i * 4);
253
+ }
254
+ for (let i = 16; i < 64; i++) {
255
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
256
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
257
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
258
+ }
259
+ let [a, b, c, d, e, f, g, hh] = h;
260
+ for (let i = 0; i < 64; i++) {
261
+ const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] >>> 0;
262
+ const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
263
+ hh = g;
264
+ g = f;
265
+ f = e;
266
+ e = d + t1 >>> 0;
267
+ d = c;
268
+ c = b;
269
+ b = a;
270
+ a = t1 + t2 >>> 0;
271
+ }
272
+ h[0] += a;
273
+ h[1] += b;
274
+ h[2] += c;
275
+ h[3] += d;
276
+ h[4] += e;
277
+ h[5] += f;
278
+ h[6] += g;
279
+ h[7] += hh;
280
+ }
281
+ const out = new Uint8Array(32);
282
+ const outView = new DataView(out.buffer);
283
+ h.forEach((v, i) => outView.setUint32(i * 4, v));
284
+ return out;
285
+ }
286
+ async function sha256Hex(text, options = {}) {
287
+ const bytes = new TextEncoder().encode(text);
288
+ const subtle = options.subtle !== void 0 ? options.subtle : globalThis.crypto?.subtle;
289
+ let digest;
290
+ try {
291
+ digest = subtle ? new Uint8Array(await subtle.digest("SHA-256", bytes)) : sha256Bytes(bytes);
292
+ } catch {
293
+ digest = sha256Bytes(bytes);
294
+ }
295
+ return [...digest].map((b) => b.toString(16).padStart(2, "0")).join("");
296
+ }
297
+ async function sourceIdOf(name, columns, options) {
298
+ const hex = await sha256Hex([name, ...columns].join("\0"), options);
299
+ return `${shownName(name)}#${hex.slice(0, 16)}`;
300
+ }
301
+
302
+ // src/import-ui.jsx
303
+ var PREVIEW_ROWS = 8;
304
+ var PREVIEW_COLUMNS = 60;
305
+ function listOf(items, locale) {
306
+ try {
307
+ return new Intl.ListFormat(locale, { type: "conjunction" }).format(items);
308
+ } catch {
309
+ return items.join(", ");
310
+ }
311
+ }
312
+ function sizeText(bytes, locale) {
313
+ const units = ["B", "KB", "MB", "GB"];
314
+ let n = bytes;
315
+ let u = 0;
316
+ while (n >= 1e3 && u < units.length - 1) {
317
+ n /= 1e3;
318
+ u += 1;
319
+ }
320
+ return `${n.toLocaleString(locale, { maximumFractionDigits: u === 0 ? 0 : 1 })} ${units[u]}`;
321
+ }
322
+ function DataPanel({ labels, locale, source, plugins, onPick, onBack, close }) {
323
+ const t = importLabels(labels);
324
+ const where = { lang: labels.lang, locale };
325
+ return /* @__PURE__ */ React.createElement("div", { className: "pk-data-menu", "data-testid": "data-menu" }, /* @__PURE__ */ React.createElement(Group, { title: t.dataSource, testId: "data-source" }, /* @__PURE__ */ React.createElement("p", { "data-testid": "data-name" }, /* @__PURE__ */ React.createElement("strong", null, source.name ?? t.hostData)), /* @__PURE__ */ React.createElement("p", { className: "pk-hint", "data-testid": "data-size" }, `${plural(t.rows, source.rows, where)} \xD7 ${plural(t.columns, source.columns, where)}`), source.imported ? /* @__PURE__ */ React.createElement("p", { className: "pk-hint" }, t.fromFile) : null), /* @__PURE__ */ React.createElement(Group, { title: t.load }, /* @__PURE__ */ React.createElement(Option, { icon: "upload", onSelect: () => {
326
+ close();
327
+ onPick();
328
+ }, testId: "load-file" }, t.loadFile), source.imported ? /* @__PURE__ */ React.createElement(Option, { icon: "reset", hint: t.backHint, onSelect: () => {
329
+ close();
330
+ onBack();
331
+ }, testId: "back-to-original" }, t.backToOriginal) : null, /* @__PURE__ */ React.createElement("p", { className: "pk-hint", "data-testid": "drop-hint" }, `${t.dropHint}. ${fill(t.formats, { formats: listOf(formatsOf(plugins, t.formatNames), locale) })}`)));
332
+ }
333
+ function DropOverlay({ labels, locale, plugins, box: boxOf }) {
334
+ const t = importLabels(labels);
335
+ const { layer } = useContext(LayerContext);
336
+ const ref = useRef(
337
+ /** @type {HTMLDivElement | null} */
338
+ null
339
+ );
340
+ const [top] = useState(hasTopLayer);
341
+ useTopLayer(true, [ref], null, layer);
342
+ const box = boxOf();
343
+ if (!layer || !box) {
344
+ return null;
345
+ }
346
+ const view = layer.ownerDocument.defaultView;
347
+ const left = Math.max(0, box.left);
348
+ const topEdge = Math.max(0, box.top);
349
+ const style = {
350
+ left,
351
+ top: topEdge,
352
+ width: Math.max(0, Math.min(box.right, view?.innerWidth ?? box.right) - left),
353
+ height: Math.max(0, Math.min(box.bottom, view?.innerHeight ?? box.bottom) - topEdge)
354
+ };
355
+ return createPortal(
356
+ /* @__PURE__ */ React.createElement("div", { ref, ...top ? { popover: "manual" } : {}, className: "pk-drop", style, "aria-hidden": "true", "data-testid": "drop-overlay" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Icon, { name: "upload", size: 24 }), /* @__PURE__ */ React.createElement("strong", null, t.dropTitle), /* @__PURE__ */ React.createElement("span", null, fill(t.formats, { formats: listOf(formatsOf(plugins, t.formatNames), locale) })))),
357
+ layer
358
+ );
359
+ }
360
+ function SourceLine({ labels, source }) {
361
+ const t = importLabels(labels);
362
+ return /* @__PURE__ */ React.createElement("span", { className: "pk-row-label pk-source", "data-testid": "source-line" }, /* @__PURE__ */ React.createElement(Icon, { name: "file", size: 14 }), fill(source.sheet ? t.sourceSheet : t.sourceLine, { name: source.name, sheet: source.sheet ?? "" }));
363
+ }
364
+ function cellText(value, type, t, locale) {
365
+ if (value === null || value === void 0) {
366
+ return "";
367
+ }
368
+ if (type === "boolean") {
369
+ return value ? t.yes : t.no;
370
+ }
371
+ if (type === "number" && typeof value === "number") {
372
+ return value.toLocaleString(locale, { maximumFractionDigits: 10 });
373
+ }
374
+ const text = String(value).replace(/^(\d{4}-\d\d-\d\d)T(\d\d:\d\d)(?::00(?:\.000)?)?$/, "$1 $2");
375
+ return text.length > 80 ? `${text.slice(0, 79)}\u2026` : text;
376
+ }
377
+ function ImportDialog({ job, labels, locale, plugins, worker, limits, timeZone, onApply, onClose, announce }) {
378
+ const t = importLabels(labels);
379
+ const where = { lang: labels.lang, locale };
380
+ const { layer } = useContext(LayerContext);
381
+ const file = job.file;
382
+ const name = useMemo(() => fileName(file, {}), [file]);
383
+ const [sheet, setSheet] = useState(
384
+ /** @type {number | undefined} */
385
+ void 0
386
+ );
387
+ const [sheets, setSheets] = useState(
388
+ /** @type {import("pivotkit-core/import").SheetInfo[]} */
389
+ []
390
+ );
391
+ const [read, setRead] = useState(
392
+ /** @type {{ table: import("pivotkit-core/import").ImportTable, sheet: number | undefined } | null} */
393
+ null
394
+ );
395
+ const [types, setTypes] = useState(
396
+ /** @type {import("pivotkit-core/import").ImportType[] | null} */
397
+ null
398
+ );
399
+ const [progress, setProgress] = useState(
400
+ /** @type {import("pivotkit-core/import").ImportProgress | null} */
401
+ null
402
+ );
403
+ const [error, setError] = useState(
404
+ /** @type {string | null} */
405
+ null
406
+ );
407
+ const [busy, setBusy] = useState(false);
408
+ const [failed, setFailed] = useState(
409
+ /** @type {number | undefined | null} */
410
+ null
411
+ );
412
+ const current = read && read.sheet === sheet ? read : null;
413
+ const reading = !current && failed !== sheet;
414
+ const latest = useRef({ onClose, announce, t, name, plugins, worker, locale, limits, where });
415
+ useEffect(() => {
416
+ latest.current = { onClose, announce, t, name, plugins, worker, locale, limits, where };
417
+ });
418
+ useEffect(() => {
419
+ const controller = new AbortController();
420
+ let last = 0;
421
+ const now = latest.current;
422
+ readImport(file, {
423
+ plugins: now.plugins,
424
+ worker: now.worker,
425
+ sheet,
426
+ locale: now.locale,
427
+ limits: now.limits,
428
+ signal: controller.signal,
429
+ // at most a few updates a second: a progress bar, not a render per step
430
+ onProgress: (p) => {
431
+ const now2 = Date.now();
432
+ if (now2 - last > 120 || p.done >= p.total) {
433
+ last = now2;
434
+ setProgress(p);
435
+ }
436
+ }
437
+ }).then(
438
+ (table) => {
439
+ if (!controller.signal.aborted) {
440
+ setRead({ table, sheet });
441
+ setTypes(null);
442
+ }
443
+ },
444
+ (e) => {
445
+ if (controller.signal.aborted) {
446
+ return;
447
+ }
448
+ const text = fill(latest.current.t.failed, { name: latest.current.name, message: errorText(e, latest.current.name, latest.current.t, latest.current.where) });
449
+ if (sheet === void 0) {
450
+ latest.current.announce(text, { tone: "error" });
451
+ latest.current.onClose();
452
+ } else {
453
+ setFailed(sheet);
454
+ setError(text);
455
+ }
456
+ }
457
+ );
458
+ return () => controller.abort();
459
+ }, [file, sheet]);
460
+ useEffect(() => {
461
+ const controller = new AbortController();
462
+ sheetsOf(file, { plugins: latest.current.plugins, limits: latest.current.limits, signal: controller.signal }).then(
463
+ (list) => !controller.signal.aborted && setSheets(list),
464
+ () => void 0
465
+ );
466
+ return () => controller.abort();
467
+ }, [file]);
468
+ const base = current?.table ?? null;
469
+ const typed = useMemo(() => {
470
+ if (!base || !types || types.every((ty, i) => ty === base.types[i])) {
471
+ return { table: base, error: null };
472
+ }
473
+ try {
474
+ return { table: retype(base, types), error: null };
475
+ } catch (e) {
476
+ return { table: base, error: messageOf(e) };
477
+ }
478
+ }, [base, types]);
479
+ const shown = typed.table;
480
+ const box = useRef(
481
+ /** @type {HTMLDivElement | null} */
482
+ null
483
+ );
484
+ const scrim = useRef(
485
+ /** @type {HTMLDivElement | null} */
486
+ null
487
+ );
488
+ const applyRef = useRef(
489
+ /** @type {HTMLButtonElement | null} */
490
+ null
491
+ );
492
+ const [top] = useState(hasTopLayer);
493
+ useTopLayer(true, [scrim, box], null, layer);
494
+ const { onKeyDown } = useModal(box, true, onClose);
495
+ const ready = Boolean(shown) && !reading;
496
+ const focused = useRef(false);
497
+ useEffect(() => {
498
+ if (ready && !focused.current) {
499
+ focused.current = true;
500
+ applyRef.current?.focus({ preventScroll: true });
501
+ }
502
+ }, [ready]);
503
+ const live = useRef(true);
504
+ useEffect(() => () => void (live.current = false), []);
505
+ const titleId = useId();
506
+ const metaId = useId();
507
+ const notesId = useId();
508
+ const formName = useFormName();
509
+ const sheetName = (() => {
510
+ const n = shown?.notes.find((x) => x.code === "SHEET");
511
+ return n && n.params?.sheet !== void 0 ? String(n.params.sheet) : null;
512
+ })();
513
+ const sheetIndex = sheet ?? sheets.find((s) => s.name === sheetName)?.index ?? 0;
514
+ const apply = async () => {
515
+ if (!shown || busy) {
516
+ return;
517
+ }
518
+ setBusy(true);
519
+ try {
520
+ await new Promise((resolve) => setTimeout(resolve, 0));
521
+ const encoded = encode({ columns: shown.columns, types: shown.types, data: shown.data }, { timeZone: timeZone ?? "UTC", limits });
522
+ const id = await sourceIdOf(name, shown.columns);
523
+ if (!live.current) {
524
+ return;
525
+ }
526
+ onApply({
527
+ encoded,
528
+ source: { id, name: shownName(name) },
529
+ file: { name, size: file.size, type: file.type },
530
+ sheet: sheetName,
531
+ rows: shown.rowCount,
532
+ columns: shown.columns.map((c, i) => ({ name: c, type: shown.types[i] })),
533
+ notes: shown.notes.map((n) => ({ code: n.code, params: { ...n.params }, message: n.message }))
534
+ });
535
+ } catch (e) {
536
+ if (live.current) {
537
+ setError(fill(t.failed, { name, message: errorText(e, name, t, where) }));
538
+ setBusy(false);
539
+ }
540
+ }
541
+ };
542
+ if (!layer) {
543
+ return null;
544
+ }
545
+ const inTop = (
546
+ /** @type {any} */
547
+ top ? { popover: "manual" } : {}
548
+ );
549
+ const cols = shown ? shown.columns.slice(0, PREVIEW_COLUMNS) : [];
550
+ const rows = shown ? Math.min(PREVIEW_ROWS, shown.rowCount) : 0;
551
+ const phase = progress && Object.hasOwn(t.phases, String(progress.phase)) ? (
552
+ /** @type {any} */
553
+ t.phases[String(progress.phase)]
554
+ ) : t.phases.read;
555
+ const percent = progress && progress.total > 0 ? Math.min(100, Math.round(progress.done / progress.total * 100)) : null;
556
+ const meta = shown && !reading ? `${plural(t.rows, shown.rowCount, where)} \xB7 ${plural(t.columns, shown.columns.length, where)} \xB7 ${sizeText(file.size, locale)}` : sizeText(file.size, locale);
557
+ return createPortal(
558
+ /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { ref: scrim, ...inTop, className: "pk-scrim pk-import-scrim", "aria-hidden": "true" }), /* @__PURE__ */ React.createElement("div", { ref: box, ...inTop, className: "pk-import", role: "dialog", "aria-modal": "true", "aria-labelledby": titleId, "aria-describedby": shown && shown.notes.length ? `${metaId} ${notesId}` : metaId, "aria-busy": reading || void 0, tabIndex: -1, onKeyDown, "data-testid": "import-dialog" }, /* @__PURE__ */ React.createElement("div", { className: "pk-drill-head" }, /* @__PURE__ */ React.createElement("div", { className: "pk-drill-heading" }, /* @__PURE__ */ React.createElement("h2", { id: titleId }, fill(t.previewTitle, { name })), /* @__PURE__ */ React.createElement("p", { id: metaId, className: "pk-hint", role: "status", "data-testid": "import-meta" }, meta))), /* @__PURE__ */ React.createElement("div", { className: "pk-import-body" }, sheets.length > 1 ? /* @__PURE__ */ React.createElement("label", { className: "pk-inline-form" }, t.sheet, /* @__PURE__ */ React.createElement("select", { name: `${formName}-sheet`, value: sheetIndex, onChange: (e) => {
559
+ setProgress(null);
560
+ setError(null);
561
+ setFailed(null);
562
+ setTypes(null);
563
+ setSheet(Number(e.target.value));
564
+ }, "data-testid": "import-sheet" }, sheets.map((s) => /* @__PURE__ */ React.createElement("option", { key: s.index, value: s.index }, s.visible ? s.name : fill(t.hiddenSheet, { name: s.name }))))) : null, error || typed.error ? /* @__PURE__ */ React.createElement("p", { className: "pk-error", role: "alert", "data-testid": "import-error" }, error ?? typed.error) : null, reading ? /* @__PURE__ */ React.createElement("div", { "data-testid": "import-progress" }, /* @__PURE__ */ React.createElement("p", null, fill(t.reading, { name })), /* @__PURE__ */ React.createElement("progress", { max: 100, value: percent ?? void 0, "aria-label": phase }), /* @__PURE__ */ React.createElement("p", { className: "pk-hint" }, `${phase}${percent !== null ? ` \xB7 ${percent} %` : ""}`)) : shown ? /* @__PURE__ */ React.createElement(React.Fragment, null, shown.rowCount === 0 ? /* @__PURE__ */ React.createElement("p", { "data-testid": "import-empty" }, t.noRows) : null, /* @__PURE__ */ React.createElement("div", { className: "pk-drill-body", "data-testid": "import-preview" }, /* @__PURE__ */ React.createElement("table", { className: "pk-drill-table" }, /* @__PURE__ */ React.createElement("caption", { className: "pk-sr" }, t.firstRows), /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", null, cols.map((c, i) => /* @__PURE__ */ React.createElement("th", { key: i, scope: "col" }, c, /* @__PURE__ */ React.createElement(
565
+ "select",
566
+ {
567
+ name: `${formName}-type-${i}`,
568
+ value: shown.types[i],
569
+ "aria-label": fill(t.typeOf, { column: c }),
570
+ onChange: (e) => setTypes((old) => (old ?? base?.types ?? []).map((ty, k) => k === i ? (
571
+ /** @type {import("pivotkit-core/import").ImportType} */
572
+ e.target.value
573
+ ) : ty)),
574
+ "data-testid": `import-type-${i}`
575
+ },
576
+ IMPORT_TYPES.map((ty) => /* @__PURE__ */ React.createElement("option", { key: ty, value: ty }, t.types[ty]))
577
+ ))))), /* @__PURE__ */ React.createElement("tbody", null, Array.from({ length: rows }, (_, r) => /* @__PURE__ */ React.createElement("tr", { key: r }, cols.map((_2, c) => /* @__PURE__ */ React.createElement("td", { key: c, className: shown.types[c] === "number" ? "pk-num" : void 0 }, cellText(shown.data[c][r], shown.types[c], t, locale)))))))), shown.columns.length > cols.length ? /* @__PURE__ */ React.createElement("p", { className: "pk-hint" }, fill(t.someColumns, { shown: cols.length.toLocaleString(locale), count: shown.columns.length.toLocaleString(locale) })) : null, shown.notes.length ? /* @__PURE__ */ React.createElement("div", { id: notesId, className: "pk-note", "data-testid": "import-notes" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", null, plural(t.notesTitle, shown.notes.length, where)), /* @__PURE__ */ React.createElement("ul", null, shown.notes.map((n, i) => /* @__PURE__ */ React.createElement("li", { key: i, "data-code": n.code }, noteText(n, t, where)))))) : null) : null), /* @__PURE__ */ React.createElement("div", { className: "pk-popover-foot" }, /* @__PURE__ */ React.createElement("button", { type: "button", className: "pk-btn", onClick: onClose, "data-autofocus": "", "data-testid": "import-cancel" }, t.cancel), ready ? /* @__PURE__ */ React.createElement("button", { ref: applyRef, type: "button", className: "pk-btn pk-primary", onClick: apply, disabled: busy || !shown || shown.rowCount === 0, "data-testid": "import-apply" }, t.apply) : null))),
578
+ layer
579
+ );
580
+ }
581
+
582
+ // src/data-history.js
583
+ var DATA_STEPS = 3;
584
+ var NO_DATA_STEPS = Object.freeze({ past: Object.freeze([]), future: Object.freeze([]) });
585
+ function pushData(steps, before, note) {
586
+ return { past: [...steps.past, { data: before.data, history: { ...before.history, future: [] }, note }].slice(-DATA_STEPS), future: [] };
587
+ }
588
+ function undoData(steps, now) {
589
+ const step = steps.past[steps.past.length - 1];
590
+ if (!step) {
591
+ return null;
592
+ }
593
+ return { steps: { past: steps.past.slice(0, -1), future: [...steps.future, { data: now.data, history: now.history, note: step.note }] }, step };
594
+ }
595
+ function redoData(steps, now) {
596
+ const step = steps.future[steps.future.length - 1];
597
+ if (!step) {
598
+ return null;
599
+ }
600
+ return { steps: { past: [...steps.past, { data: now.data, history: now.history, note: step.note }], future: steps.future.slice(0, -1) }, step };
601
+ }
602
+ function hostHistory(steps) {
603
+ for (let i = steps.past.length - 1; i >= 0; i--) {
604
+ if (steps.past[i].data === null) {
605
+ return steps.past[i].history;
606
+ }
607
+ }
608
+ return null;
609
+ }
610
+
611
+ // src/import-steps.js
612
+ function describe(ctx, data, cause, notes = []) {
613
+ const encoded = data ? data.encoded : ctx.hostEncoded;
614
+ return (
615
+ /** @type {DataLoad} */
616
+ {
617
+ cause,
618
+ source: data ? { ...data.source } : ctx.hostSource ? { ...ctx.hostSource } : null,
619
+ file: data ? { ...data.file } : null,
620
+ sheet: data ? data.sheet : null,
621
+ rows: encoded.length,
622
+ columns: encoded.schema.fields.map((f) => ({ name: f.name, type: f.type })),
623
+ notes
624
+ }
625
+ );
626
+ }
627
+ var keys = 0;
628
+ function tell(ctx, detail) {
629
+ try {
630
+ return { refused: ctx.onDataLoad?.(detail) === false };
631
+ } catch (error) {
632
+ if (detail.cause !== "load") {
633
+ setTimeout(() => {
634
+ throw error;
635
+ }, 0);
636
+ }
637
+ return { refused: true, error };
638
+ }
639
+ }
640
+ function loadData(ctx, loaded) {
641
+ const data = { key: ++keys, encoded: loaded.encoded, source: loaded.source, sheet: loaded.sheet, file: loaded.file };
642
+ const t = importLabels(ctx.labels);
643
+ const told = tell(ctx, describe(ctx, data, "load", loaded.notes));
644
+ if (told.refused) {
645
+ if (told.error !== void 0) {
646
+ ctx.announce(fill(t.refused, { name: loaded.source.name, message: messageOf(told.error) }), { tone: "error" });
647
+ }
648
+ return false;
649
+ }
650
+ const where = { lang: ctx.labels.lang, locale: ctx.locale };
651
+ ctx.setSteps(pushData(ctx.steps, { data: ctx.imported, history: ctx.history.snapshot() }, fill(t.stepLoaded, { name: loaded.source.name })));
652
+ ctx.setImported(data);
653
+ ctx.announce(fill(t.loaded, { name: loaded.source.name, rows: plural(t.rows, loaded.rows, where), columns: plural(t.columns, loaded.columns.length, where) }), { action: { label: ctx.labels.undo, run: ctx.undo } });
654
+ return true;
655
+ }
656
+ function backToOriginal(ctx) {
657
+ if (!ctx.imported) {
658
+ return;
659
+ }
660
+ const t = importLabels(ctx.labels);
661
+ const kept = hostHistory(ctx.steps);
662
+ ctx.setSteps(pushData(ctx.steps, { data: ctx.imported, history: ctx.history.snapshot() }, t.backToOriginal));
663
+ ctx.setImported(null);
664
+ if (kept) {
665
+ ctx.history.replace({ ...kept, past: [], future: [] });
666
+ }
667
+ tell(ctx, describe(ctx, null, "original"));
668
+ ctx.announce(t.originalShown, { action: { label: ctx.labels.undo, run: ctx.undo } });
669
+ }
670
+ function moveData(ctx, back) {
671
+ const moved = (back ? undoData : redoData)(ctx.steps, { data: ctx.imported, history: ctx.history.snapshot() });
672
+ if (!moved) {
673
+ return null;
674
+ }
675
+ ctx.setSteps(moved.steps);
676
+ ctx.setImported(moved.step.data);
677
+ ctx.history.replace(moved.step.history);
678
+ tell(ctx, describe(ctx, moved.step.data, back ? "undo" : "redo"));
679
+ return moved.step.note;
680
+ }
681
+ function restoreData(ctx) {
682
+ if (ctx.imported) {
683
+ tell(ctx, describe(ctx, ctx.imported, "restore"));
684
+ }
685
+ }
686
+
687
+ // src/import-host.jsx
688
+ var jobs = 0;
689
+ var shownErrors = /* @__PURE__ */ new WeakMap();
690
+ function sayError(api, text) {
691
+ const id = api.announce(text, { tone: "error" });
692
+ if (typeof id === "number" && typeof api.dismiss === "function") {
693
+ shownErrors.set(api.dismiss, [...shownErrors.get(api.dismiss) ?? [], id]);
694
+ }
695
+ }
696
+ function startFiles(api, files) {
697
+ const dismiss = api.dismiss;
698
+ if (typeof dismiss === "function") {
699
+ (shownErrors.get(dismiss) ?? []).forEach((id) => dismiss(id));
700
+ shownErrors.delete(dismiss);
701
+ }
702
+ if (files.length === 1) {
703
+ api.setJob({ file: files[0], n: ++jobs });
704
+ } else if (files.length > 1) {
705
+ sayError(api, importLabels(api.labels).dropOne);
706
+ }
707
+ }
708
+ function pickFile(input) {
709
+ if (input) {
710
+ input.value = "";
711
+ input.click();
712
+ }
713
+ }
714
+ function ImportLayer({ api, input }) {
715
+ const name = useFormName();
716
+ const job = api.job;
717
+ return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(
718
+ "input",
719
+ {
720
+ ref: input,
721
+ type: "file",
722
+ name,
723
+ hidden: true,
724
+ tabIndex: -1,
725
+ "aria-hidden": "true",
726
+ accept: acceptOf(api.plugins),
727
+ onChange: (e) => startFiles(api, [...e.target.files ?? []]),
728
+ "data-testid": "file-input"
729
+ }
730
+ ), api.dragging ? /* @__PURE__ */ React2.createElement(DropOverlay, { labels: api.labels, locale: api.locale, plugins: api.plugins, box: api.box }) : null, job ? /* @__PURE__ */ React2.createElement(
731
+ ImportDialog,
732
+ {
733
+ key: job.n,
734
+ job,
735
+ labels: api.labels,
736
+ locale: api.locale,
737
+ plugins: api.plugins,
738
+ worker: api.worker,
739
+ limits: api.limits,
740
+ timeZone: api.timeZone,
741
+ announce: (text, extra) => extra?.tone === "error" ? sayError(api, text) : api.announce(text, extra),
742
+ onClose: () => api.setJob((j) => j === job ? null : j),
743
+ onApply: (loaded) => {
744
+ loadData(api, loaded);
745
+ api.setJob((j) => j === job ? null : j);
746
+ }
747
+ }
748
+ ) : null);
749
+ }
750
+ function DataMenuPanel({ api, close }) {
751
+ const source = { name: api.sourceName ?? null, rows: api.encoded.length, columns: api.encoded.schema.fields.length, imported: Boolean(api.imported) };
752
+ return /* @__PURE__ */ React2.createElement(DataPanel, { labels: api.labels, locale: api.locale, source, plugins: api.plugins, close, onPick: api.pick, onBack: () => backToOriginal(api) });
753
+ }
754
+ function SourceLine2({ api }) {
755
+ return api.imported ? /* @__PURE__ */ React2.createElement(SourceLine, { labels: api.labels, source: { name: api.imported.source.name, sheet: api.imported.sheet } }) : null;
756
+ }
757
+ export {
758
+ DataMenuPanel,
759
+ ImportLayer,
760
+ SourceLine2 as SourceLine,
761
+ moveData,
762
+ pickFile,
763
+ restoreData,
764
+ startFiles
765
+ };