@casoon/opengrid 0.15.0 → 0.17.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 (40) hide show
  1. package/CHANGELOG.md +282 -1
  2. package/README.md +6 -4
  3. package/collation/opengrid_collation.d.ts +47 -0
  4. package/collation/opengrid_collation.js +256 -0
  5. package/collation/opengrid_collation_bg.wasm +0 -0
  6. package/collation/opengrid_collation_bg.wasm.d.ts +10 -0
  7. package/collation.js +78 -0
  8. package/engine/opengrid_wasm.d.ts +18 -1
  9. package/engine/opengrid_wasm.js +76 -0
  10. package/engine/opengrid_wasm_bg.wasm +0 -0
  11. package/engine/opengrid_wasm_bg.wasm.d.ts +5 -1
  12. package/loader.d.ts +405 -18
  13. package/loader.js +485 -95
  14. package/package.json +11 -1
  15. package/pkg/opengrid_web_components.d.ts +76 -10
  16. package/pkg/opengrid_web_components.js +346 -60
  17. package/pkg/opengrid_web_components_bg.wasm +0 -0
  18. package/pkg/opengrid_web_components_bg.wasm.d.ts +18 -9
  19. package/react/index.d.ts +10 -2
  20. package/react/index.js +10 -3
  21. package/svelte/Opengrid.svelte +7 -1
  22. package/svelte/OpengridGrid.svelte +7 -1
  23. package/svelte/OpengridPivot.svelte +3 -3
  24. package/svelte/OpengridTable.svelte +1 -1
  25. package/svelte/index.d.ts +14 -2
  26. package/svelte/index.js +1 -1
  27. package/texts/de.d.ts +5 -0
  28. package/texts/de.js +245 -0
  29. package/vue/index.d.ts +14 -2
  30. package/vue/index.js +11 -6
  31. package/worker.js +7 -3
  32. package/xlsx/opengrid_xlsx.d.ts +69 -0
  33. package/xlsx/opengrid_xlsx.js +375 -0
  34. package/xlsx/opengrid_xlsx_bg.wasm +0 -0
  35. package/xlsx/opengrid_xlsx_bg.wasm.d.ts +16 -0
  36. /package/pkg/snippets/{opengrid-web-components-ef3def04de0cb619 → opengrid-web-components-ae047af7b34e4f04}/inline0.js +0 -0
  37. /package/pkg/snippets/{opengrid-web-components-ef3def04de0cb619 → opengrid-web-components-ae047af7b34e4f04}/inline1.js +0 -0
  38. /package/pkg/snippets/{opengrid-web-core-78fdded9b8a374ed → opengrid-web-core-b158b7dd980e3998}/inline0.js +0 -0
  39. /package/pkg/snippets/{opengrid-web-core-78fdded9b8a374ed → opengrid-web-core-b158b7dd980e3998}/inline1.js +0 -0
  40. /package/pkg/snippets/{opengrid-web-core-78fdded9b8a374ed → opengrid-web-core-b158b7dd980e3998}/inline2.js +0 -0
package/loader.js CHANGED
@@ -1,6 +1,5 @@
1
1
  /**
2
- * @casoon/opengrid loader (plan point 13, plan/spezifikation/08-rendering.md
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; point 14 replaces it once the table carries data.
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 über HTTP (point 27)
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 (point 84). The providers that talk HTTP
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,10 +36,12 @@
37
36
  * single worker of V1 (no pool, no SharedArrayBuffer).
38
37
  */
39
38
 
40
- // The packaged glue (point 40 pins the path), imported statically: a bundler
39
+ // The packaged glue (its path is fixed by the package), imported statically: a bundler
41
40
  // follows the import, and the `new URL("…_bg.wasm", import.meta.url)` inside the
42
41
  // glue, so the `.wasm` ends up in its output. `moduleUrl` replaces it.
43
42
  import * as packaged from "./pkg/opengrid_web_components.js";
43
+ // The engine's collator, for a query that sorts by a locale (rule S4a).
44
+ import { withCollator } from "./collation.js";
44
45
 
45
46
  /** Set once the first `loadOpengrid` call has run. */
46
47
  let loading;
@@ -53,8 +54,7 @@ let loading;
53
54
  * @param {string} [options.wasmUrl] explicit `.wasm` URL, if it is not next to the glue.
54
55
  * @returns {Promise<{fallback: boolean, module?: object}>} whether the DOM fallback was
55
56
  * installed, and the loaded WASM module so a page can call its exports —
56
- * `set_provider` (point 14) and `set_texts` (point 48, call it first: it
57
- * rebuilds the component).
57
+ * `set_provider` and `set_texts` (call it first: it rebuilds the component).
58
58
  */
