@casoon/opengrid 0.15.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.
Files changed (32) hide show
  1. package/CHANGELOG.md +247 -1
  2. package/README.md +6 -4
  3. package/engine/opengrid_wasm_bg.wasm +0 -0
  4. package/loader.d.ts +390 -18
  5. package/loader.js +473 -90
  6. package/package.json +8 -1
  7. package/pkg/opengrid_web_components.d.ts +73 -7
  8. package/pkg/opengrid_web_components.js +339 -53
  9. package/pkg/opengrid_web_components_bg.wasm +0 -0
  10. package/pkg/opengrid_web_components_bg.wasm.d.ts +15 -6
  11. package/react/index.d.ts +8 -2
  12. package/react/index.js +9 -3
  13. package/svelte/Opengrid.svelte +7 -1
  14. package/svelte/OpengridGrid.svelte +5 -1
  15. package/svelte/OpengridPivot.svelte +3 -3
  16. package/svelte/OpengridTable.svelte +1 -1
  17. package/svelte/index.d.ts +12 -2
  18. package/svelte/index.js +1 -1
  19. package/texts/de.d.ts +5 -0
  20. package/texts/de.js +245 -0
  21. package/vue/index.d.ts +12 -2
  22. package/vue/index.js +10 -6
  23. package/worker.js +1 -2
  24. package/xlsx/opengrid_xlsx.d.ts +69 -0
  25. package/xlsx/opengrid_xlsx.js +375 -0
  26. package/xlsx/opengrid_xlsx_bg.wasm +0 -0
  27. package/xlsx/opengrid_xlsx_bg.wasm.d.ts +16 -0
  28. /package/pkg/snippets/{opengrid-web-components-ef3def04de0cb619 → opengrid-web-components-35ed06b453a9b215}/inline0.js +0 -0
  29. /package/pkg/snippets/{opengrid-web-components-ef3def04de0cb619 → opengrid-web-components-35ed06b453a9b215}/inline1.js +0 -0
  30. /package/pkg/snippets/{opengrid-web-core-78fdded9b8a374ed → opengrid-web-core-b41714d4e7311909}/inline0.js +0 -0
  31. /package/pkg/snippets/{opengrid-web-core-78fdded9b8a374ed → opengrid-web-core-b41714d4e7311909}/inline1.js +0 -0
  32. /package/pkg/snippets/{opengrid-web-core-78fdded9b8a374ed → opengrid-web-core-b41714d4e7311909}/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,7 +36,7 @@
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";
@@ -53,8 +52,7 @@ let loading;
53
52
  * @param {string} [options.wasmUrl] explicit `.wasm` URL, if it is not next to the glue.
54
53
  * @returns {Promise<{fallback: boolean, module?: object}>} whether the DOM fallback was
55
54
  * 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).
55
+ * `set_provider` and `set_texts` (call it first: it rebuilds the component).
58
56
  */
