@casoon/opengrid 0.14.0 → 0.16.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.
- package/CHANGELOG.md +621 -19
- package/README.md +19 -2
- package/engine/opengrid_wasm_bg.wasm +0 -0
- package/loader.d.ts +451 -24
- package/loader.js +584 -132
- package/package.json +13 -6
- package/pkg/opengrid_web_components.d.ts +94 -23
- package/pkg/opengrid_web_components.js +451 -59
- package/pkg/opengrid_web_components_bg.wasm +0 -0
- package/pkg/opengrid_web_components_bg.wasm.d.ts +15 -6
- package/pkg/snippets/opengrid-web-components-35ed06b453a9b215/inline0.js +8 -0
- package/pkg/snippets/opengrid-web-components-35ed06b453a9b215/inline1.js +58 -0
- package/pkg/snippets/opengrid-web-core-b41714d4e7311909/inline2.js +89 -0
- package/react/index.d.ts +20 -2
- package/react/index.js +32 -6
- package/svelte/Opengrid.svelte +46 -11
- package/svelte/OpengridGrid.svelte +20 -1
- package/svelte/OpengridPivot.svelte +3 -3
- package/svelte/OpengridTable.svelte +1 -1
- package/svelte/index.d.ts +57 -18
- package/svelte/index.js +1 -1
- package/texts/de.d.ts +5 -0
- package/texts/de.js +245 -0
- package/vue/index.d.ts +49 -7
- package/vue/index.js +41 -11
- package/worker.js +6 -3
- package/xlsx/opengrid_xlsx.d.ts +69 -0
- package/xlsx/opengrid_xlsx.js +375 -0
- package/xlsx/opengrid_xlsx_bg.wasm +0 -0
- package/xlsx/opengrid_xlsx_bg.wasm.d.ts +16 -0
- package/pkg/snippets/opengrid-web-components-56667a20e9158a6a/inline0.js +0 -17
- /package/pkg/snippets/{opengrid-web-core-a3505e32fee0c1ed → opengrid-web-core-b41714d4e7311909}/inline0.js +0 -0
- /package/pkg/snippets/{opengrid-web-core-a3505e32fee0c1ed → opengrid-web-core-b41714d4e7311909}/inline1.js +0 -0
package/loader.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @casoon/opengrid loader
|
|
3
|
-
* §JavaScript-Minimum).
|
|
2
|
+
* @casoon/opengrid loader: the small amount of JavaScript the elements need.
|
|
4
3
|
*
|
|
5
4
|
* The browser loads exactly this file plus the WASM module. `loader.js` does
|
|
6
5
|
* three small things and no domain logic:
|
|
@@ -11,7 +10,7 @@
|
|
|
11
10
|
* because of a missing `.wasm`.
|
|
12
11
|
*
|
|
13
12
|
* The fallback is intentionally the same empty skeleton the Rust element
|
|
14
|
-
* renders;
|
|
13
|
+
* renders; the Rust element replaces it once the table carries data.
|
|
15
14
|
*
|
|
16
15
|
* Point 19 adds the two providers. Both expose the same tiny shape the elements
|
|
17
16
|
* consume (`load`, `execute`, `terminate`), so a page switches between the
|
|
@@ -19,7 +18,7 @@
|
|
|
19
18
|
*
|
|
20
19
|
* createWorkerProvider() engine in a module worker
|
|
21
20
|
* createLocalProvider(engine) engine on the main thread
|
|
22
|
-
* createRestProvider({ url, source, token }) opengrid-server
|
|
21
|
+
* createRestProvider({ url, source, token }) opengrid-server over HTTP
|
|
23
22
|
*
|
|
24
23
|
* A provider's `execute` answers the result JSON **or** the binary result form
|
|
25
24
|
* (decision E35, a `Uint8Array`): the elements and `exportRows` read both. The
|
|
@@ -28,7 +27,7 @@
|
|
|
28
27
|
* when it answers JSON.
|
|
29
28
|
*
|
|
30
29
|
* Every provider's `execute(queryJson, mode, { signal })` may take an
|
|
31
|
-
* `AbortSignal` as its third argument
|
|
30
|
+
* `AbortSignal` as its third argument. The providers that talk HTTP
|
|
32
31
|
* hand it to `fetch`, so an aborted export leaves no request running; the tab
|
|
33
32
|
* and the worker cannot stop a query that has started and ignore it — the
|
|
34
33
|
* caller drops their answer.
|
|
@@ -37,14 +36,10 @@
|
|
|
37
36
|
* single worker of V1 (no pool, no SharedArrayBuffer).
|
|
38
37
|
*/
|
|
39
38
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
* Default location of the engine module's glue, shipped under `engine/`. A
|
|
45
|
-
* string, not a `URL`: it travels to the worker by `postMessage`.
|
|
46
|
-
*/
|
|
47
|
-
const DEFAULT_ENGINE_URL = new URL("./engine/opengrid_wasm.js", import.meta.url).href;
|
|
39
|
+
// The packaged glue (its path is fixed by the package), imported statically: a bundler
|
|
40
|
+
// follows the import, and the `new URL("…_bg.wasm", import.meta.url)` inside the
|
|
41
|
+
// glue, so the `.wasm` ends up in its output. `moduleUrl` replaces it.
|
|
42
|
+
import * as packaged from "./pkg/opengrid_web_components.js";
|
|
48
43
|
|
|
49
44
|
/** Set once the first `loadOpengrid` call has run. */
|
|
50
45
|
let loading;
|
|
@@ -57,8 +52,7 @@ let loading;
|
|
|
57
52
|
* @param {string} [options.wasmUrl] explicit `.wasm` URL, if it is not next to the glue.
|
|
58
53
|
* @returns {Promise<{fallback: boolean, module?: object}>} whether the DOM fallback was
|
|
59
54
|
* installed, and the loaded WASM module so a page can call its exports —
|
|
60
|
-
* `set_provider`
|
|
61
|
-
* rebuilds the component).
|
|
55
|
+
* `set_provider` and `set_texts` (call it first: it rebuilds the component).
|
|
62
56
|
*/
|
|
63
57
|
export function loadOpengrid(options = {}) {
|
|
64
58
|
if (!loading) {
|
|
@@ -67,9 +61,9 @@ export function loadOpengrid(options = {}) {
|
|
|
67
61
|
return loading;
|
|
68
62
|
}
|
|
69
63
|
|
|
70
|
-
async function start({ moduleUrl
|
|
64
|
+
async function start({ moduleUrl, wasmUrl } = {}) {
|
|
71
65
|
try {
|
|
72
|
-
const module = await import(moduleUrl);
|
|
66
|
+
const module = moduleUrl ? await import(/* @vite-ignore */ moduleUrl) : packaged;
|
|
73
67
|
// wasm-bindgen `--target web` exports the initialiser as the default.
|
|
74
68
|
await module.default(wasmUrl);
|
|
75
69
|
module.register();
|
|
@@ -93,7 +87,7 @@ async function start({ moduleUrl = DEFAULT_MODULE_URL, wasmUrl } = {}) {
|
|
|
93
87
|
*
|
|
94
88
|
* Not exported: `loadOpengrid` installs it when the module fails to load, and a
|
|
95
89
|
* page that reaches for it directly is asking for the broken state on purpose
|
|
96
|
-
* (
|
|
90
|
+
* (an export is a promise).
|
|
97
91
|
*
|
|
98
92
|
* @param {string} [name] the element to define.
|
|
99
93
|
*/
|
|
@@ -157,18 +151,17 @@ function installFallback(name = "opengrid-table") {
|
|
|
157
151
|
*
|
|
158
152
|
* @param {object} [options]
|
|
159
153
|
* @param {string} [options.moduleUrl] wasm-bindgen glue of the engine module;
|
|
160
|
-
* defaults to the packaged one under `engine
|
|
161
|
-
* travels to the worker by `postMessage`.
|
|
154
|
+
* defaults to the packaged one under `engine/`, which `worker.js` imports
|
|
155
|
+
* itself. A string, not a `URL`: it travels to the worker by `postMessage`.
|
|
162
156
|
* @param {string} [options.wasmUrl] explicit `.wasm` URL, if it is not next to the glue.
|
|
163
157
|
* @param {URL|string} [options.workerUrl] the worker entry; defaults to `worker.js` next to this file.
|
|
164
158
|
* @returns {{load: Function, execute: Function, terminate: Function, worker?: Worker}}
|
|
165
159
|
*/
|
|
166
160
|
export function createWorkerProvider({
|
|
167
|
-
moduleUrl
|
|
161
|
+
moduleUrl,
|
|
168
162
|
wasmUrl,
|
|
169
163
|
workerUrl,
|
|
170
164
|
} = {}) {
|
|
171
|
-
const workerScript = workerUrl ?? new URL("./worker.js", import.meta.url);
|
|
172
165
|
let worker;
|
|
173
166
|
let ready;
|
|
174
167
|
let nextId = 1;
|
|
@@ -202,7 +195,11 @@ export function createWorkerProvider({
|
|
|
202
195
|
|
|
203
196
|
function start() {
|
|
204
197
|
if (!worker) {
|
|
205
|
-
|
|
198
|
+
// Written out in full: the `new Worker(new URL(…, import.meta.url), …)` form
|
|
199
|
+
// is what bundlers recognise and bundle.
|
|
200
|
+
worker = workerUrl
|
|
201
|
+
? new Worker(workerUrl, { type: "module" })
|
|
202
|
+
: new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
|
|
206
203
|
worker.onmessage = ({ data }) => onMessage(data);
|
|
207
204
|
ready = request({ type: "init", moduleUrl, wasmUrl });
|
|
208
205
|
}
|
|
@@ -278,7 +275,7 @@ export function createWorkerProvider({
|
|
|
278
275
|
* The grids on an engine provider's sources (issue #182).
|
|
279
276
|
*
|
|
280
277
|
* `watch(host)` is called by `set_provider`; the host is held weakly, so a
|
|
281
|
-
* removed grid is still collected
|
|
278
|
+
* removed grid is still collected. Loading a source — under a new
|
|
282
279
|
* name or over a loaded one, which replaces it — tells every watching grid on
|
|
283
280
|
* that name with an `opengrid-source-replaced` event — it re-runs its query and
|
|
284
281
|
* keeps its view.
|
|
@@ -312,6 +309,115 @@ function createWatchers() {
|
|
|
312
309
|
};
|
|
313
310
|
}
|
|
314
311
|
|
|
312
|
+
/**
|
|
313
|
+
* The grids a REST provider's source is shown in, and the server's stream that
|
|
314
|
+
* says it changed (issue #328): `GET /watch/{source}` with the token — fetch,
|
|
315
|
+
* not `EventSource`, which cannot send a header. The grid is told with a
|
|
316
|
+
* cancelable `opengrid-source-changed` on its element and decides what the
|
|
317
|
+
* reader sees; nothing is queried here. A cut stream is taken up again after
|
|
318
|
+
* the server's `retry` (at most 30 s, longer after each failure); an answer of
|
|
319
|
+
* 4xx ends it, since asking again would not change it.
|
|
320
|
+
*/
|
|
321
|
+
function createChangeStream(endpoint, token) {
|
|
322
|
+
const hosts = new Set();
|
|
323
|
+
let controller = null;
|
|
324
|
+
let closed = false;
|
|
325
|
+
|
|
326
|
+
const alive = () => {
|
|
327
|
+
for (const ref of [...hosts]) {
|
|
328
|
+
if (!ref.deref()) {
|
|
329
|
+
hosts.delete(ref);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return [...hosts].map((ref) => ref.deref());
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
const tell = (name) => {
|
|
336
|
+
for (const host of alive()) {
|
|
337
|
+
host.dispatchEvent(
|
|
338
|
+
new CustomEvent("opengrid-source-changed", { detail: { name }, cancelable: true }),
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
async function run() {
|
|
344
|
+
let wait = 5000;
|
|
345
|
+
let failures = 0;
|
|
346
|
+
while (!closed && alive().length > 0) {
|
|
347
|
+
controller = new AbortController();
|
|
348
|
+
try {
|
|
349
|
+
const response = await fetch(endpoint, {
|
|
350
|
+
headers: { Accept: "text/event-stream", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
|
351
|
+
signal: controller.signal,
|
|
352
|
+
redirect: "error",
|
|
353
|
+
});
|
|
354
|
+
if (response.status >= 400 && response.status < 500) {
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
if (!response.ok || !response.body) {
|
|
358
|
+
throw new Error(`status ${response.status}`);
|
|
359
|
+
}
|
|
360
|
+
failures = 0;
|
|
361
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
362
|
+
let buffer = "";
|
|
363
|
+
for (;;) {
|
|
364
|
+
const { value, done } = await reader.read();
|
|
365
|
+
if (done) {
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
buffer += value;
|
|
369
|
+
let end;
|
|
370
|
+
while ((end = buffer.indexOf("\n\n")) >= 0) {
|
|
371
|
+
const block = buffer.slice(0, end);
|
|
372
|
+
buffer = buffer.slice(end + 2);
|
|
373
|
+
const lines = block.split("\n");
|
|
374
|
+
const retry = lines.find((line) => line.startsWith("retry:"));
|
|
375
|
+
if (retry) {
|
|
376
|
+
wait = Number(retry.slice(6)) || wait;
|
|
377
|
+
}
|
|
378
|
+
if (lines.includes("event: changed")) {
|
|
379
|
+
const data = lines.find((line) => line.startsWith("data:"));
|
|
380
|
+
let name;
|
|
381
|
+
try {
|
|
382
|
+
name = JSON.parse(data.slice(5)).source;
|
|
383
|
+
} catch {
|
|
384
|
+
name = undefined;
|
|
385
|
+
}
|
|
386
|
+
tell(name);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
} catch {
|
|
391
|
+
if (closed) {
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
failures += 1;
|
|
395
|
+
}
|
|
396
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(30000, wait * 2 ** Math.min(failures, 3))));
|
|
397
|
+
}
|
|
398
|
+
controller = null;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
return {
|
|
402
|
+
watch(host) {
|
|
403
|
+
for (const ref of hosts) {
|
|
404
|
+
if (ref.deref() === host) {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
hosts.add(new WeakRef(host));
|
|
409
|
+
if (!controller && !closed) {
|
|
410
|
+
controller = new AbortController();
|
|
411
|
+
run();
|
|
412
|
+
}
|
|
413
|
+
},
|
|
414
|
+
close() {
|
|
415
|
+
closed = true;
|
|
416
|
+
controller?.abort();
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
315
421
|
/** Rows as the engine reads them: a JSON array of objects, as text. */
|
|
316
422
|
function rowsJson(rows) {
|
|
317
423
|
return typeof rows === "string" ? rows : JSON.stringify(rows);
|
|
@@ -320,7 +426,7 @@ function rowsJson(rows) {
|
|
|
320
426
|
/**
|
|
321
427
|
* A provider over an engine that is already initialised on the main thread.
|
|
322
428
|
*
|
|
323
|
-
* The fallback path of the elements
|
|
429
|
+
* The fallback path of the elements: no worker, the same shape as
|
|
324
430
|
* `createWorkerProvider`, so a page can swap the two without changing the grid.
|
|
325
431
|
*
|
|
326
432
|
* @param {object} engine the loaded `Engine` from the engine module.
|
|
@@ -362,14 +468,14 @@ export function createLocalProvider(engine) {
|
|
|
362
468
|
}
|
|
363
469
|
|
|
364
470
|
/**
|
|
365
|
-
* A provider that talks to an `opengrid-server` over HTTP
|
|
471
|
+
* A provider that talks to an `opengrid-server` over HTTP.
|
|
366
472
|
*
|
|
367
473
|
* The same shape as `createLocalProvider` and `createWorkerProvider`, so a page
|
|
368
474
|
* swaps local for remote without touching the grid: `set_provider` sees one
|
|
369
475
|
* `execute(queryJson)` either way. The difference is only where the work
|
|
370
476
|
* happens — and that the answer can fail for reasons a local engine never has.
|
|
371
477
|
*
|
|
372
|
-
* The server's error form (
|
|
478
|
+
* The server's error form (docs/protocol.md, Errors) is unwrapped here: a failed request
|
|
373
479
|
* rejects with the server's own sentence, so the grid's status line shows
|
|
374
480
|
* "unknown source …" rather than "HTTP 404". The `Error` also carries the
|
|
375
481
|
* HTTP `status` and the form's `code` and `path` (issue #16), so a page can
|
|
@@ -383,9 +489,9 @@ export function createLocalProvider(engine) {
|
|
|
383
489
|
* @param {string} options.url base URL of the server, e.g. `http://127.0.0.1:8081`.
|
|
384
490
|
* @param {string} options.source the configured data source name.
|
|
385
491
|
* @param {string} [options.token] bearer token; the server refuses without one.
|
|
386
|
-
* @returns {{execute: Function, describe: Function, export: Function}}
|
|
492
|
+
* @returns {{execute: Function, describe: Function, export: Function, exportPivot: Function}}
|
|
387
493
|
*/
|
|
388
|
-
export function createRestProvider({ url, source, token } = {}) {
|
|
494
|
+
export function createRestProvider({ url, source, token, watch = false } = {}) {
|
|
389
495
|
const base = String(url).replace(/\/$/, "");
|
|
390
496
|
const endpoint = `${base}/query/${encodeURIComponent(source)}`;
|
|
391
497
|
const headers = { "Content-Type": "application/json", Accept: ACCEPT_ANSWER };
|
|
@@ -394,14 +500,31 @@ export function createRestProvider({ url, source, token } = {}) {
|
|
|
394
500
|
}
|
|
395
501
|
// The export answers a file, CSV or JSON, whatever a query would.
|
|
396
502
|
const { Accept: _answer, ...exportHeaders } = headers;
|
|
503
|
+
const changes = watch
|
|
504
|
+
? createChangeStream(`${base}/watch/${encodeURIComponent(source)}`, token)
|
|
505
|
+
: null;
|
|
397
506
|
|
|
398
507
|
return {
|
|
508
|
+
/**
|
|
509
|
+
* With `watch: true`, `set_provider` calls this: the grid hears
|
|
510
|
+
* `opengrid-source-changed` when the server says the source changed
|
|
511
|
+
* (issue #328). A page does not call it.
|
|
512
|
+
*/
|
|
513
|
+
watch(host) {
|
|
514
|
+
changes?.watch(host);
|
|
515
|
+
},
|
|
516
|
+
|
|
517
|
+
/** Closes the change stream, if there is one. */
|
|
518
|
+
terminate() {
|
|
519
|
+
changes?.close();
|
|
520
|
+
},
|
|
521
|
+
|
|
399
522
|
/** Where the queries run; the grid names it in its footer (issue #33). */
|
|
400
523
|
kind: "remote",
|
|
401
524
|
/**
|
|
402
525
|
* What the server says this source is: `{ name, schema, capabilities }`.
|
|
403
526
|
*
|
|
404
|
-
* A planner needs both halves before it can split anything
|
|
527
|
+
* A planner needs both halves before it can split anything — the
|
|
405
528
|
* schema to validate against, the capabilities to know what may be pushed.
|
|
406
529
|
* The schema is the one this token is allowed to see.
|
|
407
530
|
*/
|
|
@@ -448,7 +571,7 @@ export function createRestProvider({ url, source, token } = {}) {
|
|
|
448
571
|
* and the CSV options (`delimiter`, `bom`, `protectFormulas`, `null`).
|
|
449
572
|
* @returns {Promise<Blob>} `text/csv;charset=utf-8` or `application/json`.
|
|
450
573
|
*/
|
|
451
|
-
async export(query, { format = "csv", signal, maxRows, onProgress, ...csv } = {}) {
|
|
574
|
+
async export(query, { format = "csv", signal, maxRows, onProgress, headers, ...csv } = {}) {
|
|
452
575
|
for (const key of Object.keys(csv)) {
|
|
453
576
|
if (!CSV_OPTIONS.includes(key)) {
|
|
454
577
|
throw new TypeError(`export: unknown option "${key}"`);
|
|
@@ -462,6 +585,10 @@ export function createRestProvider({ url, source, token } = {}) {
|
|
|
462
585
|
parameters.set(key, String(csv[key]));
|
|
463
586
|
}
|
|
464
587
|
}
|
|
588
|
+
// The header texts of CSV and XLSX, one parameter each (issue #353).
|
|
589
|
+
for (const [column, text] of Object.entries(headers ?? {})) {
|
|
590
|
+
parameters.set(`header.${column}`, text);
|
|
591
|
+
}
|
|
465
592
|
const response = await fetch(`${base}/export/${encodeURIComponent(source)}?${parameters}`, {
|
|
466
593
|
method: "POST",
|
|
467
594
|
headers: exportHeaders,
|
|
@@ -494,9 +621,88 @@ export function createRestProvider({ url, source, token } = {}) {
|
|
|
494
621
|
// The type `exportRows` gives its Blob, whatever the header's spelling.
|
|
495
622
|
return new Blob([blob], { type: EXPORT_TYPES[format] ?? EXPORT_TYPES.csv });
|
|
496
623
|
},
|
|
624
|
+
|
|
625
|
+
/** `POST /pivot/{source}?format=xlsx`: see {@link pivotWorkbook}. */
|
|
626
|
+
exportPivot(pivotQuery, options) {
|
|
627
|
+
return pivotWorkbook(`${base}/pivot/${encodeURIComponent(source)}`, exportHeaders, pivotQuery, options);
|
|
628
|
+
},
|
|
497
629
|
};
|
|
498
630
|
}
|
|
499
631
|
|
|
632
|
+
/**
|
|
633
|
+
* The texts a pivot's workbook is written in: the keys `set_texts` gives
|
|
634
|
+
* them, and the parameters `POST /pivot/{source}?format=xlsx` reads.
|
|
635
|
+
*/
|
|
636
|
+
const PIVOT_TEXTS = ["noValue", "emptyValue", "total", "subtotal"];
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* What a calculated measure is shown as (issue #329), after `PIVOT_TEXTS` in
|
|
640
|
+
* the order `pivot_words` gives them. Sent only with a query that has one: a
|
|
641
|
+
* server from before calculated measures refuses a parameter it does not know.
|
|
642
|
+
*/
|
|
643
|
+
const PIVOT_CALC_TEXTS = ["shareOfRow", "shareOfColumn", "shareOfTotal", "runningTotal"];
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* `POST /pivot/{source}?format=xlsx`: a pivot as an XLSX file, a `Blob`
|
|
647
|
+
* (issue #331) — what `exportPivot` of the REST and the pivot provider does.
|
|
648
|
+
*
|
|
649
|
+
* The server answers the pivot of `pivotQuery` as one flat sheet, the table a
|
|
650
|
+
* pivot's CSV is: one header row, every row with its subtotals and the grand
|
|
651
|
+
* total, numbers and dates as cells of their type. Its rules are `/pivot`'s —
|
|
652
|
+
* the token, `allowed_fields`, the mandatory row filter, the pivot's limits —
|
|
653
|
+
* and an export's: `max_xlsx_rows`, and a place among the running exports.
|
|
654
|
+
*
|
|
655
|
+
* `texts` are the words for a total and for a NULL or empty group, under the
|
|
656
|
+
* keys of {@link PIVOT_TEXTS}, and — for a query with a calculated measure —
|
|
657
|
+
* the words of {@link PIVOT_CALC_TEXTS}; any other key is ignored. `exportPivot` reads
|
|
658
|
+
* them from the element; a page that calls this method with a query of its
|
|
659
|
+
* own hands them over, or gets the server's English defaults.
|
|
660
|
+
*
|
|
661
|
+
* @param {string} endpoint `/pivot/{source}` of the server.
|
|
662
|
+
* @param {object} headers the provider's, without `Accept`.
|
|
663
|
+
* @param {object} pivotQuery the pivot query, as an object.
|
|
664
|
+
* @param {object} [options] `format` (`"xlsx"`), `texts`, `signal`.
|
|
665
|
+
* @returns {Promise<Blob>} the workbook.
|
|
666
|
+
*/
|
|
667
|
+
async function pivotWorkbook(endpoint, headers, pivotQuery, options = {}) {
|
|
668
|
+
for (const key of Object.keys(options)) {
|
|
669
|
+
if (!PIVOT_EXPORT_OPTIONS.includes(key)) {
|
|
670
|
+
throw new TypeError(`exportPivot: unknown option "${key}"`);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
const { format, texts, signal } = options;
|
|
674
|
+
if (format !== "xlsx") {
|
|
675
|
+
throw new TypeError(
|
|
676
|
+
`exportPivot: format is "xlsx", not ${JSON.stringify(format)} — a pivot's CSV is get_pivot(host)`,
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
const parameters = new URLSearchParams({ format });
|
|
680
|
+
const calculated = Array.isArray(pivotQuery?.values) && pivotQuery.values.some((value) => value?.calc);
|
|
681
|
+
for (const key of calculated ? [...PIVOT_TEXTS, ...PIVOT_CALC_TEXTS] : PIVOT_TEXTS) {
|
|
682
|
+
if (typeof texts?.[key] === "string") {
|
|
683
|
+
parameters.set(key, texts[key]);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
const response = await fetch(`${endpoint}?${parameters}`, {
|
|
687
|
+
method: "POST",
|
|
688
|
+
headers,
|
|
689
|
+
body: JSON.stringify(pivotQuery),
|
|
690
|
+
signal,
|
|
691
|
+
redirect: "error",
|
|
692
|
+
});
|
|
693
|
+
if (!response.ok) {
|
|
694
|
+
throw refusal(await response.text(), response.status);
|
|
695
|
+
}
|
|
696
|
+
// A server from before this export ignores the parameter and answers the
|
|
697
|
+
// pivot itself: that is not a file to hand out under a workbook's name.
|
|
698
|
+
const type = (response.headers.get("Content-Type") ?? "").split(";")[0].trim().toLowerCase();
|
|
699
|
+
if (type !== EXPORT_TYPES.xlsx) {
|
|
700
|
+
await response.body?.cancel();
|
|
701
|
+
throw new Error("exportPivot: the server answered the pivot, not a workbook — it does not write a pivot as XLSX");
|
|
702
|
+
}
|
|
703
|
+
return new Blob([await response.blob()], { type: EXPORT_TYPES.xlsx });
|
|
704
|
+
}
|
|
705
|
+
|
|
500
706
|
/**
|
|
501
707
|
* What a provider asks the server for: the binary result form (E35), JSON as
|
|
502
708
|
* the fallback — a server that does not know the form answers JSON, and
|
|
@@ -523,7 +729,7 @@ async function answerOf(response) {
|
|
|
523
729
|
/**
|
|
524
730
|
* A failed request as the `Error` it rejects with (issue #16). The message is
|
|
525
731
|
* the server's own sentence, or the status when the body is not the error
|
|
526
|
-
* form of
|
|
732
|
+
* form of docs/protocol.md (Errors). The fields are what a page branches on without reading
|
|
527
733
|
* the sentence: `status` always, `code` and `path` when the error form has
|
|
528
734
|
* them.
|
|
529
735
|
*/
|
|
@@ -563,7 +769,7 @@ function coded(code, message) {
|
|
|
563
769
|
}
|
|
564
770
|
|
|
565
771
|
/**
|
|
566
|
-
* A provider that asks an `opengrid-server` for a whole **pivot
|
|
772
|
+
* A provider that asks an `opengrid-server` for a whole **pivot**.
|
|
567
773
|
*
|
|
568
774
|
* The same shape as every other provider — `execute(json)` in, JSON out — so
|
|
569
775
|
* `set_provider` is unchanged; only the endpoint and the body differ. What comes
|
|
@@ -574,7 +780,7 @@ function coded(code, message) {
|
|
|
574
780
|
* @param {string} options.url base URL of the server.
|
|
575
781
|
* @param {string} options.source the configured data source name.
|
|
576
782
|
* @param {string} [options.token] bearer token.
|
|
577
|
-
* @returns {{execute: Function}}
|
|
783
|
+
* @returns {{execute: Function, pivot: Function, exportPivot: Function}}
|
|
578
784
|
*/
|
|
579
785
|
export function createPivotProvider({ url, source, token } = {}) {
|
|
580
786
|
const endpoint = `${String(url).replace(/\/$/, "")}/pivot/${encodeURIComponent(source)}`;
|
|
@@ -594,6 +800,9 @@ export function createPivotProvider({ url, source, token } = {}) {
|
|
|
594
800
|
return answerOf(response);
|
|
595
801
|
}
|
|
596
802
|
|
|
803
|
+
// The export answers a file, whatever a pivot would.
|
|
804
|
+
const { Accept: _answer, ...exportHeaders } = headers;
|
|
805
|
+
|
|
597
806
|
return {
|
|
598
807
|
/** Where the queries run; the grid names it in its footer (issue #33). */
|
|
599
808
|
kind: "remote",
|
|
@@ -601,12 +810,16 @@ export function createPivotProvider({ url, source, token } = {}) {
|
|
|
601
810
|
// a page that called it before.
|
|
602
811
|
execute: pivot,
|
|
603
812
|
pivot,
|
|
813
|
+
/** `POST /pivot/{source}?format=xlsx`: see {@link pivotWorkbook}. */
|
|
814
|
+
exportPivot(pivotQuery, options) {
|
|
815
|
+
return pivotWorkbook(endpoint, exportHeaders, pivotQuery, options);
|
|
816
|
+
},
|
|
604
817
|
};
|
|
605
818
|
}
|
|
606
819
|
|
|
607
820
|
/**
|
|
608
821
|
* A provider that splits each query between a remote source and the engine in
|
|
609
|
-
* this tab
|
|
822
|
+
* this tab.
|
|
610
823
|
*
|
|
611
824
|
* Three steps, all of them JSON:
|
|
612
825
|
*
|
|
@@ -665,8 +878,10 @@ const EXPORT_TYPES = {
|
|
|
665
878
|
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
666
879
|
};
|
|
667
880
|
|
|
881
|
+
/** The options of `exportPivot`, the function and the providers' method. */
|
|
882
|
+
const PIVOT_EXPORT_OPTIONS = ["format", "texts", "signal"];
|
|
668
883
|
/** The options of `exportRows` that are its own. */
|
|
669
|
-
const EXPORT_OPTIONS = ["format", "chunkSize", "maxRows", "onProgress", "signal"];
|
|
884
|
+
const EXPORT_OPTIONS = ["format", "chunkSize", "maxRows", "onProgress", "signal", "headers"];
|
|
670
885
|
/**
|
|
671
886
|
* The options handed to `export_csv` — only these, whatever else is passed.
|
|
672
887
|
* The same list as `CSV_OPTION_KEYS` in
|
|
@@ -679,7 +894,7 @@ const NO_ROWS = '{"total_count":0,"columns":[]}';
|
|
|
679
894
|
|
|
680
895
|
/**
|
|
681
896
|
* Every match of `query`, fetched through `provider` in pieces, as a `Blob` of
|
|
682
|
-
* CSV or JSON
|
|
897
|
+
* CSV or JSON.
|
|
683
898
|
*
|
|
684
899
|
* The browser half of exporting the view: `get_query(host)` says what the
|
|
685
900
|
* reader sees, this fetches all of it and writes it in the notation the server
|
|
@@ -735,9 +950,10 @@ export async function exportRows(provider, query, options = {}) {
|
|
|
735
950
|
const {
|
|
736
951
|
format = "csv",
|
|
737
952
|
chunkSize = 10_000,
|
|
738
|
-
maxRows
|
|
953
|
+
maxRows: askedMaxRows,
|
|
739
954
|
onProgress,
|
|
740
955
|
signal,
|
|
956
|
+
headers,
|
|
741
957
|
delimiter,
|
|
742
958
|
bom,
|
|
743
959
|
protectFormulas,
|
|
@@ -748,13 +964,11 @@ export async function exportRows(provider, query, options = {}) {
|
|
|
748
964
|
`exportRows: format is "csv", "json" or "xlsx", not ${JSON.stringify(format)}`,
|
|
749
965
|
);
|
|
750
966
|
}
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
);
|
|
757
|
-
}
|
|
967
|
+
// A workbook built in the tab is held whole in memory — about a kilobyte a row
|
|
968
|
+
// of five columns, a gigabyte at a million — so its default is lower than the
|
|
969
|
+
// server's, which streams to a file; asked for, it is the page's to raise.
|
|
970
|
+
const maxRows =
|
|
971
|
+
askedMaxRows ?? (format === "xlsx" && typeof provider?.export !== "function" ? XLSX_TAB_MAX_ROWS : 1_000_000);
|
|
758
972
|
if (format !== "csv") {
|
|
759
973
|
// A CSV option on another export would do nothing, and do it silently.
|
|
760
974
|
const stray = CSV_OPTIONS.find((key) => options[key] !== undefined);
|
|
@@ -764,6 +978,18 @@ export async function exportRows(provider, query, options = {}) {
|
|
|
764
978
|
);
|
|
765
979
|
}
|
|
766
980
|
}
|
|
981
|
+
if (headers !== undefined) {
|
|
982
|
+
if (format === "json") {
|
|
983
|
+
throw new TypeError("exportRows: headers name the header row, and a JSON export has none");
|
|
984
|
+
}
|
|
985
|
+
if (
|
|
986
|
+
headers === null ||
|
|
987
|
+
typeof headers !== "object" ||
|
|
988
|
+
Object.values(headers).some((text) => typeof text !== "string")
|
|
989
|
+
) {
|
|
990
|
+
throw new TypeError("exportRows: headers is an object of texts, by column");
|
|
991
|
+
}
|
|
992
|
+
}
|
|
767
993
|
if (!Number.isSafeInteger(chunkSize) || chunkSize < 1) {
|
|
768
994
|
throw new TypeError("exportRows: chunkSize is a whole number of rows, at least 1");
|
|
769
995
|
}
|
|
@@ -789,18 +1015,23 @@ export async function exportRows(provider, query, options = {}) {
|
|
|
789
1015
|
throw aborted();
|
|
790
1016
|
}
|
|
791
1017
|
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
)
|
|
1018
|
+
// The export notation of CSV and JSON is in the element module; a workbook
|
|
1019
|
+
// is written by a module of its own, loaded below when the pieces come.
|
|
1020
|
+
let module;
|
|
1021
|
+
if (format !== "xlsx") {
|
|
1022
|
+
const loaded = await loadOpengrid();
|
|
1023
|
+
if (loaded.fallback) {
|
|
1024
|
+
throw coded(
|
|
1025
|
+
"module_not_loaded",
|
|
1026
|
+
"exportRows: the WebAssembly module did not load, and the export notation is in it",
|
|
1027
|
+
);
|
|
1028
|
+
}
|
|
1029
|
+
module = loaded.module;
|
|
798
1030
|
}
|
|
799
|
-
const { module } = loaded;
|
|
800
1031
|
const csvOptions = { delimiter, bom, protectFormulas, null: nullText };
|
|
801
1032
|
if (format === "csv") {
|
|
802
1033
|
// Read the options now: a wrong one should cost no request.
|
|
803
|
-
module.export_csv(NO_ROWS, csvOptions, false);
|
|
1034
|
+
module.export_csv(NO_ROWS, csvOptions, false, headers);
|
|
804
1035
|
}
|
|
805
1036
|
|
|
806
1037
|
const sort = [...(query.sort ?? [])];
|
|
@@ -818,7 +1049,7 @@ export async function exportRows(provider, query, options = {}) {
|
|
|
818
1049
|
const blob = await unlessAborted(
|
|
819
1050
|
provider.export(
|
|
820
1051
|
{ ...query, sort },
|
|
821
|
-
{ format, signal, maxRows, onProgress, ...(format === "csv" ? csvOptions : {}) },
|
|
1052
|
+
{ format, signal, maxRows, onProgress, headers, ...(format === "csv" ? csvOptions : {}) },
|
|
822
1053
|
),
|
|
823
1054
|
signal,
|
|
824
1055
|
);
|
|
@@ -829,61 +1060,125 @@ export async function exportRows(provider, query, options = {}) {
|
|
|
829
1060
|
return blob;
|
|
830
1061
|
}
|
|
831
1062
|
|
|
832
|
-
//
|
|
833
|
-
//
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
const
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
1063
|
+
// A workbook is built in the tab's memory by the XLSX module, piece by piece,
|
|
1064
|
+
// and is the file at the end: there is no temporary file to stream to (#332).
|
|
1065
|
+
let book;
|
|
1066
|
+
try {
|
|
1067
|
+
return await fetchPieces();
|
|
1068
|
+
} finally {
|
|
1069
|
+
book?.free();
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
async function fetchPieces() {
|
|
1073
|
+
// Each piece becomes a Blob of its own as soon as it is written, so its text
|
|
1074
|
+
// can leave the JS heap; the browser may keep a Blob's bytes elsewhere.
|
|
1075
|
+
const parts = format === "json" ? [new Blob(["["])] : [];
|
|
1076
|
+
let rows = 0;
|
|
1077
|
+
let total;
|
|
1078
|
+
for (;;) {
|
|
1079
|
+
if (signal?.aborted) {
|
|
1080
|
+
throw aborted();
|
|
1081
|
+
}
|
|
1082
|
+
// After the first piece nothing past `total` is asked for.
|
|
1083
|
+
const limit = total === undefined ? chunkSize : Math.min(chunkSize, total - rows);
|
|
1084
|
+
const piece = JSON.stringify({ ...query, sort, offset: rows, limit });
|
|
1085
|
+
const answer = await unlessAborted(ask(provider, piece, signal), signal);
|
|
1086
|
+
const result = countsOf(answer);
|
|
1087
|
+
const count = result.rows;
|
|
1088
|
+
const first = total === undefined;
|
|
1089
|
+
if (first) {
|
|
1090
|
+
total = result.total_count;
|
|
1091
|
+
if (total > maxRows) {
|
|
1092
|
+
throw coded(
|
|
1093
|
+
"too_many_rows",
|
|
1094
|
+
`exportRows: ${total} rows match, more than the ${maxRows} an export may have (maxRows)`,
|
|
1095
|
+
);
|
|
1096
|
+
}
|
|
1097
|
+
if (format === "xlsx" && total > XLSX_MAX_ROWS) {
|
|
1098
|
+
// Excel's limit is an error, never a shortened file — as on the server.
|
|
1099
|
+
throw coded(
|
|
1100
|
+
"too_many_rows",
|
|
1101
|
+
`exportRows: ${total} rows match, more than the ${XLSX_MAX_ROWS} an Excel sheet holds`,
|
|
1102
|
+
);
|
|
1103
|
+
}
|
|
1104
|
+
} else if (result.total_count !== total) {
|
|
1105
|
+
throw changed(`${total} rows matched at first, ${result.total_count} at row ${rows + 1}`);
|
|
1106
|
+
}
|
|
1107
|
+
if (count < limit && rows + count < total) {
|
|
1108
|
+
throw changed(`the rows ended at ${rows + count} of ${total}`);
|
|
1109
|
+
}
|
|
1110
|
+
if (format === "xlsx") {
|
|
1111
|
+
// After the checks above: a refused export does not load the module.
|
|
1112
|
+
if (!book) {
|
|
1113
|
+
book = new (await loadXlsx()).XlsxBook(sheetNameOf(query));
|
|
1114
|
+
if (headers) {
|
|
1115
|
+
book.headers(headers);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
book.add(answer);
|
|
1119
|
+
} else {
|
|
1120
|
+
parts.push(
|
|
1121
|
+
new Blob([
|
|
1122
|
+
format === "csv"
|
|
1123
|
+
? module.export_csv(answer, csvOptions, first, headers)
|
|
1124
|
+
: // `first` here is "no row written yet", not "first piece": after an
|
|
1125
|
+
// empty first piece the next one still leads without a comma.
|
|
1126
|
+
module.export_json(answer, rows === 0),
|
|
1127
|
+
]),
|
|
854
1128
|
);
|
|
855
1129
|
}
|
|
856
|
-
|
|
857
|
-
|
|
1130
|
+
rows += count;
|
|
1131
|
+
onProgress?.({ rows, total });
|
|
1132
|
+
if (rows >= total) {
|
|
1133
|
+
break;
|
|
1134
|
+
}
|
|
858
1135
|
}
|
|
859
|
-
|
|
860
|
-
|
|
1136
|
+
// An abort during the last `onProgress` still means no file.
|
|
1137
|
+
if (signal?.aborted) {
|
|
1138
|
+
throw aborted();
|
|
861
1139
|
}
|
|
862
|
-
|
|
863
|
-
new Blob([
|
|
864
|
-
format === "csv"
|
|
865
|
-
? module.export_csv(answer, csvOptions, first)
|
|
866
|
-
: // `first` here is "no row written yet", not "first piece": after an
|
|
867
|
-
// empty first piece the next one still leads without a comma.
|
|
868
|
-
module.export_json(answer, rows === 0),
|
|
869
|
-
]),
|
|
870
|
-
);
|
|
871
|
-
rows += count;
|
|
872
|
-
onProgress?.({ rows, total });
|
|
873
|
-
if (rows >= total) {
|
|
874
|
-
break;
|
|
1140
|
+
if (format === "xlsx") {
|
|
1141
|
+
return new Blob([book.finish()], { type: EXPORT_TYPES.xlsx });
|
|
875
1142
|
}
|
|
1143
|
+
if (format === "json") {
|
|
1144
|
+
parts.push(new Blob(["]"]));
|
|
1145
|
+
}
|
|
1146
|
+
return new Blob(parts, { type: EXPORT_TYPES[format] });
|
|
876
1147
|
}
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/** The most rows an Excel sheet holds, as `XLSX_MAX_ROWS` in `opengrid-export`. */
|
|
1151
|
+
const XLSX_MAX_ROWS = 1_048_575;
|
|
1152
|
+
|
|
1153
|
+
/** `maxRows` of a workbook written in the tab, unless the page says otherwise. */
|
|
1154
|
+
const XLSX_TAB_MAX_ROWS = 250_000;
|
|
1155
|
+
|
|
1156
|
+
/** The name of the workbook's sheet: the source, which the writer may refuse. */
|
|
1157
|
+
function sheetNameOf(query) {
|
|
1158
|
+
return typeof query.source === "string" && query.source !== "" ? query.source : "export";
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
/**
|
|
1162
|
+
* The XLSX writer of the tab, loaded the first time a workbook is asked for and
|
|
1163
|
+
* kept: a module of its own (`xlsx/`, built by `just wasm-build-xlsx`), so a
|
|
1164
|
+
* page that never exports to Excel does not fetch it. A failed load is not
|
|
1165
|
+
* kept, so a later call tries again.
|
|
1166
|
+
*/
|
|
1167
|
+
let xlsxModule;
|
|
1168
|
+
async function loadXlsx() {
|
|
1169
|
+
xlsxModule ??= import("./xlsx/opengrid_xlsx.js").then(async (glue) => {
|
|
1170
|
+
await glue.default();
|
|
1171
|
+
return glue;
|
|
886
1172
|
});
|
|
1173
|
+
try {
|
|
1174
|
+
return await xlsxModule;
|
|
1175
|
+
} catch (error) {
|
|
1176
|
+
xlsxModule = undefined;
|
|
1177
|
+
throw coded(
|
|
1178
|
+
"module_not_loaded",
|
|
1179
|
+
`exportRows: the XLSX module did not load (${error?.message ?? error})`,
|
|
1180
|
+
);
|
|
1181
|
+
}
|
|
887
1182
|
}
|
|
888
1183
|
|
|
889
1184
|
/**
|
|
@@ -941,14 +1236,88 @@ function changed(detail) {
|
|
|
941
1236
|
);
|
|
942
1237
|
}
|
|
943
1238
|
|
|
1239
|
+
/**
|
|
1240
|
+
* The pivot `host` shows, as an XLSX file from the server (issue #331).
|
|
1241
|
+
*
|
|
1242
|
+
* `get_pivot` writes a pivot's CSV in the element, from the answer it holds.
|
|
1243
|
+
* A workbook is written by `opengrid-server`, so this asks the server for the
|
|
1244
|
+
* pivot again — the element's view as a pivot query, through the provider's
|
|
1245
|
+
* `exportPivot` — and gets the same table as one flat sheet: one header row,
|
|
1246
|
+
* every row with its subtotals and the grand total in the table's order,
|
|
1247
|
+
* numbers and dates as cells of their type. Folded groups are exported, as
|
|
1248
|
+
* in the CSV. If the data moved since the table was drawn, the file is the
|
|
1249
|
+
* newer answer.
|
|
1250
|
+
*
|
|
1251
|
+
* **Only a provider that exports on the server**: `createPivotProvider` and
|
|
1252
|
+
* `createRestProvider` have `exportPivot`. With any other provider — the
|
|
1253
|
+
* engine in the tab or in a worker — it is a `TypeError`, as an XLSX of
|
|
1254
|
+
* `exportRows` is there.
|
|
1255
|
+
*
|
|
1256
|
+
* **The words are the element's.** The totals and the NULL and empty groups
|
|
1257
|
+
* read as in the table: the element's texts as they are now — its defaults,
|
|
1258
|
+
* or what `set_texts` made of them — are read from it and sent along. The
|
|
1259
|
+
* page hands over nothing.
|
|
1260
|
+
*
|
|
1261
|
+
* @param {{exportPivot: Function}} provider the server-backed provider.
|
|
1262
|
+
* @param {HTMLElement} host an `<opengrid-pivot>`.
|
|
1263
|
+
* @param {object} options `format` (`"xlsx"`), `signal`.
|
|
1264
|
+
* @returns {Promise<Blob>} the workbook.
|
|
1265
|
+
*/
|
|
1266
|
+
export async function exportPivot(provider, host, options = {}) {
|
|
1267
|
+
for (const key of Object.keys(options)) {
|
|
1268
|
+
// `texts` is the provider method's: here they are the element's.
|
|
1269
|
+
if (key === "texts" || !PIVOT_EXPORT_OPTIONS.includes(key)) {
|
|
1270
|
+
throw new TypeError(`exportPivot: unknown option "${key}"`);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
if (options.format !== "xlsx") {
|
|
1274
|
+
throw new TypeError(
|
|
1275
|
+
`exportPivot: format is "xlsx", not ${JSON.stringify(options.format)} — a pivot's CSV is get_pivot(host)`,
|
|
1276
|
+
);
|
|
1277
|
+
}
|
|
1278
|
+
if (typeof provider?.exportPivot !== "function") {
|
|
1279
|
+
// An XLSX file is written on the server; the pivot the element holds
|
|
1280
|
+
// cannot become one here.
|
|
1281
|
+
throw new TypeError(
|
|
1282
|
+
"exportPivot: an XLSX export needs a provider that exports on the server (createPivotProvider, createRestProvider)",
|
|
1283
|
+
);
|
|
1284
|
+
}
|
|
1285
|
+
if (options.signal?.aborted) {
|
|
1286
|
+
throw aborted();
|
|
1287
|
+
}
|
|
1288
|
+
const loaded = await loadOpengrid();
|
|
1289
|
+
if (loaded.fallback) {
|
|
1290
|
+
throw coded(
|
|
1291
|
+
"module_not_loaded",
|
|
1292
|
+
"exportPivot: the WebAssembly module did not load, and the pivot's view is read through it",
|
|
1293
|
+
);
|
|
1294
|
+
}
|
|
1295
|
+
const source = host?.getAttribute?.("datasource");
|
|
1296
|
+
const view = host?.localName === "opengrid-pivot" ? loaded.module.get_view(host) : null;
|
|
1297
|
+
if (!view || !source) {
|
|
1298
|
+
throw new TypeError("exportPivot: no pivot to export — an <opengrid-pivot> in the document, with a datasource");
|
|
1299
|
+
}
|
|
1300
|
+
// The request the element sends: `sort` and `filter` only when there is one.
|
|
1301
|
+
const query = { source, rows: view.rows, columns: view.columns, values: view.values };
|
|
1302
|
+
if (view.sort.length > 0) {
|
|
1303
|
+
query.sort = view.sort;
|
|
1304
|
+
}
|
|
1305
|
+
if (view.filter) {
|
|
1306
|
+
query.filter = view.filter;
|
|
1307
|
+
}
|
|
1308
|
+
// The element's words, in the order of `PIVOT_TEXTS` and `PIVOT_CALC_TEXTS`.
|
|
1309
|
+
const words = loaded.module.pivot_words(host);
|
|
1310
|
+
const texts = Object.fromEntries([...PIVOT_TEXTS, ...PIVOT_CALC_TEXTS].map((key, index) => [key, words[index]]));
|
|
1311
|
+
return provider.exportPivot(query, { ...options, texts });
|
|
1312
|
+
}
|
|
1313
|
+
|
|
944
1314
|
/** What an aborted export rejects with, whatever reason `abort()` was given. */
|
|
945
1315
|
function aborted() {
|
|
946
1316
|
return new DOMException("The export was aborted.", "AbortError");
|
|
947
1317
|
}
|
|
948
1318
|
|
|
949
1319
|
/**
|
|
950
|
-
* Supplies an element from one options object, and keeps it supplied
|
|
951
|
-
* point 76).
|
|
1320
|
+
* Supplies an element from one options object, and keeps it supplied.
|
|
952
1321
|
*
|
|
953
1322
|
* Every page — and every framework adapter — would otherwise have to know the
|
|
954
1323
|
* rules of the module functions itself: wait for the module; set the texts
|
|
@@ -959,8 +1328,8 @@ function aborted() {
|
|
|
959
1328
|
*
|
|
960
1329
|
* `update` applies only what changed. A key left out of an update keeps its
|
|
961
1330
|
* value; a key given as `undefined` resets it (texts to English, no formats, no
|
|
962
|
-
* presentation, no choices) — except `provider`,
|
|
963
|
-
* `view`, where `undefined` (or `null`) means the grid leads. Attributes
|
|
1331
|
+
* presentation, no choices, no actions, no validators) — except `provider`,
|
|
1332
|
+
* which has no "none", and `view`, where `undefined` (or `null`) means the grid leads. Attributes
|
|
964
1333
|
* (`label`, `columns`, `group-by`, …) are not options: the page or the
|
|
965
1334
|
* framework sets them on the element as usual.
|
|
966
1335
|
*
|
|
@@ -973,12 +1342,17 @@ function aborted() {
|
|
|
973
1342
|
* set). On an element that is not, the view **and the provider** wait for the
|
|
974
1343
|
* next `update` — together, so the first query still asks for the view.
|
|
975
1344
|
*
|
|
1345
|
+
* **Editing** (issue #206): `onRowAdd` answers with the new row's state — or a
|
|
1346
|
+
* promise of it — which is `set_row_state`; `setCellState` and `setValues` on
|
|
1347
|
+
* the connection are `set_cell_state` and `set_values`, and wait for the
|
|
1348
|
+
* module like every option does.
|
|
1349
|
+
*
|
|
976
1350
|
* `connect` loads the module with `loadOpengrid()`, whose first call decides
|
|
977
1351
|
* the URLs: a page that needs its own calls `loadOpengrid(options)` first.
|
|
978
1352
|
*
|
|
979
1353
|
* @param {HTMLElement} host an `<opengrid-grid>`, `-table` or `-pivot`.
|
|
980
1354
|
* @param {object} options see `ConnectOptions` in `loader.d.ts`.
|
|
981
|
-
* @returns {{ready: Promise<{fallback: boolean, module?: object}>, update: Function, disconnect: Function}}
|
|
1355
|
+
* @returns {{ready: Promise<{fallback: boolean, module?: object}>, update: Function, setCellState: Function, setValues: Function, disconnect: Function}}
|
|
982
1356
|
*/
|
|
983
1357
|
export function connect(host, options = {}) {
|
|
984
1358
|
let current = { ...options };
|
|
@@ -1011,11 +1385,54 @@ export function connect(host, options = {}) {
|
|
|
1011
1385
|
],
|
|
1012
1386
|
["opengrid-selection-change", (event) => current.onSelectionChange?.(event.detail)],
|
|
1013
1387
|
["opengrid-cell-change", (event) => current.onCellChange?.(event.detail)],
|
|
1388
|
+
["opengrid-row-add", (event) => answerRowAdd(event.detail)],
|
|
1389
|
+
["opengrid-paste", (event) => current.onPaste?.(event.detail)],
|
|
1390
|
+
["opengrid-bulk-change", (event) => current.onBulkChange?.(event.detail)],
|
|
1391
|
+
["opengrid-row-action", (event) => current.onRowAction?.(event.detail)],
|
|
1392
|
+
["opengrid-drill-down", (event) => current.onDrillDown?.(event.detail)],
|
|
1393
|
+
["opengrid-source-replaced", (event) => current.onSourceReplaced?.(event.detail)],
|
|
1014
1394
|
];
|
|
1015
1395
|
for (const [type, listener] of listeners) {
|
|
1016
1396
|
host.addEventListener(type, listener);
|
|
1017
1397
|
}
|
|
1018
1398
|
|
|
1399
|
+
/**
|
|
1400
|
+
* `onRowAdd`'s answer becomes the row's state: a promise shows `saving` until
|
|
1401
|
+
* it settles — resolved with nothing, the row is saved — and a rejection is
|
|
1402
|
+
* an `error` with its message. An undone add has no row left to answer for.
|
|
1403
|
+
*/
|
|
1404
|
+
function answerRowAdd(detail) {
|
|
1405
|
+
const answer = current.onRowAdd?.(detail);
|
|
1406
|
+
if (answer == null || detail.undo) {
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
const key = detail.provisionalKey;
|
|
1410
|
+
if (typeof answer.then !== "function") {
|
|
1411
|
+
setRowState(key, answer);
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
setRowState(key, { state: "saving" });
|
|
1415
|
+
answer.then(
|
|
1416
|
+
(state) => setRowState(key, state ?? { state: "saved" }),
|
|
1417
|
+
(error) => setRowState(key, { state: "error", message: String(error?.message ?? error) }),
|
|
1418
|
+
);
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
function setRowState(key, { state, key: saved, message }) {
|
|
1422
|
+
if (module && connected) {
|
|
1423
|
+
module.set_row_state(host, key, state, state === "saved" ? saved : message);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
/** Runs `call` with the module — now, or once it has loaded. */
|
|
1428
|
+
function withModule(call) {
|
|
1429
|
+
if (module) {
|
|
1430
|
+
call(module);
|
|
1431
|
+
} else {
|
|
1432
|
+
ready.then(() => module && connected && call(module));
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1019
1436
|
/** Writes one option if it differs from what the element has. */
|
|
1020
1437
|
function write(name, value, key, apply) {
|
|
1021
1438
|
if (applied.has(name) && applied.get(name) === key) {
|
|
@@ -1064,11 +1481,18 @@ export function connect(host, options = {}) {
|
|
|
1064
1481
|
// first query is the only one and asks for the right thing.
|
|
1065
1482
|
if ("texts" in changed) {
|
|
1066
1483
|
const texts = changed.texts ?? {};
|
|
1067
|
-
write("texts", texts, stableKey(texts), (value) =>
|
|
1484
|
+
write("texts", texts, stableKey(texts), (value) => {
|
|
1485
|
+
// `set_texts` adds to the texts the element has; this option is all of
|
|
1486
|
+
// them, so what an earlier value set and this one leaves out goes first.
|
|
1487
|
+
module.set_texts(host, null);
|
|
1488
|
+
if (Object.keys(value).length > 0) {
|
|
1489
|
+
module.set_texts(host, value);
|
|
1490
|
+
}
|
|
1491
|
+
});
|
|
1068
1492
|
}
|
|
1069
1493
|
if ("formats" in changed) {
|
|
1070
1494
|
const formats = changed.formats ?? {};
|
|
1071
|
-
write("formats", formats,
|
|
1495
|
+
write("formats", formats, identityKey(formats), (value) => module.set_formats(host, value));
|
|
1072
1496
|
}
|
|
1073
1497
|
if ("presentation" in changed) {
|
|
1074
1498
|
const presentation = changed.presentation ?? {};
|
|
@@ -1080,6 +1504,28 @@ export function connect(host, options = {}) {
|
|
|
1080
1504
|
const choices = changed.choices ?? {};
|
|
1081
1505
|
write("choices", choices, stableKey(choices), (value) => module.set_choices(host, value));
|
|
1082
1506
|
}
|
|
1507
|
+
if ("actions" in changed) {
|
|
1508
|
+
const actions = changed.actions ?? [];
|
|
1509
|
+
write("actions", actions, stableKey(actions), (value) => module.set_actions(host, value));
|
|
1510
|
+
}
|
|
1511
|
+
if ("cellTemplates" in changed) {
|
|
1512
|
+
const cellTemplates = changed.cellTemplates ?? {};
|
|
1513
|
+
write("cellTemplates", cellTemplates, identityKey(cellTemplates), (value) =>
|
|
1514
|
+
module.set_cell_templates(host, value),
|
|
1515
|
+
);
|
|
1516
|
+
}
|
|
1517
|
+
if ("detailRenderer" in changed) {
|
|
1518
|
+
const detailRenderer = changed.detailRenderer ?? null;
|
|
1519
|
+
write("detailRenderer", detailRenderer, identityKey({ detailRenderer }), (value) =>
|
|
1520
|
+
module.set_detail_renderer(host, value),
|
|
1521
|
+
);
|
|
1522
|
+
}
|
|
1523
|
+
if ("validators" in changed) {
|
|
1524
|
+
const validators = changed.validators ?? {};
|
|
1525
|
+
write("validators", validators, identityKey(validators), (value) =>
|
|
1526
|
+
module.set_validators(host, value),
|
|
1527
|
+
);
|
|
1528
|
+
}
|
|
1083
1529
|
|
|
1084
1530
|
const wantsView =
|
|
1085
1531
|
current.view != null ? "view" in changed || deferred : !defaultApplied && current.defaultView != null;
|
|
@@ -1128,6 +1574,12 @@ export function connect(host, options = {}) {
|
|
|
1128
1574
|
current = { ...current, ...next };
|
|
1129
1575
|
apply(next);
|
|
1130
1576
|
},
|
|
1577
|
+
setCellState(key, column, state, message) {
|
|
1578
|
+
withModule((loaded) => loaded.set_cell_state(host, key, column, state, message));
|
|
1579
|
+
},
|
|
1580
|
+
setValues(values) {
|
|
1581
|
+
withModule((loaded) => loaded.set_values(host, values));
|
|
1582
|
+
},
|
|
1131
1583
|
disconnect() {
|
|
1132
1584
|
connected = false;
|
|
1133
1585
|
for (const [type, listener] of listeners) {
|
|
@@ -1137,36 +1589,36 @@ export function connect(host, options = {}) {
|
|
|
1137
1589
|
};
|
|
1138
1590
|
}
|
|
1139
1591
|
|
|
1140
|
-
/**
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1592
|
+
/**
|
|
1593
|
+
* A JSON key that does not depend on the order an object's keys were written
|
|
1594
|
+
* in; `each` may stand in for a value first.
|
|
1595
|
+
*/
|
|
1596
|
+
function stableKey(value, each = (inner) => inner) {
|
|
1597
|
+
return JSON.stringify(value, (_, raw) => {
|
|
1598
|
+
const inner = each(raw);
|
|
1599
|
+
return inner && typeof inner === "object" && !Array.isArray(inner)
|
|
1144
1600
|
? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
|
|
1145
|
-
: inner
|
|
1146
|
-
);
|
|
1601
|
+
: inner;
|
|
1602
|
+
});
|
|
1147
1603
|
}
|
|
1148
1604
|
|
|
1149
1605
|
/**
|
|
1150
|
-
* Formats compare by identity where they are functions and by
|
|
1151
|
-
*
|
|
1152
|
-
* two different functions never compare equal.
|
|
1606
|
+
* Formats and validators compare by identity where they are functions and by
|
|
1607
|
+
* value elsewhere (`Intl` options, `block`). Function identities are numbered
|
|
1608
|
+
* per call site so two different functions never compare equal.
|
|
1153
1609
|
*/
|
|
1154
1610
|
const functionIds = new WeakMap();
|
|
1155
1611
|
let nextFunctionId = 1;
|
|
1156
|
-
function
|
|
1157
|
-
return stableKey(
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
return [column, { function: functionIds.get(format) }];
|
|
1167
|
-
}),
|
|
1168
|
-
),
|
|
1169
|
-
);
|
|
1612
|
+
function identityKey(value) {
|
|
1613
|
+
return stableKey(value, (inner) => {
|
|
1614
|
+
if (typeof inner !== "function") {
|
|
1615
|
+
return inner;
|
|
1616
|
+
}
|
|
1617
|
+
if (!functionIds.has(inner)) {
|
|
1618
|
+
functionIds.set(inner, nextFunctionId++);
|
|
1619
|
+
}
|
|
1620
|
+
return { function: functionIds.get(inner) };
|
|
1621
|
+
});
|
|
1170
1622
|
}
|
|
1171
1623
|
|
|
1172
1624
|
/**
|