59
59
  export function loadOpengrid(options = {}) {
60
60
  if (!loading) {
@@ -89,7 +89,7 @@ async function start({ moduleUrl, wasmUrl } = {}) {
89
89
  *
90
90
  * Not exported: `loadOpengrid` installs it when the module fails to load, and a
91
91
  * page that reaches for it directly is asking for the broken state on purpose
92
- * (plan point 39 — an export is a promise).
92
+ * (an export is a promise).
93
93
  *
94
94
  * @param {string} [name] the element to define.
95
95
  */
@@ -277,7 +277,7 @@ export function createWorkerProvider({
277
277
  * The grids on an engine provider's sources (issue #182).
278
278
  *
279
279
  * `watch(host)` is called by `set_provider`; the host is held weakly, so a
280
- * removed grid is still collected (point 74). Loading a source — under a new
280
+ * removed grid is still collected. Loading a source — under a new
281
281
  * name or over a loaded one, which replaces it — tells every watching grid on
282
282
  * that name with an `opengrid-source-replaced` event — it re-runs its query and
283
283
  * keeps its view.
@@ -311,6 +311,115 @@ function createWatchers() {
311
311
  };
312
312
  }
313
313
 
314
+ /**
315
+ * The grids a REST provider's source is shown in, and the server's stream that
316
+ * says it changed (issue #328): `GET /watch/{source}` with the token — fetch,
317
+ * not `EventSource`, which cannot send a header. The grid is told with a
318
+ * cancelable `opengrid-source-changed` on its element and decides what the
319
+ * reader sees; nothing is queried here. A cut stream is taken up again after
320
+ * the server's `retry` (at most 30 s, longer after each failure); an answer of
321
+ * 4xx ends it, since asking again would not change it.
322
+ */
323
+ function createChangeStream(endpoint, token) {
324
+ const hosts = new Set();
325
+ let controller = null;
326
+ let closed = false;
327
+
328
+ const alive = () => {
329
+ for (const ref of [...hosts]) {
330
+ if (!ref.deref()) {
331
+ hosts.delete(ref);
332
+ }
333
+ }
334
+ return [...hosts].map((ref) => ref.deref());
335
+ };
336
+
337
+ const tell = (name) => {
338
+ for (const host of alive()) {
339
+ host.dispatchEvent(
340
+ new CustomEvent("opengrid-source-changed", { detail: { name }, cancelable: true }),
341
+ );
342
+ }
343
+ };
344
+
345
+ async function run() {
346
+ let wait = 5000;
347
+ let failures = 0;
348
+ while (!closed && alive().length > 0) {
349
+ controller = new AbortController();
350
+ try {
351
+ const response = await fetch(endpoint, {
352
+ headers: { Accept: "text/event-stream", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
353
+ signal: controller.signal,
354
+ redirect: "error",
355
+ });
356
+ if (response.status >= 400 && response.status < 500) {
357
+ return;
358
+ }
359
+ if (!response.ok || !response.body) {
360
+ throw new Error(`status ${response.status}`);
361
+ }
362
+ failures = 0;
363
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
364
+ let buffer = "";
365
+ for (;;) {
366
+ const { value, done } = await reader.read();
367
+ if (done) {
368
+ break;
369
+ }
370
+ buffer += value;
371
+ let end;
372
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
373
+ const block = buffer.slice(0, end);
374
+ buffer = buffer.slice(end + 2);
375
+ const lines = block.split("\n");
376
+ const retry = lines.find((line) => line.startsWith("retry:"));
377
+ if (retry) {
378
+ wait = Number(retry.slice(6)) || wait;
379
+ }
380
+ if (lines.includes("event: changed")) {
381
+ const data = lines.find((line) => line.startsWith("data:"));
382
+ let name;
383
+ try {
384
+ name = JSON.parse(data.slice(5)).source;
385
+ } catch {
386
+ name = undefined;
387
+ }
388
+ tell(name);
389
+ }
390
+ }
391
+ }
392
+ } catch {
393
+ if (closed) {
394
+ return;
395
+ }
396
+ failures += 1;
397
+ }
398
+ await new Promise((resolve) => setTimeout(resolve, Math.min(30000, wait * 2 ** Math.min(failures, 3))));
399
+ }
400
+ controller = null;
401
+ }
402
+
403
+ return {
404
+ watch(host) {
405
+ for (const ref of hosts) {
406
+ if (ref.deref() === host) {
407
+ return;
408
+ }
409
+ }
410
+ hosts.add(new WeakRef(host));
411
+ if (!controller && !closed) {
412
+ controller = new AbortController();
413
+ run();
414
+ }
415
+ },
416
+ close() {
417
+ closed = true;
418
+ controller?.abort();
419
+ },
420
+ };
421
+ }
422
+
314
423
  /** Rows as the engine reads them: a JSON array of objects, as text. */
315
424
  function rowsJson(rows) {
316
425
  return typeof rows === "string" ? rows : JSON.stringify(rows);
@@ -319,7 +428,7 @@ function rowsJson(rows) {
319
428
  /**
320
429
  * A provider over an engine that is already initialised on the main thread.
321
430
  *
322
- * The fallback path of the elements (point 14): no worker, the same shape as
431
+ * The fallback path of the elements: no worker, the same shape as
323
432
  * `createWorkerProvider`, so a page can swap the two without changing the grid.
324
433
  *
325
434
  * @param {object} engine the loaded `Engine` from the engine module.
@@ -345,8 +454,9 @@ export function createLocalProvider(engine) {
345
454
  watch(host) {
346
455
  watchers.watch(host);
347
456
  },
457
+ /** The answer itself, or a promise of it while the collator loads (S4a). */
348
458
  execute(queryJson) {
349
- return engine.execute_columns(queryJson);
459
+ return withCollator(engine, queryJson, () => engine.execute_columns(queryJson));
350
460
  },
351
461
  /** What the engine holds (issue #70), as the worker provider says it. */
352
462
  async stats() {
@@ -361,14 +471,14 @@ export function createLocalProvider(engine) {
361
471
  }
362
472
 
363
473
  /**
364
- * A provider that talks to an `opengrid-server` over HTTP (plan point 27).
474
+ * A provider that talks to an `opengrid-server` over HTTP.
365
475
  *
366
476
  * The same shape as `createLocalProvider` and `createWorkerProvider`, so a page
367
477
  * swaps local for remote without touching the grid: `set_provider` sees one
368
478
  * `execute(queryJson)` either way. The difference is only where the work
369
479
  * happens — and that the answer can fail for reasons a local engine never has.
370
480
  *
371
- * The server's error form (point 23) is unwrapped here: a failed request
481
+ * The server's error form (docs/protocol.md, Errors) is unwrapped here: a failed request
372
482
  * rejects with the server's own sentence, so the grid's status line shows
373
483
  * "unknown source …" rather than "HTTP 404". The `Error` also carries the
374
484
  * HTTP `status` and the form's `code` and `path` (issue #16), so a page can
@@ -382,9 +492,9 @@ export function createLocalProvider(engine) {
382
492
  * @param {string} options.url base URL of the server, e.g. `http://127.0.0.1:8081`.
383
493
  * @param {string} options.source the configured data source name.
384
494
  * @param {string} [options.token] bearer token; the server refuses without one.
385
- * @returns {{execute: Function, describe: Function, export: Function}}
495
+ * @returns {{execute: Function, describe: Function, export: Function, exportPivot: Function}}
386
496
  */
387
- export function createRestProvider({ url, source, token } = {}) {
497
+ export function createRestProvider({ url, source, token, watch = false } = {}) {
388
498
  const base = String(url).replace(/\/$/, "");
389
499
  const endpoint = `${base}/query/${encodeURIComponent(source)}`;
390
500
  const headers = { "Content-Type": "application/json", Accept: ACCEPT_ANSWER };
@@ -393,14 +503,31 @@ export function createRestProvider({ url, source, token } = {}) {
393
503
  }
394
504
  // The export answers a file, CSV or JSON, whatever a query would.
395
505
  const { Accept: _answer, ...exportHeaders } = headers;
506
+ const changes = watch
507
+ ? createChangeStream(`${base}/watch/${encodeURIComponent(source)}`, token)
508
+ : null;
396
509
 
397
510
  return {
511
+ /**
512
+ * With `watch: true`, `set_provider` calls this: the grid hears
513
+ * `opengrid-source-changed` when the server says the source changed
514
+ * (issue #328). A page does not call it.
515
+ */
516
+ watch(host) {
517
+ changes?.watch(host);
518
+ },
519
+
520
+ /** Closes the change stream, if there is one. */
521
+ terminate() {
522
+ changes?.close();
523
+ },
524
+
398
525
  /** Where the queries run; the grid names it in its footer (issue #33). */
399
526
  kind: "remote",
400
527
  /**
401
528
  * What the server says this source is: `{ name, schema, capabilities }`.
402
529
  *
403
- * A planner needs both halves before it can split anything (point 28) — the
530
+ * A planner needs both halves before it can split anything — the
404
531
  * schema to validate against, the capabilities to know what may be pushed.
405
532
  * The schema is the one this token is allowed to see.
406
533
  */
@@ -447,7 +574,7 @@ export function createRestProvider({ url, source, token } = {}) {
447
574
  * and the CSV options (`delimiter`, `bom`, `protectFormulas`, `null`).
448
575
  * @returns {Promise<Blob>} `text/csv;charset=utf-8` or `application/json`.
449
576
  */
450
- async export(query, { format = "csv", signal, maxRows, onProgress, ...csv } = {}) {
577
+ async export(query, { format = "csv", signal, maxRows, onProgress, headers, ...csv } = {}) {
451
578
  for (const key of Object.keys(csv)) {
452
579
  if (!CSV_OPTIONS.includes(key)) {
453
580
  throw new TypeError(`export: unknown option "${key}"`);
@@ -461,6 +588,10 @@ export function createRestProvider({ url, source, token } = {}) {
461
588
  parameters.set(key, String(csv[key]));
462
589
  }
463
590
  }
591
+ // The header texts of CSV and XLSX, one parameter each (issue #353).
592
+ for (const [column, text] of Object.entries(headers ?? {})) {
593
+ parameters.set(`header.${column}`, text);
594
+ }
464
595
  const response = await fetch(`${base}/export/${encodeURIComponent(source)}?${parameters}`, {
465
596
  method: "POST",
466
597
  headers: exportHeaders,
@@ -493,9 +624,88 @@ export function createRestProvider({ url, source, token } = {}) {
493
624
  // The type `exportRows` gives its Blob, whatever the header's spelling.
494
625
  return new Blob([blob], { type: EXPORT_TYPES[format] ?? EXPORT_TYPES.csv });
495
626
  },
627
+
628
+ /** `POST /pivot/{source}?format=xlsx`: see {@link pivotWorkbook}. */
629
+ exportPivot(pivotQuery, options) {
630
+ return pivotWorkbook(`${base}/pivot/${encodeURIComponent(source)}`, exportHeaders, pivotQuery, options);
631
+ },
496
632
  };
497
633
  }
498
634
 
635
+ /**
636
+ * The texts a pivot's workbook is written in: the keys `set_texts` gives
637
+ * them, and the parameters `POST /pivot/{source}?format=xlsx` reads.
638
+ */
639
+ const PIVOT_TEXTS = ["noValue", "emptyValue", "total", "subtotal"];
640
+
641
+ /**
642
+ * What a calculated measure is shown as (issue #329), after `PIVOT_TEXTS` in
643
+ * the order `pivot_words` gives them. Sent only with a query that has one: a
644
+ * server from before calculated measures refuses a parameter it does not know.
645
+ */
646
+ const PIVOT_CALC_TEXTS = ["shareOfRow", "shareOfColumn", "shareOfTotal", "runningTotal"];
647
+
648
+ /**
649
+ * `POST /pivot/{source}?format=xlsx`: a pivot as an XLSX file, a `Blob`
650
+ * (issue #331) — what `exportPivot` of the REST and the pivot provider does.
651
+ *
652
+ * The server answers the pivot of `pivotQuery` as one flat sheet, the table a
653
+ * pivot's CSV is: one header row, every row with its subtotals and the grand
654
+ * total, numbers and dates as cells of their type. Its rules are `/pivot`'s —
655
+ * the token, `allowed_fields`, the mandatory row filter, the pivot's limits —
656
+ * and an export's: `max_xlsx_rows`, and a place among the running exports.
657
+ *
658
+ * `texts` are the words for a total and for a NULL or empty group, under the
659
+ * keys of {@link PIVOT_TEXTS}, and — for a query with a calculated measure —
660
+ * the words of {@link PIVOT_CALC_TEXTS}; any other key is ignored. `exportPivot` reads
661
+ * them from the element; a page that calls this method with a query of its
662
+ * own hands them over, or gets the server's English defaults.
663
+ *
664
+ * @param {string} endpoint `/pivot/{source}` of the server.
665
+ * @param {object} headers the provider's, without `Accept`.
666
+ * @param {object} pivotQuery the pivot query, as an object.
667
+ * @param {object} [options] `format` (`"xlsx"`), `texts`, `signal`.
668
+ * @returns {Promise<Blob>} the workbook.
669
+ */
670
+ async function pivotWorkbook(endpoint, headers, pivotQuery, options = {}) {
671
+ for (const key of Object.keys(options)) {
672
+ if (!PIVOT_EXPORT_OPTIONS.includes(key)) {
673
+ throw new TypeError(`exportPivot: unknown option "${key}"`);
674
+ }
675
+ }
676
+ const { format, texts, signal } = options;
677
+ if (format !== "xlsx") {
678
+ throw new TypeError(
679
+ `exportPivot: format is "xlsx", not ${JSON.stringify(format)} — a pivot's CSV is get_pivot(host)`,
680
+ );
681
+ }
682
+ const parameters = new URLSearchParams({ format });
683
+ const calculated = Array.isArray(pivotQuery?.values) && pivotQuery.values.some((value) => value?.calc);
684
+ for (const key of calculated ? [...PIVOT_TEXTS, ...PIVOT_CALC_TEXTS] : PIVOT_TEXTS) {
685
+ if (typeof texts?.[key] === "string") {
686
+ parameters.set(key, texts[key]);
687
+ }
688
+ }
689
+ const response = await fetch(`${endpoint}?${parameters}`, {
690
+ method: "POST",
691
+ headers,
692
+ body: JSON.stringify(pivotQuery),
693
+ signal,
694
+ redirect: "error",
695
+ });
696
+ if (!response.ok) {
697
+ throw refusal(await response.text(), response.status);
698
+ }
699
+ // A server from before this export ignores the parameter and answers the
700
+ // pivot itself: that is not a file to hand out under a workbook's name.
701
+ const type = (response.headers.get("Content-Type") ?? "").split(";")[0].trim().toLowerCase();
702
+ if (type !== EXPORT_TYPES.xlsx) {
703
+ await response.body?.cancel();
704
+ throw new Error("exportPivot: the server answered the pivot, not a workbook — it does not write a pivot as XLSX");
705
+ }
706
+ return new Blob([await response.blob()], { type: EXPORT_TYPES.xlsx });
707
+ }
708
+
499
709
  /**
500
710
  * What a provider asks the server for: the binary result form (E35), JSON as
501
711
  * the fallback — a server that does not know the form answers JSON, and
@@ -522,7 +732,7 @@ async function answerOf(response) {
522
732
  /**
523
733
  * A failed request as the `Error` it rejects with (issue #16). The message is
524
734
  * the server's own sentence, or the status when the body is not the error
525
- * form of point 23. The fields are what a page branches on without reading
735
+ * form of docs/protocol.md (Errors). The fields are what a page branches on without reading
526
736
  * the sentence: `status` always, `code` and `path` when the error form has
527
737
  * them.
528
738
  */
@@ -562,7 +772,7 @@ function coded(code, message) {
562
772
  }
563
773
 
564
774
  /**
565
- * A provider that asks an `opengrid-server` for a whole **pivot** (point 53).
775
+ * A provider that asks an `opengrid-server` for a whole **pivot**.
566
776
  *
567
777
  * The same shape as every other provider — `execute(json)` in, JSON out — so
568
778
  * `set_provider` is unchanged; only the endpoint and the body differ. What comes
@@ -573,7 +783,7 @@ function coded(code, message) {
573
783
  * @param {string} options.url base URL of the server.
574
784
  * @param {string} options.source the configured data source name.
575
785
  * @param {string} [options.token] bearer token.
576
- * @returns {{execute: Function}}
786
+ * @returns {{execute: Function, pivot: Function, exportPivot: Function}}
577
787
  */
578
788
  export function createPivotProvider({ url, source, token } = {}) {
579
789
  const endpoint = `${String(url).replace(/\/$/, "")}/pivot/${encodeURIComponent(source)}`;
@@ -593,6 +803,9 @@ export function createPivotProvider({ url, source, token } = {}) {
593
803
  return answerOf(response);
594
804
  }
595
805
 
806
+ // The export answers a file, whatever a pivot would.
807
+ const { Accept: _answer, ...exportHeaders } = headers;
808
+
596
809
  return {
597
810
  /** Where the queries run; the grid names it in its footer (issue #33). */
598
811
  kind: "remote",
@@ -600,12 +813,16 @@ export function createPivotProvider({ url, source, token } = {}) {
600
813
  // a page that called it before.
601
814
  execute: pivot,
602
815
  pivot,
816
+ /** `POST /pivot/{source}?format=xlsx`: see {@link pivotWorkbook}. */
817
+ exportPivot(pivotQuery, options) {
818
+ return pivotWorkbook(endpoint, exportHeaders, pivotQuery, options);
819
+ },
603
820
  };
604
821
  }
605
822
 
606
823
  /**
607
824
  * A provider that splits each query between a remote source and the engine in
608
- * this tab (plan point 28, plan/spezifikation/05-planner.md).
825
+ * this tab.
609
826
  *
610
827
  * Three steps, all of them JSON:
611
828
  *
@@ -649,10 +866,14 @@ export function createHybridProvider({ remote, planner, mode = "auto", onPlan }
649
866
  if (!plan.client) {
650
867
  return partial;
651
868
  }
652
- // The engine finishes in the form the source answered in.
653
- return typeof partial === "string"
654
- ? planner.finish(JSON.stringify(plan.client), partial)
655
- : planner.finish_columns(JSON.stringify(plan.client), partial);
869
+ // The engine finishes in the form the source answered in — with its
870
+ // collator, when the client's half sorts by a locale (S4a).
871
+ const client = JSON.stringify(plan.client);
872
+ return withCollator(planner, client, () =>
873
+ typeof partial === "string"
874
+ ? planner.finish(client, partial)
875
+ : planner.finish_columns(client, partial),
876
+ );
656
877
  },
657
878
  };
658
879
  }
@@ -664,8 +885,10 @@ const EXPORT_TYPES = {
664
885
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
665
886
  };
666
887
 
888
+ /** The options of `exportPivot`, the function and the providers' method. */
889
+ const PIVOT_EXPORT_OPTIONS = ["format", "texts", "signal"];
667
890
  /** The options of `exportRows` that are its own. */
668
- const EXPORT_OPTIONS = ["format", "chunkSize", "maxRows", "onProgress", "signal"];
891
+ const EXPORT_OPTIONS = ["format", "chunkSize", "maxRows", "onProgress", "signal", "headers"];
669
892
  /**
670
893
  * The options handed to `export_csv` — only these, whatever else is passed.
671
894
  * The same list as `CSV_OPTION_KEYS` in
@@ -678,7 +901,7 @@ const NO_ROWS = '{"total_count":0,"columns":[]}';
678
901
 
679
902
  /**
680
903
  * Every match of `query`, fetched through `provider` in pieces, as a `Blob` of
681
- * CSV or JSON (plan point 84).
904
+ * CSV or JSON.
682
905
  *
683
906
  * The browser half of exporting the view: `get_query(host)` says what the
684
907
  * reader sees, this fetches all of it and writes it in the notation the server
@@ -734,9 +957,10 @@ export async function exportRows(provider, query, options = {}) {
734
957
  const {
735
958
  format = "csv",
736
959
  chunkSize = 10_000,
737
- maxRows = 1_000_000,
960
+ maxRows: askedMaxRows,
738
961
  onProgress,
739
962
  signal,
963
+ headers,
740
964
  delimiter,
741
965
  bom,
742
966
  protectFormulas,
@@ -747,13 +971,11 @@ export async function exportRows(provider, query, options = {}) {
747
971
  `exportRows: format is "csv", "json" or "xlsx", not ${JSON.stringify(format)}`,
748
972
  );
749
973
  }
750
- if (format === "xlsx" && typeof provider?.export !== "function") {
751
- // An XLSX file is written on the server (issue #72); pieces fetched here
752
- // cannot become one.
753
- throw new TypeError(
754
- "exportRows: an XLSX export needs a provider that exports on the server (createRestProvider)",
755
- );
756
- }
974
+ // A workbook built in the tab is held whole in memory — about a kilobyte a row
975
+ // of five columns, a gigabyte at a million — so its default is lower than the
976
+ // server's, which streams to a file; asked for, it is the page's to raise.
977
+ const maxRows =
978
+ askedMaxRows ?? (format === "xlsx" && typeof provider?.export !== "function" ? XLSX_TAB_MAX_ROWS : 1_000_000);
757
979
  if (format !== "csv") {
758
980
  // A CSV option on another export would do nothing, and do it silently.
759
981
  const stray = CSV_OPTIONS.find((key) => options[key] !== undefined);
@@ -763,6 +985,18 @@ export async function exportRows(provider, query, options = {}) {
763
985
  );
764
986
  }
765
987
  }
988
+ if (headers !== undefined) {
989
+ if (format === "json") {
990
+ throw new TypeError("exportRows: headers name the header row, and a JSON export has none");
991
+ }
992
+ if (
993
+ headers === null ||
994
+ typeof headers !== "object" ||
995
+ Object.values(headers).some((text) => typeof text !== "string")
996
+ ) {
997
+ throw new TypeError("exportRows: headers is an object of texts, by column");
998
+ }
999
+ }
766
1000
  if (!Number.isSafeInteger(chunkSize) || chunkSize < 1) {
767
1001
  throw new TypeError("exportRows: chunkSize is a whole number of rows, at least 1");
768
1002
  }
@@ -788,18 +1022,23 @@ export async function exportRows(provider, query, options = {}) {
788
1022
  throw aborted();
789
1023
  }
790
1024
 
791
- const loaded = await loadOpengrid();
792
- if (loaded.fallback) {
793
- throw coded(
794
- "module_not_loaded",
795
- "exportRows: the WebAssembly module did not load, and the export notation is in it",
796
- );
1025
+ // The export notation of CSV and JSON is in the element module; a workbook
1026
+ // is written by a module of its own, loaded below when the pieces come.
1027
+ let module;
1028
+ if (format !== "xlsx") {
1029
+ const loaded = await loadOpengrid();
1030
+ if (loaded.fallback) {
1031
+ throw coded(
1032
+ "module_not_loaded",
1033
+ "exportRows: the WebAssembly module did not load, and the export notation is in it",
1034
+ );
1035
+ }
1036
+ module = loaded.module;
797
1037
  }
798
- const { module } = loaded;
799
1038
  const csvOptions = { delimiter, bom, protectFormulas, null: nullText };
800
1039
  if (format === "csv") {
801
1040
  // Read the options now: a wrong one should cost no request.
802
- module.export_csv(NO_ROWS, csvOptions, false);
1041
+ module.export_csv(NO_ROWS, csvOptions, false, headers);
803
1042
  }
804
1043
 
805
1044
  const sort = [...(query.sort ?? [])];
@@ -817,7 +1056,7 @@ export async function exportRows(provider, query, options = {}) {
817
1056
  const blob = await unlessAborted(
818
1057
  provider.export(
819
1058
  { ...query, sort },
820
- { format, signal, maxRows, onProgress, ...(format === "csv" ? csvOptions : {}) },
1059
+ { format, signal, maxRows, onProgress, headers, ...(format === "csv" ? csvOptions : {}) },
821
1060
  ),
822
1061
  signal,
823
1062
  );
@@ -828,61 +1067,125 @@ export async function exportRows(provider, query, options = {}) {
828
1067
  return blob;
829
1068
  }
830
1069
 
831
- // Each piece becomes a Blob of its own as soon as it is written, so its text
832
- // can leave the JS heap; the browser may keep a Blob's bytes elsewhere.
833
- const parts = format === "json" ? [new Blob(["["])] : [];
834
- let rows = 0;
835
- let total;
836
- for (;;) {
837
- if (signal?.aborted) {
838
- throw aborted();
839
- }
840
- // After the first piece nothing past `total` is asked for.
841
- const limit = total === undefined ? chunkSize : Math.min(chunkSize, total - rows);
842
- const piece = JSON.stringify({ ...query, sort, offset: rows, limit });
843
- const answer = await unlessAborted(ask(provider, piece, signal), signal);
844
- const result = countsOf(answer);
845
- const count = result.rows;
846
- const first = total === undefined;
847
- if (first) {
848
- total = result.total_count;
849
- if (total > maxRows) {
850
- throw coded(
851
- "too_many_rows",
852
- `exportRows: ${total} rows match, more than the ${maxRows} an export may have (maxRows)`,
1070
+ // A workbook is built in the tab's memory by the XLSX module, piece by piece,
1071
+ // and is the file at the end: there is no temporary file to stream to (#332).
1072
+ let book;
1073
+ try {
1074
+ return await fetchPieces();
1075
+ } finally {
1076
+ book?.free();
1077
+ }
1078
+
1079
+ async function fetchPieces() {
1080
+ // Each piece becomes a Blob of its own as soon as it is written, so its text
1081
+ // can leave the JS heap; the browser may keep a Blob's bytes elsewhere.
1082
+ const parts = format === "json" ? [new Blob(["["])] : [];
1083
+ let rows = 0;
1084
+ let total;
1085
+ for (;;) {
1086
+ if (signal?.aborted) {
1087
+ throw aborted();
1088
+ }
1089
+ // After the first piece nothing past `total` is asked for.
1090
+ const limit = total === undefined ? chunkSize : Math.min(chunkSize, total - rows);
1091
+ const piece = JSON.stringify({ ...query, sort, offset: rows, limit });
1092
+ const answer = await unlessAborted(ask(provider, piece, signal), signal);
1093
+ const result = countsOf(answer);
1094
+ const count = result.rows;
1095
+ const first = total === undefined;
1096
+ if (first) {
1097
+ total = result.total_count;
1098
+ if (total > maxRows) {
1099
+ throw coded(
1100
+ "too_many_rows",
1101
+ `exportRows: ${total} rows match, more than the ${maxRows} an export may have (maxRows)`,
1102
+ );
1103
+ }
1104
+ if (format === "xlsx" && total > XLSX_MAX_ROWS) {
1105
+ // Excel's limit is an error, never a shortened file — as on the server.
1106
+ throw coded(
1107
+ "too_many_rows",
1108
+ `exportRows: ${total} rows match, more than the ${XLSX_MAX_ROWS} an Excel sheet holds`,
1109
+ );
1110
+ }
1111
+ } else if (result.total_count !== total) {
1112
+ throw changed(`${total} rows matched at first, ${result.total_count} at row ${rows + 1}`);
1113
+ }
1114
+ if (count < limit && rows + count < total) {
1115
+ throw changed(`the rows ended at ${rows + count} of ${total}`);
1116
+ }
1117
+ if (format === "xlsx") {
1118
+ // After the checks above: a refused export does not load the module.
1119
+ if (!book) {
1120
+ book = new (await loadXlsx()).XlsxBook(sheetNameOf(query));
1121
+ if (headers) {
1122
+ book.headers(headers);
1123
+ }
1124
+ }
1125
+ book.add(answer);
1126
+ } else {
1127
+ parts.push(
1128
+ new Blob([
1129
+ format === "csv"
1130
+ ? module.export_csv(answer, csvOptions, first, headers)
1131
+ : // `first` here is "no row written yet", not "first piece": after an
1132
+ // empty first piece the next one still leads without a comma.
1133
+ module.export_json(answer, rows === 0),
1134
+ ]),
853
1135
  );
854
1136
  }
855
- } else if (result.total_count !== total) {
856
- throw changed(`${total} rows matched at first, ${result.total_count} at row ${rows + 1}`);
1137
+ rows += count;
1138
+ onProgress?.({ rows, total });
1139
+ if (rows >= total) {
1140
+ break;
1141
+ }
857
1142
  }
858
- if (count < limit && rows + count < total) {
859
- throw changed(`the rows ended at ${rows + count} of ${total}`);
1143
+ // An abort during the last `onProgress` still means no file.
1144
+ if (signal?.aborted) {
1145
+ throw aborted();
860
1146
  }
861
- parts.push(
862
- new Blob([
863
- format === "csv"
864
- ? module.export_csv(answer, csvOptions, first)
865
- : // `first` here is "no row written yet", not "first piece": after an
866
- // empty first piece the next one still leads without a comma.
867
- module.export_json(answer, rows === 0),
868
- ]),
869
- );
870
- rows += count;
871
- onProgress?.({ rows, total });
872
- if (rows >= total) {
873
- break;
1147
+ if (format === "xlsx") {
1148
+ return new Blob([book.finish()], { type: EXPORT_TYPES.xlsx });
874
1149
  }
1150
+ if (format === "json") {
1151
+ parts.push(new Blob(["]"]));
1152
+ }
1153
+ return new Blob(parts, { type: EXPORT_TYPES[format] });
875
1154
  }
876
- // An abort during the last `onProgress` still means no file.
877
- if (signal?.aborted) {
878
- throw aborted();
879
- }
880
- if (format === "json") {
881
- parts.push(new Blob(["]"]));
882
- }
883
- return new Blob(parts, {
884
- type: format === "csv" ? "text/csv;charset=utf-8" : "application/json",
1155
+ }
1156
+
1157
+ /** The most rows an Excel sheet holds, as `XLSX_MAX_ROWS` in `opengrid-export`. */
1158
+ const XLSX_MAX_ROWS = 1_048_575;
1159
+
1160
+ /** `maxRows` of a workbook written in the tab, unless the page says otherwise. */
1161
+ const XLSX_TAB_MAX_ROWS = 250_000;
1162
+
1163
+ /** The name of the workbook's sheet: the source, which the writer may refuse. */
1164
+ function sheetNameOf(query) {
1165
+ return typeof query.source === "string" && query.source !== "" ? query.source : "export";
1166
+ }
1167
+
1168
+ /**
1169
+ * The XLSX writer of the tab, loaded the first time a workbook is asked for and
1170
+ * kept: a module of its own (`xlsx/`, built by `just wasm-build-xlsx`), so a
1171
+ * page that never exports to Excel does not fetch it. A failed load is not
1172
+ * kept, so a later call tries again.
1173
+ */
1174
+ let xlsxModule;
1175
+ async function loadXlsx() {
1176
+ xlsxModule ??= import("./xlsx/opengrid_xlsx.js").then(async (glue) => {
1177
+ await glue.default();
1178
+ return glue;
885
1179
  });
1180
+ try {
1181
+ return await xlsxModule;
1182
+ } catch (error) {
1183
+ xlsxModule = undefined;
1184
+ throw coded(
1185
+ "module_not_loaded",
1186
+ `exportRows: the XLSX module did not load (${error?.message ?? error})`,
1187
+ );
1188
+ }
886
1189
  }
887
1190
 
888
1191
  /**
@@ -940,14 +1243,88 @@ function changed(detail) {
940
1243
  );
941
1244
  }
942
1245
 
1246
+ /**
1247
+ * The pivot `host` shows, as an XLSX file from the server (issue #331).
1248
+ *
1249
+ * `get_pivot` writes a pivot's CSV in the element, from the answer it holds.
1250
+ * A workbook is written by `opengrid-server`, so this asks the server for the
1251
+ * pivot again — the element's view as a pivot query, through the provider's
1252
+ * `exportPivot` — and gets the same table as one flat sheet: one header row,
1253
+ * every row with its subtotals and the grand total in the table's order,
1254
+ * numbers and dates as cells of their type. Folded groups are exported, as
1255
+ * in the CSV. If the data moved since the table was drawn, the file is the
1256
+ * newer answer.
1257
+ *
1258
+ * **Only a provider that exports on the server**: `createPivotProvider` and
1259
+ * `createRestProvider` have `exportPivot`. With any other provider — the
1260
+ * engine in the tab or in a worker — it is a `TypeError`, as an XLSX of
1261
+ * `exportRows` is there.
1262
+ *
1263
+ * **The words are the element's.** The totals and the NULL and empty groups
1264
+ * read as in the table: the element's texts as they are now — its defaults,
1265
+ * or what `set_texts` made of them — are read from it and sent along. The
1266
+ * page hands over nothing.
1267
+ *
1268
+ * @param {{exportPivot: Function}} provider the server-backed provider.
1269
+ * @param {HTMLElement} host an `<opengrid-pivot>`.
1270
+ * @param {object} options `format` (`"xlsx"`), `signal`.
1271
+ * @returns {Promise<Blob>} the workbook.
1272
+ */
1273
+ export async function exportPivot(provider, host, options = {}) {
1274
+ for (const key of Object.keys(options)) {
1275
+ // `texts` is the provider method's: here they are the element's.
1276
+ if (key === "texts" || !PIVOT_EXPORT_OPTIONS.includes(key)) {
1277
+ throw new TypeError(`exportPivot: unknown option "${key}"`);
1278
+ }
1279
+ }
1280
+ if (options.format !== "xlsx") {
1281
+ throw new TypeError(
1282
+ `exportPivot: format is "xlsx", not ${JSON.stringify(options.format)} — a pivot's CSV is get_pivot(host)`,
1283
+ );
1284
+ }
1285
+ if (typeof provider?.exportPivot !== "function") {
1286
+ // An XLSX file is written on the server; the pivot the element holds
1287
+ // cannot become one here.
1288
+ throw new TypeError(
1289
+ "exportPivot: an XLSX export needs a provider that exports on the server (createPivotProvider, createRestProvider)",
1290
+ );
1291
+ }
1292
+ if (options.signal?.aborted) {
1293
+ throw aborted();
1294
+ }
1295
+ const loaded = await loadOpengrid();
1296
+ if (loaded.fallback) {
1297
+ throw coded(
1298
+ "module_not_loaded",
1299
+ "exportPivot: the WebAssembly module did not load, and the pivot's view is read through it",
1300
+ );
1301
+ }
1302
+ const source = host?.getAttribute?.("datasource");
1303
+ const view = host?.localName === "opengrid-pivot" ? loaded.module.get_view(host) : null;
1304
+ if (!view || !source) {
1305
+ throw new TypeError("exportPivot: no pivot to export — an <opengrid-pivot> in the document, with a datasource");
1306
+ }
1307
+ // The request the element sends: `sort` and `filter` only when there is one.
1308
+ const query = { source, rows: view.rows, columns: view.columns, values: view.values };
1309
+ if (view.sort.length > 0) {
1310
+ query.sort = view.sort;
1311
+ }
1312
+ if (view.filter) {
1313
+ query.filter = view.filter;
1314
+ }
1315
+ // The element's words, in the order of `PIVOT_TEXTS` and `PIVOT_CALC_TEXTS`.
1316
+ const words = loaded.module.pivot_words(host);
1317
+ const texts = Object.fromEntries([...PIVOT_TEXTS, ...PIVOT_CALC_TEXTS].map((key, index) => [key, words[index]]));
1318
+ return provider.exportPivot(query, { ...options, texts });
1319
+ }
1320
+
943
1321
  /** What an aborted export rejects with, whatever reason `abort()` was given. */
944
1322
  function aborted() {
945
1323
  return new DOMException("The export was aborted.", "AbortError");
946
1324
  }
947
1325
 
948
1326
  /**
949
- * Supplies an element from one options object, and keeps it supplied (plan
950
- * point 76).
1327
+ * Supplies an element from one options object, and keeps it supplied.
951
1328
  *
952
1329
  * Every page — and every framework adapter — would otherwise have to know the
953
1330
  * rules of the module functions itself: wait for the module; set the texts
@@ -1019,6 +1396,7 @@ export function connect(host, options = {}) {
1019
1396
  ["opengrid-paste", (event) => current.onPaste?.(event.detail)],
1020
1397
  ["opengrid-bulk-change", (event) => current.onBulkChange?.(event.detail)],
1021
1398
  ["opengrid-row-action", (event) => current.onRowAction?.(event.detail)],
1399
+ ["opengrid-drill-down", (event) => current.onDrillDown?.(event.detail)],
1022
1400
  ["opengrid-source-replaced", (event) => current.onSourceReplaced?.(event.detail)],
1023
1401
  ];
1024
1402
  for (const [type, listener] of listeners) {
@@ -1137,6 +1515,18 @@ export function connect(host, options = {}) {
1137
1515
  const actions = changed.actions ?? [];
1138
1516
  write("actions", actions, stableKey(actions), (value) => module.set_actions(host, value));
1139
1517
  }
1518
+ if ("cellTemplates" in changed) {
1519
+ const cellTemplates = changed.cellTemplates ?? {};
1520
+ write("cellTemplates", cellTemplates, identityKey(cellTemplates), (value) =>
1521
+ module.set_cell_templates(host, value),
1522
+ );
1523
+ }
1524
+ if ("detailRenderer" in changed) {
1525
+ const detailRenderer = changed.detailRenderer ?? null;
1526
+ write("detailRenderer", detailRenderer, identityKey({ detailRenderer }), (value) =>
1527
+ module.set_detail_renderer(host, value),
1528
+ );
1529
+ }
1140
1530
  if ("validators" in changed) {
1141
1531
  const validators = changed.validators ?? {};
1142
1532
  write("validators", validators, identityKey(validators), (value) =>