59
57
  export function loadOpengrid(options = {}) {
60
58
  if (!loading) {
@@ -89,7 +87,7 @@ async function start({ moduleUrl, wasmUrl } = {}) {
89
87
  *
90
88
  * Not exported: `loadOpengrid` installs it when the module fails to load, and a
91
89
  * page that reaches for it directly is asking for the broken state on purpose
92
- * (plan point 39 — an export is a promise).
90
+ * (an export is a promise).
93
91
  *
94
92
  * @param {string} [name] the element to define.
95
93
  */
@@ -277,7 +275,7 @@ export function createWorkerProvider({
277
275
  * The grids on an engine provider's sources (issue #182).
278
276
  *
279
277
  * `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
278
+ * removed grid is still collected. Loading a source — under a new
281
279
  * name or over a loaded one, which replaces it — tells every watching grid on
282
280
  * that name with an `opengrid-source-replaced` event — it re-runs its query and
283
281
  * keeps its view.
@@ -311,6 +309,115 @@ function createWatchers() {
311
309
  };
312
310
  }
313
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
+
314
421
  /** Rows as the engine reads them: a JSON array of objects, as text. */
315
422
  function rowsJson(rows) {
316
423
  return typeof rows === "string" ? rows : JSON.stringify(rows);
@@ -319,7 +426,7 @@ function rowsJson(rows) {
319
426
  /**
320
427
  * A provider over an engine that is already initialised on the main thread.
321
428
  *
322
- * The fallback path of the elements (point 14): no worker, the same shape as
429
+ * The fallback path of the elements: no worker, the same shape as
323
430
  * `createWorkerProvider`, so a page can swap the two without changing the grid.
324
431
  *
325
432
  * @param {object} engine the loaded `Engine` from the engine module.
@@ -361,14 +468,14 @@ export function createLocalProvider(engine) {
361
468
  }
362
469
 
363
470
  /**
364
- * A provider that talks to an `opengrid-server` over HTTP (plan point 27).
471
+ * A provider that talks to an `opengrid-server` over HTTP.
365
472
  *
366
473
  * The same shape as `createLocalProvider` and `createWorkerProvider`, so a page
367
474
  * swaps local for remote without touching the grid: `set_provider` sees one
368
475
  * `execute(queryJson)` either way. The difference is only where the work
369
476
  * happens — and that the answer can fail for reasons a local engine never has.
370
477
  *
371
- * The server's error form (point 23) is unwrapped here: a failed request
478
+ * The server's error form (docs/protocol.md, Errors) is unwrapped here: a failed request
372
479
  * rejects with the server's own sentence, so the grid's status line shows
373
480
  * "unknown source …" rather than "HTTP 404". The `Error` also carries the
374
481
  * HTTP `status` and the form's `code` and `path` (issue #16), so a page can
@@ -382,9 +489,9 @@ export function createLocalProvider(engine) {
382
489
  * @param {string} options.url base URL of the server, e.g. `http://127.0.0.1:8081`.
383
490
  * @param {string} options.source the configured data source name.
384
491
  * @param {string} [options.token] bearer token; the server refuses without one.
385
- * @returns {{execute: Function, describe: Function, export: Function}}
492
+ * @returns {{execute: Function, describe: Function, export: Function, exportPivot: Function}}
386
493
  */
387
- export function createRestProvider({ url, source, token } = {}) {
494
+ export function createRestProvider({ url, source, token, watch = false } = {}) {
388
495
  const base = String(url).replace(/\/$/, "");
389
496
  const endpoint = `${base}/query/${encodeURIComponent(source)}`;
390
497
  const headers = { "Content-Type": "application/json", Accept: ACCEPT_ANSWER };
@@ -393,14 +500,31 @@ export function createRestProvider({ url, source, token } = {}) {
393
500
  }
394
501
  // The export answers a file, CSV or JSON, whatever a query would.
395
502
  const { Accept: _answer, ...exportHeaders } = headers;
503
+ const changes = watch
504
+ ? createChangeStream(`${base}/watch/${encodeURIComponent(source)}`, token)
505
+ : null;
396
506
 
397
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
+
398
522
  /** Where the queries run; the grid names it in its footer (issue #33). */
399
523
  kind: "remote",
400
524
  /**
401
525
  * What the server says this source is: `{ name, schema, capabilities }`.
402
526
  *
403
- * A planner needs both halves before it can split anything (point 28) — the
527
+ * A planner needs both halves before it can split anything — the
404
528
  * schema to validate against, the capabilities to know what may be pushed.
405
529
  * The schema is the one this token is allowed to see.
406
530
  */
@@ -447,7 +571,7 @@ export function createRestProvider({ url, source, token } = {}) {
447
571
  * and the CSV options (`delimiter`, `bom`, `protectFormulas`, `null`).
448
572
  * @returns {Promise<Blob>} `text/csv;charset=utf-8` or `application/json`.
449
573
  */
450
- async export(query, { format = "csv", signal, maxRows, onProgress, ...csv } = {}) {
574
+ async export(query, { format = "csv", signal, maxRows, onProgress, headers, ...csv } = {}) {
451
575
  for (const key of Object.keys(csv)) {
452
576
  if (!CSV_OPTIONS.includes(key)) {
453
577
  throw new TypeError(`export: unknown option "${key}"`);
@@ -461,6 +585,10 @@ export function createRestProvider({ url, source, token } = {}) {
461
585
  parameters.set(key, String(csv[key]));
462
586
  }
463
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
+ }
464
592
  const response = await fetch(`${base}/export/${encodeURIComponent(source)}?${parameters}`, {
465
593
  method: "POST",
466
594
  headers: exportHeaders,
@@ -493,9 +621,88 @@ export function createRestProvider({ url, source, token } = {}) {
493
621
  // The type `exportRows` gives its Blob, whatever the header's spelling.
494
622
  return new Blob([blob], { type: EXPORT_TYPES[format] ?? EXPORT_TYPES.csv });
495
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
+ },
496
629
  };
497
630
  }
498
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
+
499
706
  /**
500
707
  * What a provider asks the server for: the binary result form (E35), JSON as
501
708
  * the fallback — a server that does not know the form answers JSON, and
@@ -522,7 +729,7 @@ async function answerOf(response) {
522
729
  /**
523
730
  * A failed request as the `Error` it rejects with (issue #16). The message is
524
731
  * 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
732
+ * form of docs/protocol.md (Errors). The fields are what a page branches on without reading
526
733
  * the sentence: `status` always, `code` and `path` when the error form has
527
734
  * them.
528
735
  */
@@ -562,7 +769,7 @@ function coded(code, message) {
562
769
  }
563
770
 
564
771
  /**
565
- * A provider that asks an `opengrid-server` for a whole **pivot** (point 53).
772
+ * A provider that asks an `opengrid-server` for a whole **pivot**.
566
773
  *
567
774
  * The same shape as every other provider — `execute(json)` in, JSON out — so
568
775
  * `set_provider` is unchanged; only the endpoint and the body differ. What comes
@@ -573,7 +780,7 @@ function coded(code, message) {
573
780
  * @param {string} options.url base URL of the server.
574
781
  * @param {string} options.source the configured data source name.
575
782
  * @param {string} [options.token] bearer token.
576
- * @returns {{execute: Function}}
783
+ * @returns {{execute: Function, pivot: Function, exportPivot: Function}}
577
784
  */
578
785
  export function createPivotProvider({ url, source, token } = {}) {
579
786
  const endpoint = `${String(url).replace(/\/$/, "")}/pivot/${encodeURIComponent(source)}`;
@@ -593,6 +800,9 @@ export function createPivotProvider({ url, source, token } = {}) {
593
800
  return answerOf(response);
594
801
  }
595
802
 
803
+ // The export answers a file, whatever a pivot would.
804
+ const { Accept: _answer, ...exportHeaders } = headers;
805
+
596
806
  return {
597
807
  /** Where the queries run; the grid names it in its footer (issue #33). */
598
808
  kind: "remote",
@@ -600,12 +810,16 @@ export function createPivotProvider({ url, source, token } = {}) {
600
810
  // a page that called it before.
601
811
  execute: pivot,
602
812
  pivot,
813
+ /** `POST /pivot/{source}?format=xlsx`: see {@link pivotWorkbook}. */
814
+ exportPivot(pivotQuery, options) {
815
+ return pivotWorkbook(endpoint, exportHeaders, pivotQuery, options);
816
+ },
603
817
  };
604
818
  }
605
819
 
606
820
  /**
607
821
  * 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).
822
+ * this tab.
609
823
  *
610
824
  * Three steps, all of them JSON:
611
825
  *
@@ -664,8 +878,10 @@ const EXPORT_TYPES = {
664
878
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
665
879
  };
666
880
 
881
+ /** The options of `exportPivot`, the function and the providers' method. */
882
+ const PIVOT_EXPORT_OPTIONS = ["format", "texts", "signal"];
667
883
  /** The options of `exportRows` that are its own. */
668
- const EXPORT_OPTIONS = ["format", "chunkSize", "maxRows", "onProgress", "signal"];
884
+ const EXPORT_OPTIONS = ["format", "chunkSize", "maxRows", "onProgress", "signal", "headers"];
669
885
  /**
670
886
  * The options handed to `export_csv` — only these, whatever else is passed.
671
887
  * The same list as `CSV_OPTION_KEYS` in
@@ -678,7 +894,7 @@ const NO_ROWS = '{"total_count":0,"columns":[]}';
678
894
 
679
895
  /**
680
896
  * Every match of `query`, fetched through `provider` in pieces, as a `Blob` of
681
- * CSV or JSON (plan point 84).
897
+ * CSV or JSON.
682
898
  *
683
899
  * The browser half of exporting the view: `get_query(host)` says what the
684
900
  * reader sees, this fetches all of it and writes it in the notation the server
@@ -734,9 +950,10 @@ export async function exportRows(provider, query, options = {}) {
734
950
  const {
735
951
  format = "csv",
736
952
  chunkSize = 10_000,
737
- maxRows = 1_000_000,
953
+ maxRows: askedMaxRows,
738
954
  onProgress,
739
955
  signal,
956
+ headers,
740
957
  delimiter,
741
958
  bom,
742
959
  protectFormulas,
@@ -747,13 +964,11 @@ export async function exportRows(provider, query, options = {}) {
747
964
  `exportRows: format is "csv", "json" or "xlsx", not ${JSON.stringify(format)}`,
748
965
  );
749
966
  }
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
- }
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);
757
972
  if (format !== "csv") {
758
973
  // A CSV option on another export would do nothing, and do it silently.
759
974
  const stray = CSV_OPTIONS.find((key) => options[key] !== undefined);
@@ -763,6 +978,18 @@ export async function exportRows(provider, query, options = {}) {
763
978
  );
764
979
  }
765
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
+ }
766
993
  if (!Number.isSafeInteger(chunkSize) || chunkSize < 1) {
767
994
  throw new TypeError("exportRows: chunkSize is a whole number of rows, at least 1");
768
995
  }
@@ -788,18 +1015,23 @@ export async function exportRows(provider, query, options = {}) {
788
1015
  throw aborted();
789
1016
  }
790
1017
 
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
- );
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;
797
1030
  }
798
- const { module } = loaded;
799
1031
  const csvOptions = { delimiter, bom, protectFormulas, null: nullText };
800
1032
  if (format === "csv") {
801
1033
  // Read the options now: a wrong one should cost no request.
802
- module.export_csv(NO_ROWS, csvOptions, false);
1034
+ module.export_csv(NO_ROWS, csvOptions, false, headers);
803
1035
  }
804
1036
 
805
1037
  const sort = [...(query.sort ?? [])];
@@ -817,7 +1049,7 @@ export async function exportRows(provider, query, options = {}) {
817
1049
  const blob = await unlessAborted(
818
1050
  provider.export(
819
1051
  { ...query, sort },
820
- { format, signal, maxRows, onProgress, ...(format === "csv" ? csvOptions : {}) },
1052
+ { format, signal, maxRows, onProgress, headers, ...(format === "csv" ? csvOptions : {}) },
821
1053
  ),
822
1054
  signal,
823
1055
  );
@@ -828,61 +1060,125 @@ export async function exportRows(provider, query, options = {}) {
828
1060
  return blob;
829
1061
  }
830
1062
 
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)`,
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
+ ]),
853
1128
  );
854
1129
  }
855
- } else if (result.total_count !== total) {
856
- throw changed(`${total} rows matched at first, ${result.total_count} at row ${rows + 1}`);
1130
+ rows += count;
1131
+ onProgress?.({ rows, total });
1132
+ if (rows >= total) {
1133
+ break;
1134
+ }
857
1135
  }
858
- if (count < limit && rows + count < total) {
859
- throw changed(`the rows ended at ${rows + count} of ${total}`);
1136
+ // An abort during the last `onProgress` still means no file.
1137
+ if (signal?.aborted) {
1138
+ throw aborted();
860
1139
  }
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;
1140
+ if (format === "xlsx") {
1141
+ return new Blob([book.finish()], { type: EXPORT_TYPES.xlsx });
874
1142
  }
1143
+ if (format === "json") {
1144
+ parts.push(new Blob(["]"]));
1145
+ }
1146
+ return new Blob(parts, { type: EXPORT_TYPES[format] });
875
1147
  }
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",
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;
885
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
+ }
886
1182
  }
887
1183
 
888
1184
  /**
@@ -940,14 +1236,88 @@ function changed(detail) {
940
1236
  );
941
1237
  }
942
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
+
943
1314
  /** What an aborted export rejects with, whatever reason `abort()` was given. */
944
1315
  function aborted() {
945
1316
  return new DOMException("The export was aborted.", "AbortError");
946
1317
  }
947
1318
 
948
1319
  /**
949
- * Supplies an element from one options object, and keeps it supplied (plan
950
- * point 76).
1320
+ * Supplies an element from one options object, and keeps it supplied.
951
1321
  *
952
1322
  * Every page — and every framework adapter — would otherwise have to know the
953
1323
  * rules of the module functions itself: wait for the module; set the texts
@@ -1019,6 +1389,7 @@ export function connect(host, options = {}) {
1019
1389
  ["opengrid-paste", (event) => current.onPaste?.(event.detail)],
1020
1390
  ["opengrid-bulk-change", (event) => current.onBulkChange?.(event.detail)],
1021
1391
  ["opengrid-row-action", (event) => current.onRowAction?.(event.detail)],
1392
+ ["opengrid-drill-down", (event) => current.onDrillDown?.(event.detail)],
1022
1393
  ["opengrid-source-replaced", (event) => current.onSourceReplaced?.(event.detail)],
1023
1394
  ];
1024
1395
  for (const [type, listener] of listeners) {
@@ -1137,6 +1508,18 @@ export function connect(host, options = {}) {
1137
1508
  const actions = changed.actions ?? [];
1138
1509
  write("actions", actions, stableKey(actions), (value) => module.set_actions(host, value));
1139
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
+ }
1140
1523
  if ("validators" in changed) {
1141
1524
  const validators = changed.validators ?? {};
1142
1525
  write("validators", validators, identityKey(validators), (value) =>